text:
Q: Python 3 Print Update on multiple lines Is it possible to print and update more than one line?
This works for one line:
print ("Orders: " + str(OrderCount) + " Operations: " + str(OperationCount), end="\r")

and get this: (Of course the numbers update because its in a loop)
Orders: 25 Operations: 300

I have tried this:
print ("Orders: " + str(OrderCount) + "\rOperations: " + str(OperationCount), end="\r\r")

and get this: (The number does update correctly)
Operations: 300

Looking for two lines that are updated like:
Orders: 25
Operations: 300

and not:
Orders: 23
Operations: 298

Orders: 24
Operations: 299

Orders: 25
Operations: 300

A: \r is a carriage return, where the cursor moves to the start of the line (column 0). From there, writing more text will overwrite what was written before, so you end up only with the last line (which is long enough to overwrite everything you've written before).
You want \n, a newline, which moves to the next line (and starts at column 0 again):
print("Orders: " + str(OrderCount) + "\nOperations: " + str(OperationCount), end="\n\n")

Rather than use str() and + concatenation, consider using string templating with str.format():
print("Orders: {}\nOperations: {}\n".format(OrderCount, OperationCount))

or a formatted string literal:
print(f"Orders: {OrderCount}\nOperations: {OperationCount}\n")

If you wanted to use \r carriage returns to update two lines, you could use ANSI control codes; printing \x1B[2A (ESC [ 2 A) moves the cursor up 2 times, adjust the number as needed. Whether or not this works depends on what platform you are supporting.
On my Mac, the following demo works and updates the two lines with random numbers; I used the ESC [ 0 K to make sure any remaining characters on the line are erased:
import random, time

orders = 0
operations = 0

UP = "\x1B[3A"
CLR = "\x1B[0K"
print("\n\n")  # set up blank lines so cursor moves work
while True:
   orders += random.randrange(1, 3)
   operations += random.randrange(2, 10)

   print(f"{UP}Orders: {orders}{CLR}\nOperations: {operations}{CLR}\n")

   time.sleep(random.uniform(0.5, 2))

Demo:

You could also switch to a full-terminal control with Curses or stick to putting everything on one line. If you are going to go the Curses route, take into account that Windows compatibility is sketchy at best.

A: You probably want \n instead of \r. \r is "carriage return", a.k.a. "go back to the beginning of the line" -- so you're print "Operations" over "Orders".


text:
Q: android: no such instance field I'm trying to get data thru AsyncTask with web service.
I have no idea why as I declared global variable 'arrayList1' and it has been initialized, but I'm getting error for the 'arrayList1' and it skipped doin the new AsyncTask.
private Context mContext;
private ArrayList arrayList1;
private ArrayList<List> mData;
private ListView mListView;
private ListViewAdapter mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

mContext = getApplicationContext();
mListView = (ListView)findViewById(R.id.listView1);
mData = new ArrayList<List>();
mData = LoadListView();
}

public ArrayList<List> LoadListView(Void...params) {
    arrayList1 = new ArrayList();
    //here error occurred.
    new AsyncTask<Void, Void, ArrayList<List>>() {
        @Override
        protected ArrayList<List> doInBackground(Void...params) {
            arrayList1 = GetData();
            //GetData() is another function will return a arraylist from web service.
            return arrayList1;
        }

        @Override
        protected void onPostExecute(ArrayList<List> arrayList) {
            mAdapter = new ListViewAdapter(arrayList, mContext);
            mAdapter.notifyDataSetChanged();
            mListView.setAdapter(mAdapter);
        }
    }.execute((Void[]) params); //error occurred skipped directly to here.

    return arrayList1;
}

A: If you're using proGuard make sure to check minifyEnabled and shrinkResources in your gradle to find a solution

A: No need to send void parameter.
.execute();

A: I guess you are creating two different object's in one reference, try this code:
private Context mContext;
private ArrayList<List> mData;
private ListView mListView;
private ListViewAdapter mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mContext = getApplicationContext();
    mListView = (ListView)findViewById(R.id.listView1);
    mData = new ArrayList<List>();
    LoadListView();
}

public void LoadListView(Void...params) {

    //here error occurred.
    new AsyncTask<Void, Void, ArrayList<List>>() {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected ArrayList<List> doInBackground(Void...params) {
            mData.clear();
            mData.addAll(GetData());
            //GetData() is another function will return a arraylist from web service.
            return mData;
        }

        @Override
        protected void onPostExecute(ArrayList<List> arrayList) {
            mAdapter = new ListViewAdapter(arrayList, mContext);
            mAdapter.notifyDataSetChanged();
            mListView.setAdapter(mAdapter);
        }
    }.execute((Void[]) params); //error occurred skipped directly to here.

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't connect to MySQL with C++ Hello I've been trying to connect a MySQL database with C++ program but every time I try to connect I get error code 0, could someone help me or tell me what am I doing wrong?
Here's my complete code:
#include <iostream>
#include <mysql/mysql.h>
#include <stdio.h>

#define SERVER "localhost"
#define USER "user"
#define PASS "password"
#define DATABASE "database"

int main(){

 MYSQL *connect = mysql_init(NULL);

 if(!connect){
  std::cout<<"MySQL could not connect\n";
  return 1;
 }

 connect = mysql_real_connect(connect, SERVER, USER, PASS, DATABASE, 3306, NULL,0);

 if(connect){
  std::cout<<"CONNECTION SUCCESS"<<std::endl;
 }else{
  std::cout<<"CONNECTION FAILED ERROR CODE: "<<mysql_errno(connect)<<std::endl;
 }

 return 0;
}

(Yes I've already started the server I guess, and created a specific user for the program)
The output I get is:

CONNECTION FAILED ERROR: 0

A: Try using this code instead (you will need Connector/C++):
/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>

/*
  Include directly the different
  headers from cppconn/ and mysql_driver.h + mysql_util.h
  (and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"

#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>

using namespace std;

int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Hello World!' »
   AS _message'..." << endl;

try {
  sql::Driver *driver;
  sql::Connection *con;
  sql::Statement *stmt;
  sql::ResultSet *res;

  /* Create a connection */
  driver = get_driver_instance();
  con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
  /* Connect to the MySQL test database */
  con->setSchema("test");

  stmt = con->createStatement();
  res = stmt->executeQuery("SELECT 'Hello World!' AS _message");
  while (res->next()) {
    cout << "\t... MySQL replies: ";
    /* Access column data by alias or column name */
    cout << res->getString("_message") << endl;
    cout << "\t... MySQL says it again: ";
    /* Access column data by numeric offset, 1 is the first column */
    cout << res->getString(1) << endl;
  }
  delete res;
  delete stmt;
  delete con;

} catch (sql::SQLException &e) {
  cout << "# ERR: SQLException in " << __FILE__;
  cout << "(" << __FUNCTION__ << ") on line " »
     << __LINE__ << endl;
  cout << "# ERR: " << e.what();
  cout << " (MySQL error code: " << e.getErrorCode();
  cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}

cout << endl;

return EXIT_SUCCESS;
}


text:
Q: Website is not loading without https://www I have developed a website and deployed it via Google App Engine. But when I open the website with full url let's say "https://www.website.com" it opens but when I type "website.com" in url section of the browser it doesn't opens and says the site is not secure. How can I resolve this?

A: It looks like a couple of things are happening

*

*If you just type in 'website.com', the browser will try to open 'http://website.com' (note there is no subdomain -www i.e. you are using the naked domain) unless you have done a redirection to 'www' in which case, you will get 'http://www.website.com'

*If you have specified 'secure' always in your 'app.yaml' file, then GAE will redirect the 'http' to 'https'

*It seems like
a) You have specified 'secure always' in your app.yaml file
b) You are not redirecting naked domain to sub-domain
c) You have mapped the sub domain, 'www' to your GAE appspot domain. You have not mapped the naked domain
Solution

*

*Map both naked and subdomain (www) of your custom domain to your appspot.com urls

*Enable SSL for both mappings

A: The browser will give you a not secure message but it will also allow you to "proceed with risk".
For example, take a look at this image:
chrome screenshot ssl warning
Click on Advanced >> Proceed to website name (unsafe). This will take you to the website.
Basically, the original problem is that your website is not redirecting to https when someone lands on the http page.
Follow this tutorial here to do so:
https://cloud.google.com/appengine/docs/standard/nodejs/application-security
Edit 1
I have just read your question again. I think your website does redirect from http to https but the problem is that the SSL certificate attached to this website is invalid. You need to have a good SSL certificate; one which has not expired.


text:
Q: point inside a triangle I wanted to ask you if anyone knew how to check if a point was inside a given triangle, on a reference system in space.
I am aware that speaking of 2d systems I can obtain this point with the following procedures:
To determine if a given point v lies within a given triangle, consider a single vertex, denoted v0, v1 and v2 are the vectors from the other two vertices v0. Expressing the vector from v0 to v in terms of v1 and v2 then gives
v = v0 + av1 + bv2
where a, b are constant. Solve for a, b
a= (det (v v2) - det (v0 v2)) / (det (v1 v2))
b=  - (det (v v1) - det (v0 v1)) / (det (v1 v2))
So the point v is inside the triangle if a, b> 0 e a + b <1.
I was wondering if there was a similar procedure or not.
After MBo's advice I wrote the following code:
    def pointLocatedOnTheTriangularFace(self, point):
    vertList = list(self.vertices)
    system = []
    for i in range(4):
        p = vertList[1].coords-vertList[0].coords
        q = vertList[2].coords-vertList[0].coords
        n = np.cross(p,q)
        for i in range(3):
            system.append([p[i],q[i],n[i]])
        try:
            solution = list(np.linalg.solve(system,np.array(point-vertList[0].coords)))
            if solution[0] > 0 and solution[1] > 0 and solution[0]+solution[1]<1 and solution[2]==0:
                return True
        except np.linalg.LinAlgError:
            print("The system having the floor {0} {1} {2} with the point {3} does not admit solutions.\n".format(vertList[0].coords,vertList[1].coords,vertList[2].coords,point))
        v = vertList.pop(0)
        vertList.append(v)
    return False

I am working with tetrahedra, and the triangles that interest me are the faces of the tetrahedron. I state that it does not work but I can not understand why. Can anyone tell me what am I doing wrong?
I changed the code in the following way and it seems to work.
def pointLocatedOnTheTriangularFace(self, point):
    vertList = list(self.vertices)
    system = []
    for i in range(4):
        r = point-vertList[0].coords
        p = vertList[1].coords-vertList[0].coords
        q = vertList[2].coords-vertList[0].coords
        n = np.cross(p,q)
        if np.inner(r,n) == 0:
            system = [[p[0],q[0]],[p[1],q[1]]]
            try:
                solution = list(np.linalg.solve(system,np.array([r[0],r[1]])))
                if solution[0] > 0 and solution[1] > 0 and solution[0]+solution[1]<1:
                    return True
            except np.linalg.LinAlgError:
                print("The system having the floor {0} {1} {2} with the point {3} does not admit solutions.\n".format(vertList[0].coords,vertList[1].coords,vertList[2].coords,point))
        v = vertList.pop(0)
        vertList.append(v)
    return False

With the following tests:
def test_PointPlacedOnTheTriangularFace(self):
    tr1Vertices = [vertex([0,4.32978e-17,0.5],1),vertex([-0.433013,0.25,-0.5],2),vertex([-4.32978e-17,-0.5,-0.5],3),vertex([0.433013,0.25,-0.5],4)]
    tr1= tetrahedron(tr1Vertices)
    point = vertex([0,0,-0.5],1)
    self.assertTrue(tr1.pointLocatedOnTheTriangularFace(point.coords), msg="In this test the point is inside the face")

def test_PointNotPlacedLocatedOnTheTriangularFace(self):
    tr1Vertices = [vertex([0,4.32978e-17,0.5],1),vertex([-0.433013,0.25,-0.5],2),vertex([-4.32978e-17,-0.5,-0.5],3),vertex([0.433013,0.25,-0.5],4)]
    tr1= tetrahedron(tr1Vertices)
    point = vertex([1,0,-0.5],1)
    self.assertFalse(tr1.pointLocatedOnTheTriangularFace(point.coords), msg="In this test the point is outside the face")

If anyone has any advice for me I will surely treasure it. Thanks.

A: Described 2D approach is essentially decomposition of vector r = v-v0 by basis vectors p=v1-v0 and q=v2-v0.
In 3D you can decompose vector r by vectors p, q and n = p x q (where x denotes vector product operation)
If resulting coefficients a,b,c fulfill limits a, b > 0, a + b < 1, c=0, then point v lies in triangle plane inside it.
For decomposition solve this linear system for unknowns a,b,c:
rx = a * px + b * qx + c * nx
ry = a * py + b * qy + c * ny
rz = a * pz + b * qz + c * nz

Alternative approach - check that dot product r.dot.n is zero - in this case point lies in the plane, coefficient с is zero, and you can solve simplified system for a and b  choosing a pair of equations and excluding the third summand (same method as in 2D)


text:
Q: c# serialization - same input producing completely different results? My program is serializing a class and is sending it over the network and being received on the other end. When the receiving server gets the byte array and tries to deserialize it, it causes an error. When I try to compare the data sent originally to newly generated data on the server (using the same functions on the same class, ex: trying to see if the same function on the server produces the same result), the result is completely different.
How is this possible?
I cannot seem to figure this out.
public static byte[] ObjectToByteArray(object obj)
    {
        if (obj == null)
            return null;

        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream ms = new MemoryStream();
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }

    private static Object ByteArrayToObject(byte[] arrBytes)
    {
        MemoryStream memStream = new MemoryStream();
        BinaryFormatter binForm = new BinaryFormatter();
        memStream.Write(arrBytes, 0, arrBytes.Length);
        memStream.Seek(0, SeekOrigin.Begin);
        Object obj = binForm.Deserialize(memStream);
        return obj;
    }

And this is the class I am using for the serialization:
[Serializable]
public class NetworkObject
{
    public NetObjectType requestType;

    public NetworkObject(NetObjectType type)
    {
        requestType = type;
    }
}

EDIT:
Here is the error thrown:

at System.Runtime.Serialization.Formatters.Binary.BinaryAssemblyInfo.GetAssembly()
     at System.Runtime.Serialization.Formatters.Binary.ObjectReader.GetType(BinaryAssemblyInfo assemblyInfo, String name)
     at System.Runtime.Serialization.Formatters.Binary.ObjectMap..ctor(String objectName, String[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, Object[] typeInformationA, Int32[] memberAssemIds, ObjectReader objectReader, Int32 objectId, BinaryAssemblyInfo assemblyInfo, SizedArray assemIdToAssemblyTable)
     at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryObjectWithMapTyped record)
     at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryHeaderEnum binaryHeaderEnum)
     at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()
     at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
     at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
     at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream)
     at Matchmaker.Net.Network.SocketManager.ByteArrayToObject(Byte[] arrBytes) in X:\Programming\VS\matchmake .net\matchmaker.net\matchmaker.net\Matchmaker\Network\SocketManager.cs:line 220
     at Matchmaker.Net.Network.SocketManager.readAsyncBytes(IAsyncResult result) in X:\Programming\VS\matchmake .net\matchmaker.net\matchmaker.net\Matchmaker\Network\SocketManager.cs:line 126

Also, the contents of NetObjectType:
    public enum NetObjectType
{
    CLIENT_REQUEST_SERVER_LIST,
    CLIENT_SERVER_RESPONSE_GENERIC,
    CLIENT_SERVER_REGISTER_SERVER,
    CLIENT_SERVER_UNREGISTER_SERVER,
    CLIENT_SERVER_MODIFY_REGISTERED_SERVER,
    SERVER_SEND_MATCHMAKE
}

A: Implement your serializable class in common assembly which should use by client and server or use SerializationBinder to fix the issue caused by different namespace and etc.
This article is useful.


text:
Q: VS2012 компиляция под Windows XP Есть рабочий проект, все работает, НО хочется чтобы работало и под Windows XP. Пишу в VS2012 (есть еще VS2015). Решение задачи вроде как нашел -

Project->Properties->Configuration Properties->General->Platform
  toolset = Visual Studio 2010(v100)  (Проект->Свойства->Свойства
  конфигурации->Общие->Набор инструментов платформы = Visual Studio
  2010(v100))

Ну вот не вижу я "Свойства конфигурации" (или Сonfiguration Properties)...
Ребят, помогите плиз скринами выйти на страничку...

НО я вижу только это (по пути Проект->Свойства->...) и там нет "Свойства конфигурации" ((

[РЕДАКЦИЯ 1] Ребят, нашел  "Свойства конфигурации" (или Сonfiguration Properties)...Правой кнопкой прям на решении (в обозревателе решений) -> свойства

НО к сожалению нет там пункта "Общие" ("General")...

В чем может быть проблема?
Заранее спасибо за помощь, и ценные советы. ))

A: Надо просто версию фреймвёрка выставить в 4.0 на этом скрине:


text:
Q: Why batch script run in loop My Batch code run in loop. and I don't know why
@ECHO OFF

REM Stop Service Adobe
:Adobestop
sc stop AdobeARMservice

REM Start Service Adobe
:Adobestart
sc start AdobeARMservice

REM Enable Fire wall rule Base1
:EnableBase1
netsh advfirewall firewall set rule name="Base1" new enable=yes

REM Disable Fire wall rule Base1
:DisableBase1
netsh advfirewall firewall set rule name="Base1" new enable=no

REM Step 1. disable fire wall rule Base1.
netsh advfirewall firewall show rule name=Base1 | find /I "Enabled" | find "Yes"
IF %ERRORLEVEL% NEQ 1 (
goto :DisableBase1
)

REM Step 2. Stop Adobe Service.
sc query AdobeARMservice | find /I "STATE" | find "RUNNING"
IF %ERRORLEVEL% NEQ 1 (
goto :Adobestop
)

REM Step 3. Start Adobe Service.
sc query AdobeARMservice | find /I "STATE" | find "STOPPED"
IF %ERRORLEVEL% NEQ 1 (
goto :Adobestart
)

REM Step 4. Enable fire wall rule Base1.
netsh advfirewall firewall show rule name=Base1 | find /I "Enabled" | find "No"
IF %ERRORLEVEL% NEQ 1 (
goto :EnableBase1
)

A: %ERRORLEVEL% will be 0 if the command completes successfully. Change all of your
IF %ERRORLEVEL% NEQ 1 (

to
IF %ERRORLEVEL% NEQ 0 (

Perhaps someone was testing the error checking and didn't revert the 1's to 0's.


text:
Q: Connection timed out: Connect While developing against sandbox (CS21) I continue to get time outs from Force IDE (Eclipse) when refreshing or saving changes to salesforce. This happens in a number of situations including

*

*refreshing to select metadata resources for inclusion in package

*saving to sandbox

*deploying to production

*refreshing current data from sandbox

I have not pulled out wireshark yet and watched the packets go by yet but would anyone have any guidance on why I'm getting this error? Its really putting a crimp in productivity.
Update 1: This issue has been happening using the last 2 recent versions of the Force IDE the previous being winter 14 and current summer 15. Overall it seems to be network related but where in the network I have not determined, local, isp or on the salesforce side.


text:
Q: How to display a property of an object nested in an array inside a template attribute? I get the error:

TypeError: "someArr[0] is undefined".

When you try to access an object property inside a template:
{{someArr[0].name}}

Despite the error, the data is displayed.
Source data for someArr:
Array[0]: Object {id: "1", name: "One"}
Array[1]: Object {id: "2", name: "Two"}

Is it possible to get the value directly without using a loop?
EDIT
I call inside the block created() this method fetchData(), which via Ajax, retrieves data and populates the model. Now I will check your assumption, but why then the data is displayed?

A: Welcome to StackOverflow community !
When you use any value inside vue data property, Vue tracks it's value that's the whole purpose of the framework. Now the value connected to reactivity, and you binded that value to UI so whenever that value get changed Vue tracks it and re-render that module which is binded to the value and reflects the updated value.
In your case it's clear that there is a property Ex -
data() {
  return {
    someArr: []
  }
},
created() {
 // Await api call
 this.someArr = response
}

Now for the first render your value is empty arr which get updated once the async request get completed and that value get updated. But Obviously synchronous code will execute which throw the error that someArr[0] is undefined as value is empty.
For such case always preferred to check if the value exist.
{{someArr[0].name}}

Now JS engine will not execute or look for someArr[0].id if the array is empty, once you fetched the data updated it, Vue will re-render and this time it will look for id as array is having some value


text:
Q: ¿Cómo puedo medir el tiempo que se demora en ejecutar un algoritmo BubbleSort en java? quisiera saber si me podrían ayudar con una duda que tengo para poder medir el tiempo que tarda en ejecutarse un ordenamiento burbuja. En mi caso tengo listo el código solo que no se donde implementar el contador para que me muestre cuanto se demoró (en milisegundos) en ordenar el arreglo D: tengo una clase que ordena y otra test para que me muestre que se ordeno el arreglo como pueden ver a continuación:
public class Burbuja{
    public int[] BubbleSort(int[] arreglo)
    {
        int aux;
        for (int i=0; i < arreglo.length; i++)
        {
            for (int j=i+1; j < arreglo.length; j++)
            {
                if (arreglo[j] < arreglo [i])
                {
                    aux=arreglo[i];
                    arreglo[i]=arreglo[j];
                    arreglo[j]=aux;
                }
            }
        }

        return arreglo;
    }
}

y esto seria el test:
public class Test1
{
    public static void main(String[] args)
    {

        int[] arreglo= {2, 4, 7, 13, 9, 27, 6, 25, 11, 18, 1, 8};
        System.out.println("Arreglo antes de ser ordenado: ");

        for(int i=0; i < arreglo.length; i++)
        {
            System.out.print("[" + arreglo[i]+"]");
        }
        Burbuja o=new Burbuja();
        o.BubbleSort(arreglo);
        System.out.println("\nArreglo ordenado: ");

        for (int i=0; i<arreglo.length; i++)
        {
            System.out.print("[" + arreglo[i]+"]");
        }

    }

}

De antemano gracias!

A: El método System.currentTimeMillis() devuelve la hora actual en milisegundos.
Sin embargo, para medir la ejecución de un código (que puede ocurrir en menos de 1 milisegundo), se debe utilizar System.nanoTime(), que mide con precisión de nanosegundos.
public static void main(String[] args){

    long startTime = System.nanoTime();

    // ...
    // El resto del código

    long endTime = System.nanoTime();

    return (endTime-startTime);

}


text:
Q: One Netgear GS716T switch port, connected to an HP CLJ 2605dn printer, triggers SNMP down/up traps every few minutes The port only goes down for a few seconds, then comes back up. A few minutes later, it does the same thing. The printer functions normally.

*

*All the other ports on the switch are fine.

*I've tried moving it to a different port and it does the same thing.

*I've looked into power management settings and there are none for this printer.      - I've also tried changing the switch port and the printer's NIC from auto-negotiate to 100Full

I'm thinking it's a bad cable. Does anyone have any other ideas?

A: Can you temporarily move the printer to the switch or use a different cable run?  Are duplex and speed Auto or hard set on both switch and printer?  Have seen a problem with duplex and speed on auto.  I know it is supposed to work and normally does.  Had one that was fine for ages and suddenly wanted both hard set.


text:
Q: VSCode Python IntelliSense Not working On Remove Machine I use VSCode "Remote-SSH" to access a VM to do all my coding.
On the VM I have installed the "Python" and "Pylance" extensions hoping to get IntelliSense autocomplete.
My python interpreter is not in the "typical" /usr/bin/python3 location. So I have the following setting in my VM's setting.json:
"python.defaultInterpreterPath": "/some/path/to/3.6.8/python3",

I have successfully enabled python lint. Although my IntelliSense autocomplete isn't working at all. When I type I don't see any pulldown menu or error messages.
What could I possibly be missing?


text:
Q: How to get nearest place? I'm using the code below:
I want to get the nearest place from google (only need nearest result).
To do this, I changed radius but then result is wrong.
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=6.384314,81.324417&radius=1000&types=accounting|airport|amusement_park|aquarium|art_gallery|atm|bakery|bank|bar|beauty_salon|bicycle_store|book_store|bowling_alley|bus_station|cafe|campground|car_dealer|car_rental|car_repair|car_wash|casino|cemetery|church|city_hall|clothing_store|convenience_store|courthouse|dentist|department_store|doctor|electrician|electronics_store|embassy|establishment|finance|fire_station|florist|food|funeral_home|furniture_store|gas_station|general_contractor|grocery_or_supermarket|gym|hair_care|hardware_store|health|hindu_temple|home_goods_store|hospital|insurance_agency|jewelry_store|laundry|lawyer|library|liquor_store|local_government_office|locksmith|lodging|meal_delivery|meal_takeaway|mosque|movie_rental|movie_theater|moving_company|museum|night_club|painter|park|parking|pet_store|pharmacy|physiotherapist|place_of_worship|plumber|police|post_office|real_estate_agency|restaurant|roofing_contractor|rv_park|school|shoe_store|shopping_mall|spa|stadium|storage|store|subway_station|synagogue|taxi_stand|train_station|trave_agency|university|veterinary_care|zoo&sensor=false&key=AIzaSyA0JD_Z2Uo2AfnDTejQFWHAXOIaRRpjF8c

A: Order the results by distance(by using the rankby-parameter):
https://maps.googleapis.com/maps/api/place/nearbysearch/json?rankby=distance&location=6.384314,81.324417&types=accounting|airport|......&sensor=false&key=AIzaSyA0JD_Z2Uo2AfnDTejQFWHAXOIaRRpjF8c
Note:

*

*you must ommit the radius in this case

*there is no way to limit the number of results to a specific value


text:
Q: How union works when we print other variables which are not initialized? #include<stdio.h>
#include<stdlib.h>
union employee
{
    char name[15];
    int age;
    float salary;
};
const union employee e1;
int main()
{
    strcpy(e1.name, "z");
    printf("%s %d %f\n", e1.name, e1.age, e1.salary);
    strcpy(e1.name, "x");
    printf("%s %d %f", e1.name, e1.age, e1.salary);
    return 0;
}

Output:
z 122 0.000000
x 120 0.000000

union is declared const but why the value is changing?
and how the union works when we print other values?

A: Writing to const data is undefined behavior (UB).
const union employee e1;
strcpy(e1.name, "z");

You are "getting this warning, so strcpy" may or may not correctly perform the copy to a const.  Code has broken the contract about writing to const data.  Now the compiler not longer needs to behave in a proscribed manner.  The code may abruptly fail at this point or it may do anything - including work as desired.  That is undefined behavior (UB).


text:
Q: How to create a list of all accessible objects in Pyramid / SQLAlchemy? I have developed a small web application using the pyramid framework and just implemented the integrated security features. I have created a ressource object, let's call it Page, and I endowed it with an ACL so that every user can see and edit the pages for which he has the appropriate permissions. This all works fine.
My question is the following: What is the pyramid appropriate way to create a list of all pages the currently logged in user is allowed to see?
The application uses URLDispatch and SQLAlchemy.

A: There is no "pyramid-appropriate way". Just query your database for a "list of all pages the currently logged in user is allowed to see".
db.query(Page).filter_by(owner=user_id).

There are Pyramid cookbook recipes for idiomatic ways of accessing the user and the database session via request.user and request.db that may be worth a look.

A: you could post filter them if the acls aren't known to the database....
from pyramid.security import has_permission

def make_permission_filter(request, permission="view"):
    def f(r):
        if r and has_permission(permission, r, request):
            return r
        else:
            return None

(r for r in make_permission_filter(request, permission="view")(db.query(Page).filter_by(owner=user_id)) if r)

there are drawbacks of course but that is one way to do it.


text:
Q: Why do spiral waves annihilate each other when 2 wavefronts collide? I was reading about Fitzhugh-Nagumo model. And in a 2D space the simulations a Reaction-Diffusion process associated with FitzHugh system look like this. But intuitively I could not satisfy myself about the annihilation of wave when 2 wavefronts meet each other. Why do they annihilate each other?
One example I heard in practical world is controlling forest fire using opposing wavefront of a controlled fire.

A: Let's consider this incarnation of the FitzHugh–Nagumo model:
$$\begin{matrix}
\dot{V} & = &  V-V^3/3 - W +  I  \\
\dot{W} & = & 0.08(V+0.7 - 0.8W)
\end{matrix}$$
This describes an excitable system. In the following I will explain what this means, how this relates to the above equation and use a small patch of forest as an example.

*

*A small stimulus (via $I$) can trigger a huge response (excitation). In the equation, the extent of excitation is represented by the variable $V$. The mechanism of excitation is somewhat difficult to see from the equations and comes from the non linear structure $V-V^3/3$ which causes the nullclines to be aligned such that a small excitation from the fixed point requires the system to perform a large excursion in phase space to return to the fixed point. In the forest example, the stimulus corresponds to throwing a match into our patch of forest.

*Excitation triggers an inhibitory process that counteracts the excitation. The unit becomes refractory. In the equations this inhibitory process is represented by the variable $W$. Furthermore, you can see that a high $V$ (excitation) begets a high $W$ (inhibition), as $\dot{W}$ increases with $V$. Furthermore a high $W$ (inhibition) begets a lower $V$ (excitation), as $\dot{V}$ decreases with $W$. In the forest example the inhibitory process corresponds to ashes, which do not burn.

*The inhibitory process self-terminates after a while. In the equations, this is implemented via $\dot{W}$ decreasing with $W$, i.e., without further influence, the variable $W$ drifts towards $0$. In the forest example, this corresponds to the forest regrowing from the ashes.
In an excitable medium such as a 2D reaction–diffusion system, each point in space is represented by an excitable system and these systems are coupled via a next-neighbour coupling. This coupling is usually diffusive, i.e., $I \propto ΔV$, but other couplings have a similar effect. In our forest example, an excitable medium corresponds to a whole forest, consisting of many patches and the coupling represents sparks of fire going from one burning patch to its neighbours.
In an excitable medium, excitations spread in a wave-like manner, the same way forest fires do: Whenever a single patch is excited, it is likely to also excite its neighbours, which then excite their neighbours and so on – the forest fire spreads in a wave-like manner. However, each excited unit becomes refractory shortly afterwards and thus a front of excitation is followed by a front of inhibition.
Now, if two wavefronts collide, consider the single front of excitation formed by this collision. As both wavefronts are followed by fronts of inhibition, it is now enclosed by inhibitory regions. Thus the excitation cannot spread anywhere and thus once this single front becomes inhibitory, the excitation dies and the wavefronts have annihilated.
Fighting fire with fire works the same way: Each forest-fire front leaves behind nothing but ashes. If this front runs into another front, it is enclosed by ashes and can thus not spread any further.


text:
Q: Not Able to Install when Newer Version of Prerequisites are Present I have a c# solution that includes a c++ project accessed as a COM object. I am building this in VS 2010, and have created a Windows Installer to install the program. The application is 64 bit, and runs fine on most machines. However, I want to add "Visual C++ 2010 Runtime Libraries (x64)" as a prerequisite, so I can be sure everything required is available on the system.
If I make the change, every time I try installing on my test system, where it worked before, I am told that Visual C++ needs to be installed. I click the Install button, say yes to the UAC, and get an error saying "A newer version of Microsoft Visual C++ 2010 Redistributable has been detected on the machine." I am then given a message that "An error occured while installing system components... Setup cannot continue until all system components have been successfully installed."
Component Visual C++ 2010 Runtime Libraries (x64) has failed to install with the following error message:
"Asia"

The following components failed to install:
- Visual C++ 2010 Runtime Libraries (x64)

I find it odd that I can't install the application if a newer version of C++ is already on the computer.

One additional bit of information: to get the msi file to work with the 64 bit installation, I need to edit it with Orca, go to Binary -> InstallUtil _> and change the field to the 64 bit version of the installUtilLib.dll. Since prerequisite checking happens in the exe file, before loading the msi, I don't think this would make a difference, but thought I would add it in. If I do not make the change, the installer crashes immediately.
If anyone knows what I need to do to either get the latest version of Visual C++ to install, or to accept a later version as fulfilling the requirements, I would greatly appreciate the guidance.
Currently testing on Windows 7 x64 system.

A: Steps to solve this can be found here, and product values can be found here.
Below are the basic steps that I followed:
Edit
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bootstrapper\Packages\vcredist_x64\product.xml

Find
<InstallChecks>
    <MsiProductCheck Property="VCRedistInstalled" Product="{6EE91C1A-A2E7-38CD-AEBB-3B900A4D8868}"/>
</InstallChecks>

Change to
  <InstallChecks>
    <MsiProductCheck Property="VCRedistInstalled" Product="{1D8E6291-B0D5-35EC-8441-6616F567A0F7}"/>
  </InstallChecks>

A:
RESOLUTION
There is no fix for this issue, as it is a limitation of the Microsoft
  installer when it encounters a newer version of the same Runtime
  Libraries.

Source : http://micc.mitel.com/


text:
Q: GlobalKTable - StreamsException: Encountered a topic-partition not associated with any global state store I am trying to use Kafka-streams to create a GlobalKTable from a stream, and getting an exception when I call streams.start():

org.apache.kafka.streams.errors.StreamsException: Encountered a topic-partition not associated with any global state store

My code is:
private final KafkaStreams streams;
private final StoreQueryParameters<ReadOnlyKeyValueStore<LocalDate, String>> bankHolidayTypesSqp = StoreQueryParameters.fromNameAndType("bank_holiday_type_store"
            ,QueryableStoreTypes.<LocalDate, String>keyValueStore());
private final ReadOnlyKeyValueStore<LocalDate, String> localBankHolidayTypeStore;

private void instantiateKafka()
{
        // configure Kafka

        StreamsBuilder builder = new StreamsBuilder();

       // CustomSerializableSerde is just a generic serializer that uses standard java Base64 encoding on any object that implements Serializable - it works in a dummy application I've tested, so I don't think it's the problem
        addGlobalTableToStreamsBuilder(builder, bankHolidayTypeTopic,"bank_holiday_type_store", new CustomSerializableSerde<LocalDate>(),Serdes.String());

        streams = createStreams("localhost:9092", "C:\\Kafka\\tmp\\kafka-streams-global-tables",MyClass.class.getName(),builder);
        streams.start(); // hangs until the global table is built
}

public static <Tk extends Serializable,Tv extends Serializable> StreamsBuilder addGlobalTableToStreamsBuilder(StreamsBuilder builder, String topic
            , String store, Serde<Tk> keySerializer, Serde<Tv> valueSerializer)
    {
        builder.globalTable(topic, Materialized.<Tk, Tv, KeyValueStore<Bytes, byte[]>>as(store)
                .withKeySerde(keySerializer)
                .withValueSerde(valueSerializer));
        return builder;
    }

public static KafkaStreams createStreams(final String bootstrapServers, final String stateDir, String clientID, StreamsBuilder finishedBuilder)
     {
        final Properties streamsConfiguration = new Properties();
        // Give the Streams application a unique name.  The name must be unique in the Kafka cluster against which the application is run.
        streamsConfiguration.put(StreamsConfig.APPLICATION_ID_CONFIG, "applicationName");
        streamsConfiguration.put(StreamsConfig.CLIENT_ID_CONFIG, clientID);
        // Where to find Kafka broker(s).
        streamsConfiguration.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        streamsConfiguration.put(StreamsConfig.STATE_DIR_CONFIG, stateDir);
        // Set to earliest so we don't miss any data that arrived in the topics before the process started
        streamsConfiguration.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

         return new KafkaStreams(finishedBuilder.build(), streamsConfiguration);
     }

And the producer:
Producer<LocalDate,String> bankHolidayTypeProducer = MyClass<LocalDate,String>createProducer("localhost:9092", BankHolidayData.class.getName()
                    , CustomSerializer.class.getName(), StringSerializer.class.getName());

//...

HashMap<LocalDate, String> bankHolidaysData = populateBankHolidayMap();

for (LocalDate bhDay : bankHolidaysData.keySet())
            {
                bankHolidayTypeProducer.send(new ProducerRecord<>(bankHolidayTypeTopic, bhDay, bankHolidaysData.get(bhDay)));
            }

public static <Tk extends Serializable, Tv extends Serializable> Producer<Tk,Tv> createProducer(String bootstrapServers
            , String clientID, String keySerializerClassName, String valueSerializerClassName)
    {
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        props.put(ProducerConfig.CLIENT_ID_CONFIG, clientID);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, keySerializerClassName);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, valueSerializerClassName);
        return new KafkaProducer<>(props);
    }

My topic is created automatically by the producer when it first produces, and will always exist by the time the GlobalKTable comes to try and read from it. Is this the problem? Do I need to do something when setting up the topic to tell Kafka that it's going to be used by a Streams GlobalKTable?

A: There had (apparently) been some changes to the structure of the topic, meaning that Streams needed to be reset. To do this, you can use the application Conduktor, or the reset tool found at http://docs.confluent.io/current/streams/developer-guide.html#application-reset-tool.

A: if you are running local instance/ or you have the ability, then

*

*stop brokers

*stop zookeeper

*remove the kafka-streams folder under the parent folder as referenced by the env var java.io.tmpdir.

you can get the true folder name in the Broker logs, search for 'INFO Client environment:java.io.tmpdir'

A: If this helps someone, this happens if you update any schema on consumer side of GlobalKTable and also may be when the schema changes on the Kafka side. So what fixed for me is just deleting my local state-store folder, usually present in your projects root directory.


text:
Q: How to automatically save a list of files with different names? I have a text file of URLs, each in the form of:
http://domain.com/a/b/c/d.jpg
I want to download all of these, but save each file under the name:
c_d.jpg
In other words, for each file, I want to save the file under its original filename prefixed by the name of its parent directory.
How would I go about doing this on Windows?
I'm fine with using a command line tool, such as wget or curl, just give me the arguments.
Thanks.

A: Not sure how to make it in a pure windows environment, but in a cygwin environment, you could try this: (requires bash, sed, wget)
while read link; do a=`echo $link | sed 's/.*\/\(.*\)\/\(.*\)/wget \0 -O \1_\2/'`; echo $a; $($a); done < links.txt

where links.txt is your file.
Of course you can tweak the sed expression to convert the link to a filename in anyway.
Cheers


text:
Q: How to delete a specific sub-folder in a parent folder using a batch file? I would like to create a batch file deleting or removing the folder C:\temp\root\students\type1, its subfolder and all the files.
The folders and files I do have are as follows:
C:\temp
C:\temp\root
C:\temp\root\students
C:\temp\root\tutors
C:\temp\root\students\type1
C:\temp\root\students\type2
C:\temp\root\tutors\type1
C:\temp\root\tutors\type2
C:\temp\root\students\type1\details.txt
C:\temp\root\students\type1\assignment1
C:\temp\root\students\type1\assignment1\results.txt

The folder C:\temp\root\students\type1\assignment1 is specified in the batch file.
I would like to go one folder/directory up and delete or remove C:\temp\root\students\type1 in my batch file (test.bat).
Please help me with this.

A: Use this:
rd /s /q C:\temp\root\students\type1

It will remove files and folders recursively, caution, without prompt. It's kind of a substitute for the good old deltree. Best.
EDIT: within your notepad, create your mygoodbatch.bat with this content:
md C:\temp
md C:\temp\root
md C:\temp\root\students
md C:\temp\root\tutors
md C:\temp\root\students\type1
md C:\temp\root\students\type2
md C:\temp\root\tutors\type1
md C:\temp\root\tutors\type2
md C:\temp\root\students\type1\details.txt
md C:\temp\root\students\type1\assignment1
md C:\temp\root\students\type1\assignment1\results.txt
rd /s /q C:\temp\root\students\type1

(md is the make dir dos command, so all the lines beginning with it are creating the folders - the last line is the one to del your level 4AA)
Save this batch on the root of your disk and then run it. I really wish this is what you want. What I yet didn't understand is: you are creating a directory structure and, at the same time, excluding level 4AA... is that it?

A: You can use a for loop to get the parent folder for a given folder:
set target_dir=C:\temp\root\students\type1.test\assignment1

for %%a in ("%target_dir%") do (
    echo Removing %%~dpa%
    rd /s/q %%~dpa%
)


text:
Q: Regex duration in seconds I'm sorry, I speak English little.
My PHP code:
$duration = "3 h 33 min";
preg_match( '/(?<h>.*) h (?<m>.*) min/', $duration, $time );
$h = $time['h'] * 60 * 60;
$m = $time['m'] * 60;
$s = $h + $m;

It works, but my durations:
12 sec
75 sec
2 min
69 min
1 h
2 h 35 min
How to write regex or better idea in PHP? I need the output in seconds.

A: Considering the input is always correct and only contains the hours, minutes or seconds values marked with the strings you mentioned, you can use
$text = "2 h 35 min";
$rx = '~(\d+)\h*(h|min|sec)~';
$res = 0;
if (preg_match_all($rx, $text, $matches,PREG_SET_ORDER,0)) {
    foreach ($matches as $match) {
        if ($match[2] === "h") {
            $res += (int)$match[1] * 60 * 60;
        } else if ($match[2] === "min") {
            $res += (int)$match[1] * 60;
        } else if ($match[2] === "sec") {
            $res += (int)$match[1];
        }
    }
}
echo $res;

See the PHP demo.
The (\d+)\h*(h|min|sec) regex matches and captures into Group 1 any one or more digits, \h* matches zero or more horizontal whitespaces and then h, min or sec are matched and captured into Group 2.

A: The current answer does solve the problem. I took an approach similar to yours.
I didn't use named group captures (?<name>...) but you could if you preferred. My solution encloses a (\d+) timeunit in a non capturing group, (?:...). Meaning it doesn't end up in $m matches. Then we make the group optional through ?. The groups are the separated by  * meaning 0 or more white spaces.
$test = [
    '' => 0,
    'invalid duration' => 0,
    '12 sec' => 12,
    '75 sec' => 75,
    '2 min' => 120,
    '69 min' => 69 * 60,
    '1 h' => 60 * 60,
    '2 h 35 min' => 2 * 60 * 60 + 35 * 60,
];

function duration_in_seconds(string $duration): int
{
    preg_match('/(?:(\d+) h)? *(?:(\d+) min)? *(?:(\d+) sec)?/', $duration, $m);

    return ((int) ($m[1] ?? 0)) * 60 ** 2 +
        ((int) ($m[2] ?? 0)) * 60 ** 1 +
        ((int) ($m[3] ?? 0));
}

foreach ($test as $durationString => $duration) {
    echo 'Expected: ', str_pad((string) $duration, 5), '  got: ', duration_in_seconds($durationString), PHP_EOL;
}


text:
Q: Inside our SharePoint online tenant, is there a way to view all the Nintex workflows for all the sites, or at-least for a site? I am working on a SharePoint online tenant for a new customer, now the customer is using Nintex workflow, but I am trying to know how many Nintex workflows they have.
Now if I go a list >> I will get the Nintex button >> if I click on it I can view the Nintex workflows linked to that list, as follow:

But my question is, if there is a way to view all the Nintex workflows for all the site collections? or atleast for each site?
EDIT. this is the error:

A: You can get the list of all Nintex workflows in your tenant using:

*

*Nintex Hawkeye

*PowerShell

Check this thread for more information & PowerShell script: How can I find all the workflows in my O365 SharePoint tenant using PowerShell

A: Go to site settings >> Workflow Inventory
/_layouts/15/NintexWorkflow/WorkflowGallery.aspx

You can find this option under site settings >> Nintex workflow

In case you cannot access the Workflow-Inventory-page , please go to this URL
Unable to access Workflow Inventory page


text:
Q: DNN Too many redirects Our dnn version is 07.04.00 (353). We have an external system that redirects the user to some page. In order, the user will see the page he must have specific role i.e. this page only visible for users that have this role. If the user doesn't have this role he should be redirected to the home page.
Using chrome developer tools we see that the page get "You+do+not+have+access+to+view+this+page+within+the+website", dnn then redirect to Default.aspx where there it gets "=An%20unexpected%20error%20has%20occurred". It then try redirect to the page again and it enter into infinite loop of redirection.
Can you please advise?

A: Please check the Log4Net files in \Portals_default\Logs for more a detailed error message.


text:
Q: Alternatives for deprecated code in java? I'm currently learning GUI applications from a book called "starting out with java". I've tried one of the author's code examples regarding JList, but it turns out that the getSelectedValues() in ButtonListener is already deprecated. I just want to ask if you guys know any alternatives for that specific code for that. Although the code still works tho but I still wanted to know alternatives.
Here is the code:
package Practice;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Practice1 extends JFrame{
private JPanel monthPanel;
private JPanel selectedMonthPanel;
private JPanel buttonPanel;
private JList monthList;
private JList selectedMonthList;
private JScrollPane scrollPane1;
private JScrollPane scrollPane2;
private JButton button;

private String[]months = {"January","February","March","April",
        "May","June","July","August","September","October",
        "November","December"};

public Practice1(){
    setTitle("List Demo");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new BorderLayout());
    buildMonthPanel();
    buildSelectedMonthPanel();
    buildButtonPanel();
    add(monthPanel,BorderLayout.NORTH);
    add(selectedMonthPanel,BorderLayout.CENTER);
    add(buttonPanel,BorderLayout.SOUTH);
    pack();
    setVisible(true);
}

private void buildMonthPanel(){
    monthPanel = new JPanel();
    monthList = new JList(months);
    monthList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    monthList.setVisibleRowCount(6);
    scrollPane1 = new JScrollPane(monthList);
    monthPanel.add(scrollPane1);
}

private void buildSelectedMonthPanel(){
    selectedMonthPanel = new JPanel();
    selectedMonthList = new JList();
    selectedMonthList.setVisibleRowCount(6);
    scrollPane2 = new JScrollPane(selectedMonthList);
    selectedMonthPanel.add(scrollPane2);
}

private void buildButtonPanel(){
    buttonPanel = new JPanel();
    button = new JButton("Get Selections");
    button.addActionListener(new ButtonListener());
    buttonPanel.add(button);
}

private class ButtonListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
        Object[]selections = monthList.getSelectedValues();
        selectedMonthList.setListData(selections);
    }
}

public static void main(String[]args){
    new Practice1();
}
}

A: Replace it with the following
monthList.getSelectedValuesList().toArray()

See This post for more information

A: In the docs, it says that getSelectedValues is deprecated and it says that this method is replaced by getSelectedValuesList! If you looked at the docs, you would have known that. Next time you encounter these kind of problem, just look at the docs. Here is the docs:
http://docs.oracle.com/javase/7/docs/api/javax/swing/JList.html#getSelectedValuesList()
Note that the new method returns a List<E>, not a Object[]. You can just use the toArray method to convert it to Object[].


text:
Q: Can I keep a reference to hazelcast replicatedmap or should I look it up every time I am writing a hazelcast client in spring boot and I need to access a replicated map.
Can I look this up in my singleton bean constructor, or should I call hz.getReplicatedMap("mymap") every time I need it?
The client should of course restarts of the hazelcast members/servers.
I am using hazelcast 4.2.1 in case that matters.

A: Yes, you can look it up in your singleton bean constructor and keep using the reference.


text:
Q: What will happen if I made a mistaken configuration of DNS Reverse Lookup in IIS? I have configured a correct DNS in my wndows 2008 server, all my websites works well.
Now I hope to configure DNS Reverse Lookup, so I read http://www.windowsreference.com/dns/how-to-create-dns-reverse-lookup-zone-in-windows-server-2003/.
but I do not completely understand  ßthe article, what will happen if I make a mistake in my Reverse DNS Lookup configuration ?
Will all my websites become unaccessable ?

A: You will add the option to translate your IP to a name. If you configure your reverse DNS in the wrong way, your A records will still work unless you start to mess with that zone. As on the how to test it, you can use dig to look for pointer records.


text:
Q: How to create trigger functions? How to create triggers?
I found an article on PostgreSQL's official website, but I couldn't understand what spj, trim and ns mean. Help me, please.
CREATE FUNCTION trigger_s_before_del () RETURNS trigger AS '
BEGIN
if (select count(*) from spj a where trim(a.ns)=trim(OLD.ns))>0
then delete from spj where trim(spj.ns)=trim(OLD.ns);
end if;
return OLD;
END;
' LANGUAGE  plpgsql;

A: *

*spj is a table name

*a is an alias given to a table,

*ns is a column name in spj table,

*trim is a PostgreSQL buil-in function.

A: to define a trigger, first we need a special kind of function which returns TRIGGER;
CREATE OR REPLACE FUNCTION "myTriggerFunction"() RETURNS TRIGGER AS $BODY$
DECLARE
    myVal BOOLEAN = TRUE;
BEGIN
    myVal = ( OLD."myField" > NEW."myField" );

    IF myVal THEN
        INSERT INTO "sampleRelatedTable"
            ( "id", "someField_old", "someField_new" )
        VALUES
            ( OLD."id", OLD."myField", NEW."myField" )
        ;
    END IF;

    RETURN NULL;
END;
$BODY$ LANGUAGE 'plpgsql' VOLATILE;

since our "Trigger Procedure" is ready, we can attach it to the table;
CREATE TRIGGER "myTrigger"
    UPDATE ON "myTable"
    FOR EACH ROW EXECUTE PROCEDURE "myTriggerFunction"()
;

now our trigger is ready. it will trigger "myTriggerFunction" when a record in "myTable" is updated.
for detailed information refer to docs;
TRIGGER PROCEDURES : https://www.postgresql.org/docs/current/static/plpgsql-trigger.html
CREATE TRIGGER : https://www.postgresql.org/docs/current/static/sql-createtrigger.html


text:
Q: Is it good practice to clear the cache files generated by AdMob in Android? I have integrated AdMob in my Android app. I noticed the app taking up more and more storage space in a folder called app_webview generated by AdMob inside the app data folder. Should I clear the contents of this folder on each app exit ?

A:
Should I clear the contents of this folder on each app exit ?

Why would you want to do that? Admob does this to provide better and speedy ad serving. And I'm sure the amount it is caching is within tolerable limits. Clearing that much space on the user's storage will not make him much happy. But you'll lose on revenue because of Admob trying to re-download all the stuff again. It will lower your fill rate and thereby your revenue.
There is no harm in doing it but you'll lose more (revenue) than you gain (user satisfaction). The user might not even notice it.

A: Admob is just caching its ads so they load quicker. The Android OS will clear the /cache directory if the filesystem gets too full, and Admob should be managing its own cache size. You shouldn't have to worry about it.


text:
Q: List of Magento XML Layout Tags I have search google, loads, but with no joy. I am thinking this doesn't exist on the internet, or (more likely) I just don't know the right search terms to find this, so I apologize in advance if this seems like a fairly basic question.
I am just looking for a list of XML Layout tags. I know a few already, and I also know that you (or 3rd parties) can create and define your own custom tags. All I need is a list of the basic layout tags that Magento uses, tags like these:
<default>
<catalog_category_layered>
<catalog_category_default>
<cms_page>
<cms_index_index>

Etc.
Can anyone provide me for a more complete list?
Many thanks!

A: To see the handles for the current page (as they are different for different pages) you can add the following code at the end of the index.php file:
var_dump(Mage::app()->getLayout()->getUpdate()->getHandles());


text:
Q: playing sound onClick event in Vue returns Uncaught (in promise) DOMException: Failed to load because no supported source was found I am trying to play an mp3 sound when I click on an image, but currently I get this error : Uncaught (in promise) DOMException: Failed to load because no supported source was found
Why isn't my audio playing and how can I make it play?
my function:
 playSound() {
  const sound = new Audio("/src/assets/sounds/openbeersound.wav");
  sound.play();
    }

  <img
    style="width: 100%;"
    :src="beer.image_url"
    alt="placeholder"
    @click="playSound()"
   />

A: Make sure the audio is loaded correctly.
How to bind img src to data in Vue
(images or audio are the same)
If you want to learn more about it.


text:
Q: Disable drag and drop option for multiple file uploader These are the screenshots of multiple file uploader from the same SharePoint 2010 site. Some users are seeing the first and some are seeing the second one. Is it possible to disable the second view(drag and drop) by editing upload.aspx in the layouts folder?

Thank You

A: You can disable it by editing the JS files.
read the below post, they enforcing the metadata when uploading the docuemnt and they talked about the disabling the drag and drop.
How can I disable the Document Library drag and drop function?
Enforce Drag and Drop documents to apply metadata


text:
Q: beginner: c++ code: strings are being duplicated when printed so i coded a program where you enter "n" amount of strings. Porgram prints first and last string by alphabet order, then prints the rest of them (no alphabet order for the rest)
example, a user enters
ab
cd
ef
gh

Program should pirnt:
ab
gh
cd
ef

This part above works fine in my code, the problem comes when you enter 2 times a same string, it will print them both, which should not happen... it should skip the duplicates and do its original job.
for example if I enter in my code:
ab
cd
ef
gh
ab

Program will print two times ab, etc.
ab
ab
cd
ef
gh

This is the code:
#include<iostream>
#include<vector>
#include<string>

using namespace std;

int main(){
cout<<"Enter a number of words: ";
int n;
cin>>n;

vector<string> v;
for(int i=0;i<n;i++){
    string temp;
    cout<<"Enter "<<i+1<<". word: ";
    cin>>temp;
    v.push_back(temp);
}
if(v[0][0]<v[n-1][0])cout<<v[0]<<endl<<v[n-1];
else cout<<v[n-1]<<endl<<v[0];

cout<<endl;
for(int i=1;i<n-1;i++){
    cout<<v[i]<<endl;
}
return 0;
}

It's probably an easy fix, but not for me.
Thanks

A: If you don't want multiple elements in your array you should check every time a string is going to be added if it's already present (in a loop, comparing with all the other strings) or you can change the container from a vector to another which guarantees uniqueness, like std::map or std::unordered_set.
Using a vector you can change your code like this:
#include<iostream>
#include<vector>
#include<string>

using namespace std;

int main() {
    cout << "Enter a number of words: ";
    int n;
    cin >> n;

    vector<string> v;
    for( int i = 0; i < n; ) {
        string temp;
        cout << "Enter " << i + 1 << ". word: ";
        cin >> temp;

        // loop through the vector searching for temp
        int j = 0;
        while ( j < v.size()  &&  v[j] != temp )
            ++j;

        // add temp if it isn't already present
        if ( j == v.size() ) {
            v.push_back(temp);
            ++i;
        }
        else
            cout << temp << " is already present\n";
    }

    // use the real size of the vector
    int last = v.size() - 1;
    if ( v[0][0] < v[last][0] )
        cout << v[0] << endl << v[last];
    else
        cout << v[last] <<endl <<v[0];

    cout << endl;
    for ( int i = 1; i < last; i++ ){
        cout << v[i] << endl;
    }
return 0;
}


text:
Q: Custom modules are not found when calling python script in console VS pycharm I have a python3 script that I am calling in terminal; I do not use Python prefix to run it, since I did add #!/usr/local/bin/python3 in my script (I have python3 from brew, on OSX).
The interesting thing is that if I run the script in terminal, I get an import error because one of my custom module hasn't been found. If I run the same script in pycharm, it works fine.
I assume Python launch and read all the various path that I use for modules in the same way, in both pycharm and terminal, but it seems not the case. How do I set up my scripts so the modules are found, independently from their path?
I may run the same script from other machines too, so I want to be prepared and do the right thing from the start.
EDIT
I am running pycharm on OSX; Python3 is installed via Brew, but the symlink is in /usr/local/bin.
My script is running from a folder inside my home directory, so
/Users/tester/git/python_test_app/main/base/app_main.py
The custom modules are in the same folder of the main py script, but one level above: /Users/tester/git/python_test_app/main/pyutils.py
The import statement from app_main.py is
import main.pyutils as utilities
This is the stack trace that I get when running the script:
Traceback (most recent call last):
  File "main/base/app_main.py", line 13, in <module>
    import main.pyutils as utilities
ModuleNotFoundError: No module named 'main'

EDIT 2 and solution
Thanks to The answers, I was able to figure out that the issue is related to how Pycharm handle projects. Basically it somehow save the path where the project is; so calling an import will result in the project folder being parsed, and that's why it works fine from Pycharm.
In Python, unless PYTHONPATH has the path to my project or other modules that I wrote, it won't be able to find them, hence, raise the error.
FIX:
in my main module that I use to run the application, I did retrieve the path of the file; which I know being one level below the modules I need; so I can explicitly add the folder to the current sys.path. This will end up making possible for me to call the import successfully.
import sys

current_dir = os.path.dirname(__file__)
sys.path.insert(0, , current_dir)

The only downside is that every file and resource that I use in my project, has to be directly referred by full path; so I have to pass the current_dir around the various files in the project.

A: PyCharm has project interpreter settings. Verify these are the same as your system Python. Go to:

*

*File menu

*Settings

*Project: <project name>

*Project Interpreter

*View the path to the Python executable/binary being used by the project in PyCharm and verify it matches what your system is calling (e.g., which python3)

Alternatively, it may be that you declared your sources root within PyCharm and the system cannot properly run the module as it exists in the path you're running it from (especially if inside a package). You can get around this using the -m parameter and calling it from Python.
You can also try running it from the Terminal inside PyCharm and see what it adds to the path before initializing the shell session (you can sometimes see this in your Run configurations also). If you are referring to modules not installed via pip / into the Python path but rather loaded into your project path, then this may be the culprit.

A: On PyCharm, next to the green "RUN" arrow press the box and then press edit configurations (see image)

There you'll have Working Directory - that path is where PyCharm is running that script from (without errors).
Try running it from the terminal within that path - that should solve your import errors.


text:
Q: Should I respond with a 400 error if a form submit contains validation errors? In a classic form-based webapp, if a user submits a HTML form that contains validation errors, assuming no JavaScript, what's the correct thing to do?

*

*Respond with the HTTP 200 + the page content (including error info for the user)

*Respond with the HTTP 400 + the page content (including error info for the user)

Does it matter?

A: Your app is talking to human beings, not other machines.  Therefore you should do the right thing and handle exceptions in a user-friendly manner.
Your user doesn't care about HTTP return codes, and so it should not even be a consideration for you either.  You are confusing business-logic problems with HTTP protocol problems.
Infact, by throwing a 400 error at a web-browser, you are only likely to encounter the web browser throwing up an ugly message to the user.
If you were coding a REST api, then the answer would be different.  But you're not.

A: 1) would be the correct approach because you want to display a page of content to the user that highlights the invalid input values.
The trouble with 2) is that some browsers may display their own 'friendly' error page that is designed to help users understand 4xx errors. Here's some information about when IE displays 'friendly' error pages:
http://support.microsoft.com/kb/294807

A: On the one hand, if it is a web app for human consumption, a 200 with a some useful error message will work. Making web sites for humans is easier in that sense because they can read and understand the content and do not have to depend on the status code for interact with the applications.
On the other hand, If you thinking of a REST API more appropriate would be to throw a 4xx error because it is a client side error. In that case, you have several options.
According RFC2616, a 400 means

The request could not be understood by the server due to malformed
syntax. The client SHOULD NOT repeat the request without
modifications.

This doesn't seem to be appropriate as it's not due to malformed syntax.
However, RFC2616 is now obsoleted by RFC7230-7235. The new RFC7231 defines the meaning of 400 in a more broader way.

Client Error 4xx The 4xx (Client Error) class of status code indicates
that the client seems to have erred.  Except when responding to a HEAD
request, the server SHOULD send a representation containing an
explanation of the error situation, and whether it is a temporary or
permanent condition.
400 Bad Request
The 400 (Bad Request) status code indicates that the server cannot or
will not process the request due to something that is perceived to be
a client error (e.g., malformed request syntax, invalid request
message framing, or deceptive request routing)

So this seems acceptable even though still generic. Another option would be to use 422 status code defined by RFC4918 (WebDAV).

422 Unprocessable Entity The 422 (Unprocessable Entity) status code
means the server understands the content type of the request entity
(hence a 415(Unsupported Media Type) status code is inappropriate),
and the syntax of the request entity is correct (thus a 400 (Bad
Request) status code is inappropriate) but was unable to process the
contained instructions.  For example, this error condition may occur
if an XML request body contains well-formed (i.e., syntactically
correct), but semantically erroneous, XML instructions.


text:
Q: TypeError: Cannot read property 'send' of undefined discord bot Does anyone know how to fix this?
    client.channels.get(config.logChannel).send(embed)
                                          ^

TypeError: Cannot read property 'send' of undefined
    at Client.client.once (/home/fynn/DiscordTickets/server.js:119:43)
    at Object.onceWrapper (events.js:313:30)
    at emitNone (events.js:111:20)
    at Client.emit (events.js:208:7)
    at WebSocketConnection.triggerReady (/home/fynn/DiscordTickets/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:128:17)
    at WebSocketConnection.checkIfReady (/home/fynn/DiscordTickets/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:144:61)
    at ReadyHandler.handle (/home/fynn/DiscordTickets/node_modules/discord.js/src/client/websocket/packets/handlers/Ready.js:80:8)
    at WebSocketPacketManager.handle (/home/fynn/DiscordTickets/node_modules/discord.js/src/client/websocket/packets/WebSocketPacketManager.js:108:65)
    at WebSocketConnection.onPacket (/home/fynn/DiscordTickets/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:336:35)
    at WebSocketConnection.onMessage (/home/fynn/DiscordTickets/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:299:17)

public source code: https://github.com/eartharoid/DiscordTickets
      .setAuthor(`${client.user.username} / Ticket Log`, client.user.avatarURL)
      .setColor("#2ECC71")
      .setDescription(":white_check_mark: **Started succesfully**")
      .setFooter(`DiscordTickets by Eartharoid`);
    client.channels.get(config.logChannel).send(embed)
  } else {
    client.channels.get(config.logChannel).send(":white_check_mark: **Started succesfully**")
  } ```

A: Are you sure the bot has access to that channel?
This is because if the client is not able to see the channel, it will give you an undefined back
Are you sure the ID in of the channel in your config is a String?
discord.js needs a Snowflake in the ChannelManager.get() method
Maybe try this instead of .get()
client.channels.fetch(config.logChannel)

This is a method that ships with the ChannelManager, that as far as I know does basicly the exact same as .get() method on a Discord Collection.
Sorry for my not so good english, tried my best to answer your questions with some explanations!


text:
Q: Updating db columns of employees with their joining dates We have a table called emp_details with the columns CL and PL which stores employee details with joining dates.
I need to update CL and PL of each employees using the following rule:
difference of (Current date-Date Of Joining) > 10 then CL +=0.5 and PL +=0.5
Could anyone please help me with the query for MySQL

A: Assuming you have the following structure
UPDATE hs_hr_employee AS l
INNER JOIN hs_hr_employee AS r ON l.employee_id = r.employee_id
SET
    l.CL = (r.cl + 0.5),
    l.PL = (r.pl + 0.5)
WHERE (DATE(NOW()) - DATE(l.joined_date)) > 10


text:
Q: Error "Could not find com.android.support:appcompat-v7:22.2.0" Im using github template product-catalogue-android-master
When i try clone thins...the same error occur and i dont know what to do...
Im using Android studio 1.4, JRE 1.8, SDK Build 22.0.1.
Already put gradle 2.2.1 in project user/gradle/wrapper/dists/
and both gradle 2.2.1 and 2.4 in AS gradle folder
error says
FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugCompile'.
   > Could not find com.android.support:appcompat-v7:22.2.0.
     Searched in the following locations:
         https://jcenter.bintray.com/com/android/support/appcompat-v7/22.2.0/appcompat-v7-22.2.0.pom
         https://jcenter.bintray.com/com/android/support/appcompat-v7/22.2.0/appcompat-v7-22.2.0.jar
         https://repo.commonsware.com.s3.amazonaws.com/com/android/support/appcompat-v7/22.2.0/appcompat-v7-22.2.0.pom
         https://repo.commonsware.com.s3.amazonaws.com/com/android/support/appcompat-v7/22.2.0/appcompat-v7-22.2.0.jar
         file:/C:/Android-sdk/extras/google/m2repository/com/android/support/appcompat-v7/22.2.0/appcompat-v7-22.2.0.pom
         file:/C:/Android-sdk/extras/google/m2repository/com/android/support/appcompat-v7/22.2.0/appcompat-v7-22.2.0.jar
     Required by:
         product-catalogue-android-master:app:unspecified
   > Could not find com.android.support:cardview-v7:22.2.0.
     Searched in the following locations:
         https://jcenter.bintray.com/com/android/support/cardview-v7/22.2.0/cardview-v7-22.2.0.pom
         https://jcenter.bintray.com/com/android/support/cardview-v7/22.2.0/cardview-v7-22.2.0.jar
         https://repo.commonsware.com.s3.amazonaws.com/com/android/support/cardview-v7/22.2.0/cardview-v7-22.2.0.pom
         https://repo.commonsware.com.s3.amazonaws.com/com/android/support/cardview-v7/22.2.0/cardview-v7-22.2.0.jar
         file:/C:/Android-sdk/extras/google/m2repository/com/android/support/cardview-v7/22.2.0/cardview-v7-22.2.0.pom
         file:/C:/Android-sdk/extras/google/m2repository/com/android/support/cardview-v7/22.2.0/cardview-v7-22.2.0.jar
     Required by:
         product-catalogue-android-master:app:unspecified

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED
What should i do next...anyone can guide me?

A: Update your Android Support Repository, Android Support Library
And set
compile 'com.android.support:appcompat-v7:23.0.1'

And
 compileSdkVersion 23
 buildToolsVersion "23.0.1"

and
targetSdkVersion 23


text:
Q: Can not show sub-menu when using the scroll bar on a sub menu I'm using bootstrap for my multi drop down menu. But it has a problem, i want to show sub menu when scroll bar on a sub menu but it's not working for me,anyone can help me? please check my screenshot and my code,thank you very much.
Screenshot :
 https://photos.google.com/share/AF1QipN1gUlcuB3zpUZ-scjmd6vhZyDFM8S-GsUUKH-SjGbTbI7kuz1Z-1JTfViNwt2B7w?key=QkVhOThzMXFzVFJrbGctRGFEQUpYRVhDa1Z0cTBR
Demo:

$(function () {
            $(".dropdown-menu > li > a.trigger").on("click", function (e) {
                var current = $(this).next();
                var grandparent = $(this).parent().parent();
                if ($(this).hasClass('left-caret') || $(this).hasClass('right-caret'))
                    $(this).toggleClass('right-caret left-caret');
                grandparent.find('.left-caret').not(this).toggleClass('right-caret left-caret');
                grandparent.find(".sub-menu:visible").not(current).hide();
                current.toggle();
                e.stopPropagation();
            });
            $(".dropdown-menu > li > a:not(.trigger)").on("click", function () {
                var root = $(this).closest('.dropdown');
                root.find('.left-caret').toggleClass('right-caret left-caret');
                root.find('.sub-menu:visible').hide();
            });
        });
.dropdown-menu > li {
            position: relative;
            -webkit-user-select: none; /* Chrome/Safari */
            -moz-user-select: none; /* Firefox */
            -ms-user-select: none; /* IE10+ */
            /* Rules below not implemented in browsers yet */
            -o-user-select: none;
            user-select: none;
            cursor: pointer;
        }

        .dropdown-menu .sub-menu {
            left: 100%;
            position: absolute;
            top: 0;
            display: none;
            margin-top: -1px;
            border-top-left-radius: 0;
            border-bottom-left-radius: 0;
            border-left-color: #fff;
            box-shadow: none;
        }

        .right-caret:after, .left-caret:after {
            content: "";
            border-bottom: 5px solid transparent;
            border-top: 5px solid transparent;
            display: inline-block;
            height: 0;
            vertical-align: middle;
            width: 0;
            margin-left: 5px;
        }

        .right-caret:after {
            border-left: 5px solid #ffaf46;
        }

        .left-caret:after {
            border-right: 5px solid #ffaf46;
        }

  .sub-menu {
      height: 200px;
      overflow-y: scroll;
    }

    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

    <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css">

        Click Here

                Level 1

Level 2

               Level 2

Level 3

Level 3

               Level 3

Level 4

Level 4

Level 4

Level 2

Level 1

Level 1

A: I think You need this.I hope This will help you.

 $(function () {
            $(".dropdown-menu > li > a.trigger").on("click", function (e) {
                var current = $(this).next();
                var grandparent = $(this).parent().parent();
                if ($(this).hasClass('left-caret') || $(this).hasClass('right-caret'))
                    $(this).toggleClass('right-caret left-caret');
                grandparent.find('.left-caret').not(this).toggleClass('right-caret left-caret');
                grandparent.find(".sub-menu:visible").not(current).hide();
                current.toggle();
                e.stopPropagation();
            });
            $(".dropdown-menu > li > a:not(.trigger)").on("click", function () {
                var root = $(this).closest('.dropdown');
                root.find('.left-caret').toggleClass('right-caret left-caret');
                root.find('.sub-menu:visible').hide();
            });
        });
 .dropdown-menu > li {
            position: relative;
            -webkit-user-select: none; /* Chrome/Safari */
            -moz-user-select: none; /* Firefox */
            -ms-user-select: none; /* IE10+ */
            /* Rules below not implemented in browsers yet */
            -o-user-select: none;
            user-select: none;
            cursor: pointer;
        }

        .dropdown-menu .sub-menu {
            left: 100%;
            position: absolute;
            top: 0;
            display: none;
            margin-top: -1px;
            border-top-left-radius: 0;
            border-bottom-left-radius: 0;
            border-left-color: #fff;
            box-shadow: none;
        }

        .right-caret:after, .left-caret:after {
            content: "";
            border-bottom: 5px solid transparent;
            border-top: 5px solid transparent;
            display: inline-block;
            height: 0;
            vertical-align: middle;
            width: 0;
            margin-left: 5px;
        }

        .right-caret:after {
            border-left: 5px solid #ffaf46;
        }

        .left-caret:after {
            border-right: 5px solid #ffaf46;
        }

    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

    <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css">

        Click Here

                Level 1

Level 2

               Level 2

Level 3

Level 3

               Level 3

Level 4

Level 4

Level 4

Level 2

Level 1

Level 1


text:
Q: Why does the sequence operator 0-2:-4 lead to -2 -1 0 1 2 3 4? Typing in 0-2:-4 returns [1] -2 -1  0  1  2  3  4 in the console. Can anyone explain the logic behind this?

A: Because of the order of operation:
0 - (2:-4)

which expands to
0 - c(2, 1, 0, -1, -2, -3, -4)

See ?Syntax for more details, including a complete list of binary operators in order of precedence.


text:
Q: Android location only refreshes after opening google maps on Android Emulator When I open the app it reports the coordinates of the device. Then I change the coordinates using the emulator's menu, close and reopen the app, and the old coordinates still show. After opening Google Maps, for a while the location icon is grey and then it jumps to the new location. Then I open my app again and it's in the correct place now.
The code I'm using is really simple. Here it is:
FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    fusedLocationClient.getLastLocation().addOnCompleteListener(
            new OnCompleteListener<Location>() {
                @Override
                public void onComplete(@NonNull Task<Location> task) {
                    Location location = task.getResult();

                    Toast.makeText(MainActivity.this, "" + location.getLongitude(), Toast.LENGTH_LONG).show();
                }
            }
    );

I assume Google Maps is somehow force refreshing the location. How can I do this on my own app?


text:
Q: useState in react not pushing into my array first try I am trying to push values to an array with usestate, always have an empty array first !
After a while i decide to providse the entire runnable code and hope someone can help
const Tasks = () => {
  const [task, setTask] = useState('');
  const [tasks, setTasks] = useState([]);

    const addTask = (e) => {
    e.preventDefault();
    setTasks([
      ...tasks,
      {
        id: tasks.length,
        description: task,
      },
    ]);
    setTask('');
  };
return (
    <form
      onSubmit={addTask}
      noValidate
      autoComplete="off"
    >
      <TextField
        value={task}
        id="standard-basic"
        label="Type and Enter to add a task"
        onChange={(e) => {
          setTask(e.target.value);
        }}
      />
    </form>
  );
};
export default Tasks;

Codesandbox runnable code here

A: I guess you did not update your state correctly. Use function like this if your new state depends on old one.
   setTasks(prevState => [
      ...prevState,
      {
        id: prevState.length,
        description: task,
      },
    ]);

A: Try this one
    const addTask = (e)=>{
    e.preventDefault()
    const newTask = {
    id:tasks.length,
    description:task
    }
    setTasks((prevState)=>[...prevState,newTask])
    setTask("")
     }


text:
Q: How to subtract in R Programming Language Here is my syntax:
a <-as.integer(a)
a <-readline(prompt = "Enter first number: ")
b <-as.integer(b)
b <-readline(prompt = "Enter second number: ")
c = a-b
print(paste("Difference of two number is :",c)

and the output is this:

print(paste("Difference of two number is :",c))
Error in paste("Difference of two number is :", c) :
cannot coerce type 'builtin' to vector of type 'character'

can someone explain to me what is the error and help me this my first time learning r language

A: *

*the first issue is that you should cast a and b as numerics after you input them

*the second issue that that value assignment in R uses <- rather that =

*edit: As mentioned in the comments: = does work in place of <-, but there is just a preference for <-
The following code will work :-)
a <-readline(prompt = "Enter first number: ")
a <-as.integer(a)
b <-readline(prompt = "Enter second number: ")
b <-as.integer(b)
c <- a-b
print(paste("Difference of two number is :", c))


text:
Q: Android: HttpUrlConnection object returns error 301 after connection I'm trying to connect to a web API using a URL. However, I get a 301 error from the server (Moved Permanently), although the provided URL works very well with no errors when I try it in my browser.
Here is the code that builds the URL:
 public Loader<List<Earthquake>> onCreateLoader(int i, Bundle bundle) {

        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        String minMagnitude = sharedPrefs.getString(
                getString(R.string.settings_min_magnitude_key),
                getString(R.string.settings_min_magnitude_default));

        String orderBy = sharedPrefs.getString(
                getString(R.string.settings_order_by_key),
                getString(R.string.settings_order_by_default)
        );

        Uri baseUri = Uri.parse(USGS_REQUEST_URL);
        Uri.Builder uriBuilder = baseUri.buildUpon();

        uriBuilder.appendQueryParameter("format", "geojson");
        uriBuilder.appendQueryParameter("limit", "10");
        uriBuilder.appendQueryParameter("minmag", minMagnitude);
        uriBuilder.appendQueryParameter("orderby", orderBy);
        Log.i ("the uri is ", uriBuilder.toString());
        return new EarthquakeLoader(this, uriBuilder.toString());
    }

Here is the code that tries to connect to the resource represented by the URL:
private static String makeHttpRequest(URL url) throws IOException {
        String jsonResponse = "";

        // If the URL is null, then return early.
        if (url == null) {
            return jsonResponse;
        }
        Log.i("The received url  is " , url +"");
        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000 /* milliseconds */);
            urlConnection.setConnectTimeout(15000 /* milliseconds */);
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            // If the request was successful (response code 200),
            // then read the input stream and parse the response.
            if (urlConnection.getResponseCode() == 200) {
                inputStream = urlConnection.getInputStream();
                jsonResponse = readFromStream(inputStream);
            } else {
                Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode()); //this log returns 301
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (inputStream != null) {
                // Closing the input stream could throw an IOException, which is why
                // the makeHttpRequest(URL url) method signature specifies than an IOException
                // could be thrown.
                inputStream.close();
            }
        }
        return jsonResponse;
    }

I could know that the connection returns status code of 301 from the log provided in the case when the status code is not 200. I have also logged the generated URL, I copied it from the logcat and tried it in my browser and it worked well. Here is the built URL: http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&limit=10&minmag=6&orderby=magnitude
I checked this question: Android HttpURLConnection receives HTTP 301 response code but it wasn't clear to me what is the solution for the problem.
Can you please help me identify and solve the problem?
UPDATE: As greenapps indicated in his comment, the connection is done through https. That comment identified the problem and helped me fix the code.
In my code, the string I used to build the basic URL, had the protocol value as http not https, it was:
private static final String USGS_REQUEST_URL =
            "http://earthquake.usgs.gov/fdsnws/event/1/query";

After reading greenapps comment, I just changed the protocol part in the string to https, so it became:
 private static final String USGS_REQUEST_URL =
            "https://earthquake.usgs.gov/fdsnws/event/1/query";

That solved the problem.
Thanks.

A: If you click your http link here you will see that the browser shows a https page. You better use that url directly as there is redirection now.

A: This is because the address http to https transferred.
To avoid this, you need to convert the request address to https.


text:
Q: Google map not displayed in my android application now it displayed before two days I developed apps with google map.I got map key i got google map in my application two days before .I did nt change anything but now i did not get the google map only show boxes .The logcat show couldn't get connection factory client error.I searched this error but i can't get clear ans as well as map .So plz anyone help me to solve this problem.
Thanks ,
Lakshmanan

A: I've had that error appearing as well, so please check the following :

*

*Your API Key has been correctly generated (sadly, no tool to check for that) (see this tutorial)

*You have a INTERNET permission in your manifest, within the <manifest> tag

*You have a uses-library within the <application> tag

*You start the emulator with a Google Maps API Target

*You have internet (3G display) within the emulator

Just a small checklist, hope this helps !


text:
Q: Contained draggable div with random positioning has 'no' bottom limits Here is where I am for the moment : http://jsfiddle.net/___Vikus___/tk0mn4je/
$(function () {
    $(".col1").each(
    function (intIndex) {
        var l = Math.floor(Math.random() * $(".col1").width());
        var r = Math.floor(Math.random() * $(".col1").height());
        $(this).css("left", l);
        $(this).css("top", r);
    });
    $(".col1").draggable({
        containment: "#wraper",
        scroll: false,
        stack: ".col1"
    });
});

The script for random positioning works fine but the draggable propriety has no bottom containment. So how could I limit my random positioning inside a div ? Or, what could I do to create a real bottom limit ?


text:
Q: GORM Mapping Manifesto :: To Long or not to Long Fairly basic problem but it's roots run deep in the framework (and there is little definitive information on the subject), so I am putting it out here so as to save others the pain (and to verify that I am correct or not in my thinking).
What is the problem?
Grails automatically injects an id field of type Long into your domains (see Beckwith's comment). When using a legacy DB Grails maps Longs to bigints by default, an inefficient storage type that anyone dealing with large million+ record tables would avoid.
Upon discovering this a few months ago I set to work on getting a "proper" column type in place for my domain ids. Not having a Java background, blindly I thought, Long-bad, Integer-good and set hibernate mapping dialect for Integer types to what I would do by hand in mysql

registerColumnType(Types.INTEGER, 'mediumint unsigned')

and then defined "Integer id" in all of my domains (not necessary according to Bert's comment in link above). Everything worked swimmingly, wonderful, on to other things.
Fast forward to Grails 2.0 (as I could not resist all of the goodies ;-)) and Spock. For the life of me I could not figure out why, despite 2.0 new in-memory GORM and support for dynamic finders, that Domain.findByFoo(fooVal) would always return null (yes, I @Mock(Domain) and populate with test data). In fact, both within the test itself and @TestFor target, the only GORM methods that worked were save() and get(); everything else returned null.
I whipped up a quick test app, domain + controller + spoc spec and discovered the source of the problem: If you use a property type other than Long for your ids (including referenced FKs), your @Mock domain(s) will be rendered useless.
So, am I correct or not in saying that one must use Long ids in order to take full advantage of the framework? @Mock + @TestFor + Spock is an incredible combo!  Guidance appreciated before I head down refactor-to-Long road...

A: I cannot imagine any realistic scenario where the difference between Integer and Long would make any noticeable difference to performance (which seems to have been the original motivation for making this change).
If using Long works, but Integer causes problems, then use Long and move onto more important tasks. I would only worry about this if you can prove that using Integer makes any significant difference.
Update
You're right, I did completely miss the point about the database type that Grails automatically uses for Long. As you seem to already know, you can control the database type in the mapping closure of your domain class, e.g.
class Person {
   Long id

   static mapping = {
      // See here for alternatives to integer, and how they map to DB types
      // http://docs.jboss.org/hibernate/stable/core/manual/en-US/html/mapping.html#mapping-types-basictypes
      id type:'integer'
   }
}

You also brought up in the comments

dealing with Long at code level where one must specify def foo(Long id) {...} and params.id.toLong() as opposed to Integer

You can simply define an action as
def myAction = {Person p ->

}

or
def myAction = {
   Person p = new Person(params)
}

And Grails will take care of type-converting the id request parameter to Person.id, regardless of whether it's a Long, Integer, BigDecimal, etc.


text:
Q: Hidden values in an extension - encode decode data transaction I found an interesting extension for onepagecheckout. It seems to be free but when I installed the extension I realized that the code is sending and encoding data to developer servers. In theory its validating a license value - I don't know why because its free, additionally the site is not telling anything about that hidden value passed to their servers but.. OK. - its free.
Based on the fact that this particular area manages information about credit cards I would like to know which values are they passing. In my research I found that the code send to their servers are in a line called id=opc_s_data with a call to:
public function getSUrl($mode = '') {
    $code = Mage::getStoreConfig('onepagecheckout/sdatacode');
    eval(base64_decode($code));
    if(!isset($url))
        $url = '';
    return $url;
}

and the value sent is something like:
<input type='hidden' id='opc_s_data'
    value='http://company.com/magento/opclicense/opcaction.php?sdata=bWFEuN......=='/

Does anyone know what can I do to decode the information sent to my application from their servers? If I erase this hidden ID the onepagecheckout doesn't work.
Disclaimer: I wrote to the developer but I never received a response.

A: Marius, Thanks for the investigation. I too, highly dislike and discourage magento module creators to ads these type of "phone home calls" to their extensions. They should be exposed and eradicated.
To disable the phone home call, and keep your onepagecheckout extension working (yes, they can disable it)
do the following.
Copy the file /skin/frontend/base/default/js/onepagecheckout.pack.js to your theme folder/js/onepagecheckout.pack.js and beautify the code using a site like:
http://jsbeautifier.org/
Now around line:244 in the start method
You'll see
addjsphp(this.s_code);
this.getActionResults(0)

change it to
//addjsphp(this.s_code);
//this.getActionResults(0)

This will stop the script from always phoning home to their slow website, and will stop it from action on the code results
This should work, but test it before you roll it out. It is your checkout after all

A: First of all I want to say that this is an ugly way of doing things. Most probably the ugliest. If you didn't want to add the company name in here I will. It's interiorwebdesign.com. Most probably the things sent to their server are the magento version, the extension version and the url of your website. You can check for sure by doing base64_decode on the value of the sdata parameter sent to them. I don't know what the answer should be if your licence is correct, but in case there is an error this is the response:
checkout.o_p_c_l_s = '2';
deljsphp();

Look in the code for a function called deljsphp. I think that disables your checkout.
[EDIT]
Because I get mad when I see these types of extensions I decided to waste some time for investigating.
Here is what I found.
The result of the request should be a link to a js file or some js code on their server. After decoding the js file from the extension I found this function:
start: function () {
    this.s_code = $('opc_s_data').value;
    $('opc_s_data').remove();
    if (this.s_code == '') {
        this.opcdis();
        return false
    }
    addjsphp(this.s_code);
    this.getActionResults(0)
},

so if the code 'license' is valid some js is added to the DOM through addjsphp that looks like this:
function addjsphp(u) {
    var me = document.createElement('div');
    me.setAttribute('id', 'opcstataj');
    var p = 'html';
    var th1 = document.getElementsByTagName(p)[0];
    th1.appendChild(me);
    var th = document.getElementById('opcstataj');
    var s = document.createElement('script');
    s.setAttribute('language', 'javascript');
    s.setAttribute('type', 'text/javascript');
    s.setAttribute('src', u);
    th.appendChild(s)
}

I don't know (yet) how the js from their server should look like, but here is what you can try. Not sure if it works. Edit the js file skin\frontend\base\default\js\onepagecheckout.pack.js and at the end of the file add this:
function deljsphp(){
    return 1;
}

This should override the original deljsphp function, that by the way looks like this:
function deljsphp() {
    var th = $('opcstataj');
    if (th && th != null && th != undefined) th.remove()
}

Basically it removes the <script> tag added from their server.
Other info
The code that is being eval'd in the the line you mentioned in the question is this:

eval(gzinflate(base64_decode('jZAxb8MgEIXn+FfQCBl7qL1UHRLRDFGkLlWjOM0SVRHBV4NqwIKLqqrKfy84S9MuXeDgcd97BzWiI5xQVDrcPnSAT6IDi24HPmhni3KeUePaqyfP6+VPWV2Jy5Nv0Hl48X1UJ5OMhqhPow3/onE95xGXSteec2WFgXhQ51xIjEAuFcj3aaS2AkVsPIoA93cHsNK1UNAwGiZicQNmwM+CHprVZrfa7Nnjdrtu2GtJ8pz8ueWcM2dZuWAKcQhsNu4s0k6+TwOoULFZXWuL4LXzH3BsIejOVtKZ2lw+pXaD7LUEGyCVl8jVoIZFSHE5q8bY80y/FWlAIJwThhCQlb+NeidFr1zA/0K/AQ==')));

Going further...this is the code that actually gets evaluated:
$mag = $this->getMagentoVersion();
$mod = $this->getOPCVersion();
$h = $this->getCurStoreUrl();
$s = "mag={$mag}&mod={$mod}&hname={$h}&action=check";
$data = base64_encode($s);
$hs = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']==='on')?'https':'http';
$url = $hs.'://interiorwebdesign.com/magento/opclicense/opcaction.php?sdata='.$data;
if($mode == 'test')
    $url = $hs.'://localhost/opclicense/opcaction.php?sdata='.$data;

This confirms my initial suspicions on what is sent to their servers.

A: I would like to say that this regular code was just about to collect information on what version was used by our clients. No other information was collected.
We also have removed that since version 3, which was released like about 1.5 years ago. So, if you use version 2 still, it's time for you to upgrade to version 4.x