text:
Q: Is it possible to zoom in and out on the contents of a div? I'm trying to make a system similar to that of google maps with panning and zooming with the contents of a div. This div will have different buttons, links and images. I just can't find a way to do it without using a canvas. Any ideas on how this could be done?

A: you  can do this by Zoomooz.js
Simply add "zoomTarget" to the element you want to zoom to when clicked on:

This element zooms when clicked on.

You can also add some additional attributes for tuning the animation as data fields of the element:

This element zooms when clicked on.

from the source  Zoomooz.js

A: I have created a simple zoom in zoom out div
(http://jsfiddle.net/tamilselvanA/05erzotj/5/) with using  references
(https://rbalajiprasad.blogspot.in/2012/02/zoom-in-zoom-out-jquery.html).

$(document).ready(function() {
  var currZoom = $("#divpnlChart").css("zoom");
  if (currZoom == 'normal') currZoom = 1;

  $(".zoomIn").click(function() {
    currZoom *= 1.2;
    $("#divpnlChart").css("zoom", currZoom);
    $("#divpnlChart").css("-moz-transform", "Scale(" + currZoom + ")");
    $("#divpnlChart").css("-moz-transform-origin", "0 0");

  });
  $(".zoomOff").click(function() {
    $("#divpnlChart").css("zoom", 1);
    $("#divpnlChart").css("-moz-transform", "Scale(" + currZoom + ")");
    $("#divpnlChart").css("-moz-transform-origin", "0 0");

  });
  $(".zoomOut").click(function() {
    currZoom *= .8;
    $("#divpnlChart").css("zoom", currZoom);
    $("#divpnlChart").css("-moz-transform", "Scale(" + currZoom + ")");
    $("#divpnlChart").css("-moz-transform-origin", "0 0");

  });
});

var down = false;
var scrollLeft = 0;
var x = 0;

$('#sd').mousedown(function(e) {
  down = true;
  scrollLeft = this.scrollLeft;
  x = e.clientX;
}).mouseup(function() {
  down = false;
}).mousemove(function(e) {
  if (down) {
    this.scrollLeft = scrollLeft + x - e.clientX;
  }
}).mouseleave(function() {
  down = false;
});
#sd {
  border: 1px solid black;
  height: 1200px;
  margin: 50px auto;
  overflow: scroll;
  width: 500px;
}

#divpnlChart {
  height: 100px;
  width: 900px;
}

+

original

-

  CHENNAI: Actor Kamal Haasan has alleged that right wing Hindus have started employing terrorism to propagate their communal agenda.

  In his column in a Tamil magazine that hit stands on Thursday, the 62-year-old actor said the right-wingers could no longer say "show me a Hindu terrorist if you can." Terrorism has spread into their fold also, he said.

  "Earlier, the right-wing Hindus employed debates, and not force, against people of other religions. Having realised that their attempts are failing, they have started using violence," he wrote.

  "This is not a victory or a sign of progress. If we start believing that force will prevail and not truth, then we will all turn into violent beasts," he wrote.

  In his column, Kamal was replying to a question posed by Kerala chief minister Pinarayi Vijayan who had sought the actor's opinion on "the attempt by Hindutva forces to infiltrate into Tamil Nadu."

  Kamal wrote: "Only change is permanent. No matter how many forces push it back, Tamil Nadu will once again prevail as the forerunner in social reforms. Kerala is standing as an example today. Congrats for that."

<a href="https://ade.clmbtech.com/evnt/click.htm?r=MjExMTI4YjYtZGUwOS00OWQ4LTkwOTAtZTRlMmY4YzYzMGRhLTEwb253OjEyOTE0NjphbGwsNXE2LDV4cSw5bmo6MTQ3MDIwMTg6MjE6MTMzMTAzOTo3MzM6OjoxLjA2OjA6NjE0NTM2NzIxOjE6Mjk1NjI6MDo6OjI6MTIxLjIwMC41NC4yMDY6TW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzYxLjAuMzE2My4xMDAgU2FmYXJpLzUzNy4zNjo6MC4wOjA6MDo4ODQtMToxNjoxOjA6MDo0Ojo6MTUwOTYyMDkyODc2MjpmYWxzZQ&fpc=99e43293-2827-4598-9d0d-c435bc993f90-10o79&i=U932w528X919&s=https%253A%252F%252Ftimesofindia.indiatimes.com%252Fcity%252Fchennai%252Fsaffron-terrorism-kamal-haasan-says-right-wing-hindus-have-started-employing-terrorism%252Farticleshow%252F61453672.cms&u=http%3A%2F%2Fwww.zeeayurveda.com">Improve your power, vigor, vitality & staminaZEEAYURVEDA

<a href="https://ade.clmbtech.com/evnt/click.htm?r=MjExMTI4YjYtZGUwOS00OWQ4LTkwOTAtZTRlMmY4YzYzMGRhLTEwb253OjEyOTE0NjphbGwsNXE2LDV4cSw5bmo6MTcyNDAwMDY6MjoyMTMyNzkyOjczMzo6OjIuMzY3OTQ4MTAxODkxNzIxOjA6NjE0NTM2NzIxOjE6NDI2OTg6MDo6OjI6MTIxLjIwMC41NC4yMDY6TW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzYxLjAuMzE2My4xMDAgU2FmYXJpLzUzNy4zNjo6MC4wOjA6MDoyNTMxLTE6MTY6MTowOjA6NDo6OjE1MDk2MjA5Mjg3NjI6ZmFsc2U&fpc=99e43293-2827-4598-9d0d-c435bc993f90-10o79&i=U932w528X919&s=https%253A%252F%252Ftimesofindia.indiatimes.com%252Fcity%252Fchennai%252Fsaffron-terrorism-kamal-haasan-says-right-wing-hindus-have-started-employing-terrorism%252Farticleshow%252F61453672.cms&u=http%3A%2F%2Fwww.custom-trackx.com%2Fa860c2d2-aed7-4e80-a5e4-3faf4641310f%3Fadid%3Ddx15%26head%3DBurn_upto_20_kgs_with_this_easy_method%26imag%3D20">Burn upto 20 kgs with this easy method.Nutralyfe

Recommended By Colombia

  Kamal pointed out that Tamil Nadu's Dravidian tradition is thousands of years old and said the social revolution brought on by Ramanujam 1,000 years ago is a landmark.

  Kamal wrote, "There is no possibility that the attempt by fascists to shift the world towards the right will succeed. The shift towards the right is only a temporary fashion, a cosmetic change. It will not last. The backward old generation, particularly those belonging to the upper castes, which is rattled by the equality evolving in society, is trying to feed their caste-driven, backward ideology to the young generation by sugar coating it and presenting it as a modern idea."

Top Comment
if Hindus would have adapted terrorism, then shameless chapa like him would not existed.OMSM
<input type="button" data-plugin="show-comments" data-type="allcomment" class="btn" value="See All Comments" pg="TopComment#SeeAllComments#https://timesofindia.indiatimes.com/city/chennai/saffron-terrorism-kamal-haasan-says-right-wing-hindus-have-started-employing-terrorism/articleshow/61453672.cms"><input type="button" data-plugin="show-comments" data-showtype="autofocus" data-type="addcomment" class="btn" value="Add Comment" pg="TopComment#AddComment#https://timesofindia.indiatimes.com/city/chennai/saffron-terrorism-kamal-haasan-says-right-wing-hindus-have-started-employing-terrorism/articleshow/61453672.cms">

  Stating that the affinity that human race has towards science and wisdom will draw them towards rationalism despite opposition, Kamal said, "The youth in the state are not waiting for the change to happen. They have stepped into the fray to protect Tamil Nadu."

  According to him, the conservatives are not stressing on what needs to be learned from the past tradition. "Destroying agriculture for commercial gains and selling mythology as history are evils they have been tirelessly carrying forward for ages," he wrote.


text:
Q: Truncating a Time-Series Graph I'm looking for a way to truncate outliers in a time-series graph.
Some context:
I'm plotting two different metrics on a single graph.  It's important to understand what portion of "Metric A" takes up respective to "Metric B".  "Metric B" can at times spike to a high value thus increasing the Y-Axis scale which then minimizes the visibility of Metric "A".
Are there any good formulas that help normalize this data or visual treatments that can make the graphic honest as well as accessible?
See screenshot for more context.  The blue area is "Metric B".

Thanks!

A: If Metric B spikes up too much (say to more than twice the maximum of Metric A), you can display it as a vertical blue column with a jagged break in the middle to indicated it goes off the top of the graph.  I have also seen it with a jagged break and an arrow on the top.  You can also list the specific data point to show how tall the spike is.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get UTC time without SimpleDateFormat? I'm currently working on timestamps that are converted from and to UTC. All articles that I found were based on conversion to and from String. Like this one:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = simpleDateFormat.parse(rawQuestion.getString("AskDateTime"));

But I wonder if there is a way to simply work with the Date instance/class or the calendar to convert the local Date into UTC and vice versa without converting it to String in between.

A: Read up on Joda-Time. That is a better API for such things than the java date and calendar classes

A: maybe this can help you:
Calendar.getInstance(java.util.TimeZone)

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

A: java.until.Date does not have a timezone, so there's nothing to be converted. You only see a timezone when you format the date to a string explicitly, or implicitly by using its toString method. An implicit conversion uses the local default timezone.
Internally, Date stores the date/time as a long, representing milliseconds since midnight, Jan. 1, 1970, UTC.
So, if you format a date as a string, and then parse the string back to a date, you've changed nothing at all.

A: So far, I could not find a perfect solution, so I had to stick to the conversion from Date to String and vice versa. Here's a little helper class that I wrote.
public class DateTimeHelper {

    public static final String MYSQL_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static final TimeZone timeZoneUTC = TimeZone.getTimeZone("UTC");

    private Date date = new Date();
    private final SimpleDateFormat format;

    public DateTimeHelper(String dateTimeFormat) {
        format = new SimpleDateFormat(dateTimeFormat, Locale.US);
    }

    public DateTimeHelper(String dateTimeFormat, String utcTimeString) {
        this(dateTimeFormat);

        try {
            format.setTimeZone(timeZoneUTC);
            Date utc = format.parse(utcTimeString);
            format.setTimeZone(TimeZone.getDefault());
            String local = format.format(utc);
            date = format.parse(local);
        } catch (ParseException e) {
            // nothing
        }
    }

    public Date getDate() {
        return date;
    }

    public Date toUtc() {

        String temp = toString();
        format.setTimeZone(timeZoneUTC);
        try {
            return format.parse(temp);
        } catch (ParseException e) {
            return date;
        }
    }

    @Override
    public String toString() {
        format.setTimeZone(TimeZone.getDefault());
        return format.format(date);
    }

    public String toUtcString() {
        format.setTimeZone(timeZoneUTC);
        return format.format(date);
    }
}

And another one that's easier to use:
public class MySqlDateTimeHelper extends DateTimeHelper {

    public MySqlDateTimeHelper() {
        super(DateTimeHelper.MYSQL_DATE_TIME_FORMAT);
    }

    public MySqlDateTimeHelper(String utcTimeString) {
        super(DateTimeHelper.MYSQL_DATE_TIME_FORMAT, utcTimeString);
    }

    public static String getCurrentTimestampUtc() {
        MySqlDateTimeHelper current = new MySqlDateTimeHelper();
        return current.toUtcString();
    }
}


text:
Q: How to convert text file that contain colon seperated data into JSON object? I have a text file that contain colon separated data. How I can convert it into JSON object? I have the following text in a file:
BEGIN:VCARD
VERSION:2.1
FN:Campus Police
N:Campus Police
TEL:555-EDU-HELP
ADR:8230 Boone Blvd.;Bldg 001;;Vienna;VA;22181;
X-MS-OL-DEFAULT-POSTAL-ADDRESS:01155
EMAIL:police@wisconsin.edu
REV:20120501T180000Z
END:VCARD
BEGIN:VCARD
VERSION:2.1
FN:Campus Medical Clinic
N:Campus Medical Clinic
TEL:555-EDU-HURT
ADR:8230 Boone Blvd.;Bldg 001;;Vienna;VA;22181;
X-MS-OL-DEFAULT-POSTAL-ADDRESS:01155
EMAIL:medical@wisconsin.edu
REV:20120501T180000Z
END:VCARD

A: Below code is in java. May be you need few changes according to your requirements.
   import java.io.BufferedReader;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;

    public class Main {
        public static void main(String[] args) throws IOException {
            readFile();
        }

        public static void readFile() throws IOException {
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream("d:/input.txt");
                BufferedReader  br = new BufferedReader(new InputStreamReader(fileInputStream));
                String line = null;
                String obj = new String("[");
                while ((line = br.readLine()) != null) {
                    if (line.split(":").length > 1) {
                        Entry entry = new Entry(line.split(":")[0], line.split(":")[1]);
                        obj = obj +" \n "+ entry.toString();
                    }
                }
                obj = obj.replaceAll("\"BEGIN\":\"VCARD\"", "{");
                obj = obj.replaceAll("\"END\":\"VCARD\"", "},");
                obj = obj.substring(0, obj.lastIndexOf(","));
                obj = obj + "\n]";

                System.out.println(obj);
                br.close();
            } catch ( Exception e) {
                System.out.println(e);
            } finally {
                fileInputStream.close();
            }
        }
    }

    class Entry {
        private String key;
        private String value;
        Entry (String key, String value) {
            this.key = key;
            this.value = value;
        }

        @Override
        public String toString() {
            return "\""+ key + "\"" +  ":" +  "\"" +  value + "\"";
        }
    }

output is similar to json format.

[
 {
 "VERSION":"2.1"
 "FN":"Campus Police"
 "N":"Campus Police"
 "TEL":"555-EDU-HELP"
 "ADR":"8230 Boone Blvd.;Bldg 001;;Vienna;VA;22181;"
 "X-MS-OL-DEFAULT-POSTAL-ADDRESS":"01155"
 "EMAIL":"police@wisconsin.edu"
 "REV":"20120501T180000Z"
 },
 {
 "VERSION":"2.1"
 "FN":"Campus Medical Clinic"
 "N":"Campus Medical Clinic"
 "TEL":"555-EDU-HURT"
 "ADR":"8230 Boone Blvd.;Bldg 001;;Vienna;VA;22181;"
 "X-MS-OL-DEFAULT-POSTAL-ADDRESS":"01155"
 "EMAIL":"medical@wisconsin.edu"
 "REV":"20120501T180000Z"
 }
]


text:
Q: Access file in WebContent folder from a servlet I'm trying to generate a PDF document using FOP. The pdf generation code is kept in a servlet and the xsl is in a specific folder in the WebContent folder.
How can I access this xsl file by giving a relative path? It works only if I give the complete path in the File object.
I need to generate the xml content dynamically. How can I give this dynamically generated xml as the source instead of a File object?
Please provide your suggestions.

A: For a direct and independent container implementation, you can access the resourcewith the following method getResource() inside your servlet:
/start servlet/
public InputStream getResource(String resourcePath) {
  ServletContext servletContext = getServletContext();
  InputStream openStream = servletContext.getResourceAsStream( resourcePath );
  return openStream;
}

public void testConsume() {
  String path = "WEB-INF/teste.log";
  InputStream openStream = getResource( path );

  int c = -1;
  byte[] bb = new byte[1024];
  while ( -1 != ( c = openStream.read( bb ) ) ) {
    /* consume stream */
  }
  openStream.close();
}

/end servlet/

A: To get the path you can just do:
String path = s.getServletContext().getRealPath("/WEB-INF/somedir/hdfeeh");

s is the class that implements HTTPServlet.You can also use this.getServletContext() if its your servlet class.
Then pass this as a parameter.
As far as using dynamically generated XML, the library you're using should support using an input stream, write your XML, convert it to a byte array, then wrap it in a ByteArrayInputStream and use this.

A: I used the following method to read the file under web content
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getSession().getServletContext().getResourceAsStream("/json/sampleJson.json")));

Now all the file content is available in the reader object.


text:
Q: How should electron app handle a OAuth callback I am pretty fresh to the electron, and I am working on building an application that uses Facebook/Google to authorize a user. Everything works fine when I am working on development, when I just use localhost:3000 as the callback URL for Facebook/Google API. But when I build the app and run it, things just fell apart. I followed the steps on this medium post here to configured the building proces. And to make it simple I just used the npm submodule: react-facebook-login, react-google-login.
I thoughts there should be any difference between these two, but the process works fine on dev but not on built app:

Should I treat this case as a native app and rebuild the authorization from scratch instead of using node module?

A: Part of the way OAuth2 works is that the step of getting the authorisation code invokes the login dialog you see from Facebook or Google or whatever. For your app to regain control after that dialog is done requires your request to open the dialog to specify a "redirect_url" at which your app will get back control.
Also, part of the security is that Facebook or Google or whatever will check the redirect_url you specify against some preconfigured settings.
Therefore:

*

*You have to configure the redirect URL(s) you plan to use

*You have to ensure that the redirect URL used matches one you configured

Failing either will typically result in a messae like the one you are seeing.


text:
Q: easy thumbnail, without thumbnail image works but with thumbnail, nothing shows up my image is displayed without thumbnail functionality, but as soon as I put thumbnail I get nothing.
I'm using easy thumbnail, I followed the documentation mainly.
In  template
{% load thumbnail %}
<img src="{{post.image|thumbnail_url:'avatar'}}" alt="" />

In setting
THUMBNAIL_ALIASES = {
    '': {
        'avatar': {'size': (50, 50), 'crop': True},
    },
    }


text:
Q: PyOpengl: Changing gluPerspective variables makes cube flash When using gluPerspective in glutReshapeFunc function, the square image flashes while resizing and is gone after a few moments.
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *

width = 500
height = 500

def cube():
    glBegin(GL_QUADS)
    glColor3f(0, 1, 0)
    glVertex3f(10, 0, 0)
    glVertex3f(10, 10, 0)
    glVertex3f(10, 0, 0)
    glVertex3f(0, 0, 0)
    glVertex3f(10, 0, 0)
    glVertex3f(10, 0, 10)
    glVertex3f(0, 10, 0)
    glVertex3f(10, 10, 0)
    glVertex3f(0, 10, 0)
    glVertex3f(0, 0, 0)
    glVertex3f(0, 10, 0)
    glVertex3f(0, 10, 10)
    glVertex3f(0, 0, 10)
    glVertex3f(0, 0, 0)
    glVertex3f(0, 0, 10)
    glVertex3f(10, 0, 10)
    glVertex3f(0, 0, 10)
    glVertex3f(0, 10, 10)
    glVertex3f(10, 10, 10)
    glVertex3f(10, 10, 0)
    glVertex3f(10, 10, 10)
    glVertex3f(10, 0, 10)
    glVertex3f(10, 10, 10)
    glVertex3f(0, 10, 10)
    glEnd()

def showScreen():
    global width, height

    glClearColor(0, 0, 0, 1)
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    cube()
    glutSwapBuffers()

def mouseTracker(mousex, mousey):
    print(f"Mouse pos: {mousex}, {mousey}")

def reshapeWindow(x, y):
    global width, height
    width = x
    height = y
    print(x, y)
    gluPerspective(45, (width / height), 0.0001, 1000)

glutInit()
glutInitDisplayMode(GLUT_RGBA)
glutInitWindowSize(500, 500)
wind = glutCreateWindow("OpenGL")
glutDisplayFunc(showScreen)
glutIdleFunc(showScreen)
glutMotionFunc(mouseTracker)
glutPassiveMotionFunc(mouseTracker)
glutReshapeFunc(reshapeWindow)
gluPerspective(45, (width / height), 0.0001, 1000)
glTranslatef(0, 0, -5)

while True:
    glutMainLoopEvent()
    glutPostRedisplay()

If I put the gluPerspective into the showScreen function like so:
def showScreen():
    global width, height

    glClearColor(0, 0, 0, 1)
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    cube()
    gluPerspective(45, (width / height), 0.0001, 1000)
    glutSwapBuffers()

The square flashes without resizing but it is gone after a few moments. If I remove the gluPerspective entirely, the image turns into a triangle. Is there any way to change gluPerspective variables without making the image flash?

A: You have to call gluPerspective before drawing the cube. The matrix operations not only set the current matrix, but define a new matrix and multiply the current matrix by the new matrix. Therefore you must load the Identity matrix with glLoadIdentity before modifying the matrix. The legacy OpenGL provides different current matrices for the model view matrix and the projection matrix. Before changing a matrix, select the matrix mode with glMatrixMode:
Change the projection matrix in the reshape callback:
def reshapeWindow(x, y):
    global width, height
    width = x
    height = y
    print(x, y)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(45, (width / height), 0.0001, 1000)
    glMatrixMode(GL_MODELVIEW)

Set the model view matrix before the application loop or in the application loop:
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslatef(0, 0, -5)

gluPerspective defines a Viewing frustum. The center of the view is (0, 0). Hence you need to change the vertex coordinates.
I suggest enabling the Depth Test when drawing 3D meshes.
Minimale example based on your code:
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import time

width = 500
height = 500

vertices = [(-1,-1,-1), ( 1,-1,-1), ( 1, 1,-1), (-1, 1,-1), (-1,-1, 1), ( 1,-1, 1), ( 1, 1, 1), (-1, 1, 1)]
faces = [(4,0,3,7), (1,0,4,5), (0,1,2,3), (1,5,6,2), (3,2,6,7), (5,4,7,6)]
colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 0), (1, 0, 1), (0, 1, 1)]

def cube():
    glRotatef(1, 3, 1, 1)
    glBegin(GL_QUADS)
    for i, face in enumerate(faces):
        glColor3fv(colors[i])
        for vertex in face:
            glVertex3fv(vertices[vertex])
    glEnd()

def showScreen():
    glClearColor(0, 0, 0, 1)
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    cube()
    glutSwapBuffers()

def mouseTracker(mousex, mousey):
    print(f"Mouse pos: {mousex}, {mousey}")

def reshapeWindow(x, y):
    global width, height
    width = x
    height = y
    print(x, y)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(45, (width / height), 0.0001, 1000)
    glMatrixMode(GL_MODELVIEW)

glutInit()
glutInitDisplayMode(GLUT_RGBA)
glutInitWindowSize(500, 500)
wind = glutCreateWindow("OpenGL")
glutDisplayFunc(showScreen)
glutIdleFunc(showScreen)
glutMotionFunc(mouseTracker)
glutPassiveMotionFunc(mouseTracker)
glutReshapeFunc(reshapeWindow)

glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslatef(0, 0, -5)

glEnable(GL_DEPTH_TEST)

while True:
    glutMainLoopEvent()
    glutPostRedisplay()
    time.sleep(0.01)


text:
Q: How can I convert a windows path to posix path using node path I'm developing on windows, but need to know how to convert a windows path (with backslashes \) into a POSIX path with forward slashes (/)?
My goal is to convert C:\repos\vue-t\tests\views\index\home.vue to C:/repos/vue-t/tests/views/index/home.vue
so I can use it in an import on a file I'm writing to the disk
const appImport = `
import Vue from "vue"
import App from '${path}'

function createApp (data) {
    const app = new Vue({
        data,
        render: h => h(App)
    })
    return app
}`

//this string is then written to the disk as a file

I'd prefer not to .replace(/\\/g, '/') the string, and would rather prefer to use a require('path') function.

A: Given that all the other answers rely on installing (either way too large, or way too small) third party modules: this can also be done as a one-liner for relative paths (which you should be using 99.999% of the time already) using Node's standard library path module, and more specifically, taking advantage of its dedicated path.posix and path.win32 namespaced properties/functions (introduced in Node v0.11):
const path = require("path");

// ...

const definitelyPosix = somePathString.split(path.sep).join(path.posix.sep);

This will convert your path to POSIX format irrespective of whether you're already on a POSIX compliant platform, or on Windows, without needing any kind of external dependency.

A: Slash converts windows backslash paths to Unix paths
Usage:
const path = require('path');
const slash = require('slash');

const str = path.join('foo', 'bar');

slash(str);
// Unix    => foo/bar
// Windows => foo/bar

A: There is node package called upath will convert windows path into unix.
upath = require('upath');

or
import * as upath from 'upath';

upath.toUnix(destination_path)

A: For those looking for an answer that doesn't depend on Node.js
One Liner (no 3rd party library)
//
// one-liner
//
let convertPath = (windowsPath) => windowsPath.replace(/^\\\\\?\\/,"").replace(/\\/g,'\/').replace(/\/\/+/g,'\/')

//
// usage
//
convertPath("C:\\repos\\vue-t\\tests\\views\\index\\home.vue")
// >>> "C:/repos/vue-t/tests/views/index/home.vue"

//
// multi-liner (commented and compatible with really old javascript versions)
//
function convertPath(windowsPath) {
    // handle the edge-case of Window's long file names
    // See: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#short-vs-long-names
    windowsPath = windowsPath.replace(/^\\\\\?\\/,"");

    // convert the separators, valid since both \ and / can't be in a windows filename
    windowsPath = windowsPath.replace(/\\/g,'\/');

    // compress any // or /// to be just /, which is a safe oper under POSIX
    // and prevents accidental errors caused by manually doing path1+path2
    windowsPath = windowsPath.replace(/\/\/+/g,'\/');

    return windowsPath;
};

// dont want the C: to be inluded? here's a one-liner for that too
let convertPath = (windowsPath) => windowsPath.replace(/^\\\\\?\\/,"").replace(/(?:^C:)?\\/g,'\/').replace(/\/\/+/g,'\/')

Normally I import libraries. However, I went and read the source code for both slash and upath. The functions were not particularly up to date, and incredibly small at the time I checked. In fact, this one liner actually handles more cases than the slash library. Not everyone is looking for this kind of solution, but for those that are, here it is. By coincidence this has the fastest runtime of all the current answers.

A: Just use default lib as:
const {direname, resolve, basename}= require('path').posix;

or
import {posix} from 'path';
const {direname, resolve, basename}= posix;

A: I was looking for something similar, but a little more universal especially to include drives in the absolute path. Thus if you work with e.g. git-bash or WSL usually drives are mapped by default as letters from root / (git-bash) or /mnt (WSL). So here is a regex that does the job for me

// For git-bash Windows drives are mounted in the root like /C/ /D/ etc.
const toGitBashPosixPath = (windowsPath) => windowsPath.replace(/^(\w):|\\+/g,'/$1');

console.log(toGitBashPosixPath('c:\\\\\\project\\file.x')); // messy Windows path
console.log(toGitBashPosixPath('c:\\project\\file.x')); // regular Windows path
console.log(toGitBashPosixPath('c:/project/file.x')); // slash path acceptable by Windows
console.log(toGitBashPosixPath('project\\file.x'));// relative Windows path
console.log(toGitBashPosixPath('.\\project\\file.x'));// another relative Windows path

// For WSL Windows drives are mounted by default next to /mnt like /mnt/C/ /mnt/D/ etc.
const toWSLPosixPath = (windowsPath) => windowsPath.replace(/^(\w):|\\+/g,'/$1').replace(/^\//g,'/mnt/');
console.log(toWSLPosixPath('c:\\project\\file.x'))

Hopefully this will help someone.

A: const winPath = 'C:\\repos\\vue-t\\tests\\views\\index\\home.vue'
const posixPath = winPath.replace(/\\/g, '/').slice(2)
// Now posixPath = '/repos/vue-t/tests/views/index/home.vue'


text:
Q: Retrieve documents starting from a particular document From the following sorted collection in MongoDB, how do I create a new collection so that it contains all documents after the document that contains {"hash": "b"}
{"hash": "a", "key1": "val1", "key2": "val2"},
{"hash": "b", "key1": "val3", "key2": "val4"},
{"hash": "c", "key1": "val5", "key2": "val6"},
{"hash": "d", "key1": "val7", "key2": "val8"}

So I'm trying to create a new collection that contains:
{"hash": "c", "key1": "val5", "key2": "val6"},
{"hash": "d", "key1": "val7", "key2": "val8"}

I can retrieve the doc that contains {"hash": "b"} using find() but that doesn't help me traverse the subsequent elements in the original collection

A: If I understand how you are sorting on the hash value correctly, then the following will do what you want:
db.getCollection('test').aggregate([{$match: {hash: {$gt: 'b'}}},
{$out: 'new'}])

Just replace the name of the collection and the new collection you want to put the results into (the $out operator specifies the latter).


text:
Q: React Leaflet - How to render custom image using Circle Markers I am trying to generate a custom image for my CircleMarkers. I am not sure how to do it. I am using CircleMarkers here because I have almost 20K+ markers and need them for performance. I can't quite figure out how to pass a custom image to the CircleMarker. Any help on this is much appreciated.

A: There is no way to do this directly. APIs of leaflet.js or react-leaflet libraries do not respond to your request. You can do this by placing an extra marker child component in CircleMarker and removing its opacity if you don't want the circle to be seen.
You can set your marker icon with an external url or a local file such as png, svg etc. Then you will be able to do what you want. If you need an example please have a look at that:
import L from 'leaflet';

const duckIcon = new L.Icon({
  iconUrl: 'https://i.ya-webdesign.com/images/sample-png-image-download-3.png',
  iconRetinaUrl: 'https://i.ya-webdesign.com/images/sample-png-image-download-3.png',
  iconAnchor: new L.Point(0, 0),
  popupAnchor: new L.Point(16, 0),
  shadowUrl: null,
  shadowSize: null,
  shadowAnchor: null,
  iconSize: new L.Point(32, 32),
  className: 'leaflet-div-icon'
});

You can define this in a different file as well. But please do not forget to export it!
If you have a question like "What are these options?" You can also try to understand from
here. And finally you have a custom marker icon. Just pass a prop to your Marker component like below.
<CircleMarker
  center={{ lat: markerPosition[0], lng: markerPosition[1] }}
  opacity={0}>
  <Marker position={markerPosition} icon={duckIcon}>
    <Popup/>
  </Marker>
</CircleMarker>

I hope that will be useful. Please let me know if you have a problem and we will try to fix it.


text:
Q: How do I auto click a button using document.querySelectorAll jscript I have a web page that has a list of various items. I go into this location regularly to empty it out by inputting 0 in a quantity field and then clicking an "update quantity" button, this process is/has to be done item by item.
I can't figure out how to have the script execute item by item  i.e. input zero for item a, update the quantity, go to next item and repeat.
Inspecting the "update quantity" button displays this -
<input type ="text" name="quantity" value="1" size='3">
, so i'm unable to use a getElementsById.
Here is what my script looks like now -
function emptylocation()
  {
  var quantities = document.getElementsByName("quantity");
  for (var i = 0; i < quantities.length; i++)
    {
    quantities[i].value = 0;
    }
  document.querySelectorAll("button[type='submit']")[0].click();
}

A: <script>

function emptylocation(event)
{
  event.preventDefault()

  var quantities = document.getElementsByName("quantity");
  for (var i = 0; i < quantities.length; i++)
    {
    quantities[i].value = 0;
    }
}

</script>

<form>
  <input type ="text" name="quantity" value="1" size="3"/>
  <input type ="text" name="quantity" value="1" size="3"/>
  <input type ="text" name="quantity" value="1" size="3"/>
  <button type="submit" onclick="emptylocation(event)">update quantity</button>
</form>


text:
Q: Reading a list of numbers and sorting C++ I'm trying to read a list of numbers from a file and sort them by reading them into an array and then sorting the contents of the array. But I'm getting
error:incompatible types in assignment of 'std::basic_ostream<char, std::char_traits<char> >' to 'int [1]'

I'm fairly new to programming and this is my first time working with C++
Can anyone tell me how to write the list of numbers to an array so that I can sort them?
Here is what I have:
#include <fstream>
#include <iostream>
#include <iomanip>
#define ANYSIZE_ARRAY 1
using std::cout;
using std::endl;

int main()
{
  const char* filename = "test.txt";
  std::ifstream inputFile(filename);
  int numbers[ANYSIZE_ARRAY];
  int i, key;

  // Make sure the file exists
  if(!inputFile)
  {
    cout << endl << "The File is corrupt or does not exist. " << filename;
    return 1;
  }

  long n = 0;
  while(!inputFile.eof())
  {
    inputFile >> n;
    numbers = cout << std::setw(10) << n;
  }

  for(int j=1;j<5;j++)
    {
        i=j-1;
        key=numbers[j];
        while(i>=0 && numbers[i]>key)
        {
                    numbers[i+1]=numbers[i];
                    i--;
        }
        numbers[i+1]=key;
    }

    //Display sorted array
    cout<<endl<<"Sorted Array\t";
     for(i=0;i<5;i++)
       cout<<numbers[i]<<"\t";
    cout<<endl;
}

A: The line causing the error is:
numbers = cout << std::setw(10) << n;

I'm not quite sure what you're trying to do here, it looks like you just want to print it in which case the numbers = isn't needed.
The structure of your loop to read all the data is problematic also. The line: while (!inputFile.eof()) isn't idiomatic C++ and won't do what you hope. See here for a discussion on that issue (and here).
For reference you can do this quite simply with less work by using std::sort
#include <iterator>
#include <algorithm>
#include <vector>
#include <fstream>
#include <iostream>

int main() {
  std::ifstream in("test.txt");
  // Skip checking it

  std::vector<int> numbers;

  // Read all the ints from in:
  std::copy(std::istream_iterator<int>(in), std::istream_iterator<int>(),
            std::back_inserter(numbers));

  // Sort the vector:
  std::sort(numbers.begin(), numbers.end());

  // Print the vector with tab separators:
  std::copy(numbers.begin(), numbers.end(),
            std::ostream_iterator<int>(std::cout, "\t"));
  std::cout << std::endl;
}

This program also uses a std::vector instead of an array to abstract the "how big should my array be?" problem (which your example looked to have a possible problem problem with).

A: Here is what you need to do to get your program to work:

*

*Change ANYSIZE_ARRAY to 5

*Where you read the numbers, replace the while with this:
long n = 0;
i=0;
while(!inputFile.eof())
{
        inputFile >> n;
        cout << std::setw(10) << n;
        numbers[i]=n;
        i++;
}

This way, you will create an array which can hold 5 numbers, and you will read the numbers into that array. I used 5 because I saw that you were using the same number in the sorting algorithm, so I assumed that you only have to read 5 numbers. This is a bad thing, because your program will only work with 5 numbers.
If you need it to work with a variable amount of numbers, you can use a std::vector<long> to store the numbers. You can create a vector, and then use push_back() to add numbers to it. The vector will resize automatically and will hold as many numbers as you put in it. Then you can replace the 5s in your code with the vector's size() method.
You were getting your original error because this line doesn't make sense:
numbers = cout << std::setw(10) << n;

C++ views that line as if you are trying to print out the number to the stdout stream (which is in our case the console, the screen), and then assigning that stream to the "numbers" array. You cannot assign an output stream to an integer array (hence the error cannot convert from ostream to int[1]).

A: First, you should not assign an outstream variable to an int.
Second, n is long type and numbers is an integer array. There is type-unsafety.
Third, you should pre-allocate array size.
Forth, you can directly use sort() in STL function to do the sorting.
Try the following code:
#include <fstream>
#include <iostream>
#include <iomanip>
#include <algorithm>
using namespace std;

#define ANYSIZE_ARRAY 5

int main()
{
const char* filename = "test.txt";
std::ifstream inputFile(filename);
int numbers[ANYSIZE_ARRAY];
int i, key;

// Make sure the file exists
if(!inputFile)
{
    cout << endl << "The File is corrupt or does not exist. " << filename;
    return 1;
}

int n = 0;
i = 0;
while(!inputFile.eof())
{
    inputFile >> n;
    cout << std::setw(10) << n;
    numbers[i++] = n;
}

sort(numbers, numbers + ANYSIZE_ARRAY);

//Display sorted array
cout<<endl<<"Sorted Array\t";
for(i=0; i<ANYSIZE_ARRAY; i++)
    cout<<numbers[i]<<"\t";

cout<<endl;
}


text:
Q: TypeScript inference doesn't work properly Let's imagine we have the following definitions, I don't understand why TypeScript still doesn't infer the types correctly!
Anyone knows how to write it correctly?
Notes:
* Make sure you turn on "Strict Null Check" option.
* I commented the code to explain the issue, if it's not clear please comment.
type Diff<T, U> = T extends U ? never : T;
type NotNullable<T> = Diff<T, null | undefined>;
type OptionType<T> = T extends NotNullable<T> ? 'some' : 'none';
interface OptionValue<T> {
  option: OptionType<T>;
  value: T;
}

let someType: OptionType<string>; // evaludates to 'some' correctly
let noneType: OptionType<undefined>; // evaluates to 'none' correctly
let optionSomeValue = { option: 'some', value: 'okay' } as OptionValue<string>; // evaluates correctly
let optionNoneValue = { option: 'none', value: null } as OptionValue<null>; // evaluates correctly

let getValue = <T>(value: T): (T extends NotNullable<T> ? OptionValue<T> : OptionValue<never>) =>
  ({ option: value ? 'some' as 'some' : 'none' as 'none', value });

let handleSomeValue = <T>(obj: OptionValue<T>) => {
  switch (obj.option) {
    case 'some':
      return obj.value;
    default:
      return 'empty' as 'empty';
  }
}

let someStringValue = 'check'; // type string
let someNumberValue = 22;
let someUndefinedValue: string | null | undefined = undefined;

let result1 = handleSomeValue(getValue(someStringValue)); // it is 'string' correctly
let result2 = handleSomeValue(getValue(someNumberValue)); // should be 'number' but it's 'number | empty'
let result3 = handleSomeValue(getValue(someUndefinedValue)); // it is 'empty' correctly;

Playground link

A: There is a lot to unpack here, but the short version is that you need to use explicit type annotations to get this to work, inference has it's limits.
It is interesting to look at why this apparently works as you expect it to in some of the cases.
Firstly the inferred signature of handleSomeValue is <T>(obj: OptionValue<T>) => T | "empty". Notice there is no relation between T and whether 'empty' is included in the return type or not, the result is always T | "empty". So why is 'empty' sometimes missing and T sometimes missing. Well that has to do with the rules of how unions are evaluated.
Lets consider the first example
let someStringValue = 'check'; // type string
let result1 = handleSomeValue(getValue(someStringValue));

here the T to handleSomeValue will be string, so the result will be string | 'empty' but "empty" is a subtype of string so string will eat up the literal type "empty" (because it's redundant) and the result will be string
Now let's look at the third example which also appears to work:
let someUndefinedValue: string | null | undefined = undefined;
let result3 = handleSomeValue(getValue(someUndefinedValue)); // it is 'empty' correctly;

While here someUndefinedValue appears to be typed as string | null | undefined it is in fact not, if you hover over someUndefinedValue in the second line you will see it is typed as undefined. This is because flow analysis determines that the actual type will be undefined because there is no path for the variable to be undefined.
This means that getValue(someUndefinedValue) will return OptionValue<never>, so the T in handleSomeValue will be never so we get never | 'empty'. And since never is a subtype of all types (see PR) never | 'empty' will just evaluate to 'empty'.
It's interesting to note that when someUndefinedValue is actually string | undefined the example fails to compile because getValue will return 'OptionValue<string> | OptionValue<never>' and the compiler will not be able to infer T correctly.
let someUndefinedValue: string | null | undefined = Math.random() > 0.5 ? "" : undefined;
let result3 = handleSomeValue<string | never>(getValue(someUndefinedValue)); // Argument of type 'OptionValue<string> | OptionValue<never>' is not assignable to parameter of type 'OptionValue<string>'

With this understanding it becomes obvious why the second example does not work as expected.
let someNumberValue = 22;
let result2 = handleSomeValue(getValue(someNumberValue)); // should be 'number' but it's 'number | empty'

getValue returns OptionValue<number> so the T in handleSomeValue will be number and the result will thus be number | 'empty'. Since the two types in the union have no relation, the compiler will not try to simplify the union any further and will leave the result type as is.
The solution
A solution that works as you expect and the preserves the 'empty' literal type is not possible because the union of string | 'empty' will always be string. We can prevent the simplification if we use branded types to add something to empty to prevent the simplification. Also we will need an explicit type annotation for the return type that will correctly identify the return type:
type Diff<T, U> = T extends U ? never : T;
type NotNullable<T> = Diff<T, null | undefined>;
type OptionType<T> = T extends NotNullable<T> ? 'some' : 'none';
interface OptionValue<T> {
    option: OptionType<T>;
    value: T;
}

let someType: OptionType<string>; // evaludates to 'some' correctly
let noneType: OptionType<undefined>; // evaluates to 'none' correctly
let optionSomeValue = { option: 'some', value: 'okay' } as OptionValue<string>; // evaluates correctly
let optionNoneValue = { option: 'none', value: null } as OptionValue<null>; // evaluates correctly

let getValue = <T>(value: T): (T extends NotNullable<T> ? OptionValue<T> : OptionValue<never>) =>
({ option: value ? 'some' as 'some' : 'none' as 'none', value }) as any;

type GetOptionValue<T extends OptionValue<any> | OptionValue<never>> =
    T extends OptionValue<never> ? ('empty' & { isEmpty: true }) :
    T extends OptionValue<infer U> ? U: never ;

let handleSomeValue = <T extends OptionValue<any> | OptionValue<never>>(obj: T) : GetOptionValue<T>=> {
switch (obj.option) {
    case 'some':
    return obj.value;
    default:
    return 'empty' as  GetOptionValue<T>;
}
}
let someStringValue = 'check'; // type string
let result1 = handleSomeValue(getValue(someStringValue)); // it is 'string' correctly
let someNumberValue = 22;
let result2 = handleSomeValue(getValue(someNumberValue)); //is number

let someStringOrUndefinedValue: string | null | undefined = Math.random() > 0.5 ? "" : undefined;
let result3 = handleSomeValue(getValue(someStringOrUndefinedValue)); // is string | ("empty" & {isEmpty: true;})

let someUndefinedValue: undefined = undefined;
let result4 = handleSomeValue(getValue(someUndefinedValue)); // is "empty" & { isEmpty: true; }

A: The inferred return type of handleSomeValue is computed as the union of the types of all of the returned expressions, i.e., T | "empty".  At each call site, this return type is instantiated with the type argument for T.  TypeScript does not re-analyze the body of handleSomeValue for each call to see which cases of the switch are reachable depending on T.  If you wanted, you could annotate handleSomeValue like this:
type SomeValueReturn<T> = T extends NotNullable<T> ? T : "empty";
let handleSomeValue = <T>(obj: OptionValue<T>): SomeValueReturn<T> => {
  switch (obj.option) {
    case 'some':
      return obj.value as SomeValueReturn<T>;
    default:
      return 'empty' as SomeValueReturn<T>;
  }
}

But I don't really understand what you are trying to achieve.

A: Because T is not NotNullable nor Diff<T, U>.  If you input type T, it will alway return the same.  You must instruct the compiler how to do
You must define new type that wrap OptionValue<T>:
type OptionValue2<T> = OptionValue<NotNullable<T>>;

let getValue = <T>(value: T): OptionValue2<T> => ({
  option: value ? "some" : "none",
  value
});

let someValue: undefined;
let value = getValue(someValue); // this type will be OptionValue<never>

// still use OptionValue
let handleSomeValue = <T>(obj: OptionValue<T>): SomeValueReturn<T>  => {
  switch (obj.option) {
    case "some":
      return obj.value as T;
    default:
      return "empty" as "empty";
  }
};

let someUndefinedValue: string | null | undefined = undefined;

For last case, Typescript compiler evaluate type only. It can not know if the result is string or null. You can not expect dynamic value evaluation


text:
Q: How do I change the Dropbox directory on a headless GNU/Linux server? I have installed Dropbox 2.0.0 via command line on my home server (Ubuntu Server 12.04) to use for off-site automated backups, but I can't change the directory that the Dropbox daemon keeps synced.
I've tried the following:
The official docs say to use the desktop application, which is not applicable in my situation. However I installed the desktop app on my desktop machine and changed the default folder location, but I can't find where this change is stored in the ~/.dropbox/ directory so I can make the same change on the server.
This page (and several others) recommends a Python script to do the job. Looking at the script, it opens a SQLite database called ~/.dropbox/dropbox.db, which does not exist on my Dropbox install, leading me to believe the script is out-of-date.
This forum thread suggests manually inserting the required row in the config.db database, which I did, but it made no difference. I checked the same database file on my desktop machine, and it does not have the dropbox_path key, so I'm presuming the information in that thread is also out of date for version 2.0.
I have tried to launch the Dropbox GUI configuration wizard over SSH with X11 forwarding, as suggested in one of the answers, but the binary must detect the absence of a local X11 install and it starts a command line daemon instead, which provides no means to change the option I need.
I am currently using a symlink, as suggested as an answer, but this is a kludge. I would like to know the correct way to make the change.
How do I change the Dropbox directory on a headless GNU/Linux server?
Update: I've ditched Dropbox and started using Copy. Their Linux tools and support is far superior to Dropbox. I leave this question here in case someone, someday, can answer it.

A: You could just create a symlink to ~/Dropbox
ln -s <dir-that-you-want-to-sync> ~/Dropbox

A: This is a real shortcoming of the Linux application. In the older versions you could modify the settings file. In the most recent version it appears the only solution is to change the $HOME variable before Dropbox starts.
Lets say we want the 'Dropbox' folder to appear in /foo/bar.

*

*Install Dropbox to /foo/bar/.dropbox-dist.

*Download the Python script to control Dropbox from the Linux Dropbox page.

*In this script, below import os add a line: os.environ["HOME"] = "/foo/bar"

*Dropbox controlled / started through the control script now thinks /foo/bar/ is your /home/username/.

This means that when using the control script it now looks for /foo/bar/.dropbox-dist/dropbox to execute the daemon. Configuration files will be written to /foo/bar/.dropbox/. The /foo/bar/Dropbox/ folder will be used for file synchronization.

A: So here's my trick:
First I remove all related folder created in my home folder
rm -rf ~/.dropbox-dist

I also remove Dropbox default folder:
rm -rf ~/Dropbox

So then I reinstalled dropbox daemon by define HOME env var like this:
HOME=/data/other_folder dropbox.py start -i

Next, start dropboxd daemon manually by run:
HOME=/data/other_folder /data/other_folder/.dropbox-dist/dropboxd

Then wait it till finish.

A: I had the same issue. I wanted to use dropbox to sync a large secondary hard disk on a ubuntu server. What I did was I created a symlink from the secondary hard disk to my home directory before installing dropbox
ln -s /mnt/disks/sdb /home/marc/Dropbox

Only install Dropbox after completing the above step.
This way, the Dropbox in the Home directory is the symlink and the real folder is where ever you symlinked from.

A: My solution is to make a permanent alias named dropb with the HOME-path to your new directory.
echo 'alias dropb="HOME=/media/your/path dropbox"' >> ~/.bash_aliases
source ~/.bash_aliases

Then you can use it like normal dropbox
dropb start -i
dropb status
dropb exclude add ./my_wife/shoe_collection

A: If you have ssh access to the machine in question, you might be able to launch the dropbox desktop application on the headless server and have it displayed on your local machine:

*

*Connect to the server using X11 port forwarding
ssh -Y user@server

*Now launch the dropbox app, it should appear on your local screen
~/.dropbox-dist/dropbox

It may take a while depending on your network connection. Don't give up if you don't get an error message. I can confirm that this worked when I connected from my Debian box to a remote, Ubuntu server that was running no X server. After a few seconds, a second Dropbox icon appeared on my local taskbar and I could access/modify the options of the remote Dropbox install from there.
Now, some details may change since I am using Dropbox 1.6.18 but the basics should be the same. In case the name or location of the app have changed, this is how I found out what command I need to execute to launch the Dropbox desktop app:

*

*Get the list of currently running processes
top -cbd .10 -n 1 | sort > no_drop.txt

*Launch the Dropbox app (right click on the Dropbox icon in your taskbar and chose "Preferences...") and repeat
top -cbd .10 -n 1 | sort > drop.txt

*Compare the files to find the relevant command
diff drop.txt no_drop.txt

A: This might be what you're looking for:
Set up Dropbox on a GUI-less Linux server
I apologize for simply tossing an URL instead of describing the procedures here. I'm at work and can't elaborate more right now. Later I can expand on the answer, I just don't want to lose this valuable URL with your solution.

A: I just hit the same problem and was able to resolve it by

*

*Unlinking the account through the Dropbox web UI:
https://blogs.dropbox.com/dropbox/2014/10/how-to-unlink-a-device-from-your-dropbox/

*Removing the ~/.dropbox directory for the user running dropboxd.
rm -r ~/.dropbox

*You might need to clean up the ~/Dropbox directory also.
The first step may be not necessary, but I'd already done that before removing ~/.dropbox, which ultimately allowed me to set it up again.
Remember to cd to the directory you want to be your Dropbox root folder.
It then worked fine for me.

A: TechRepublic has a page — Set up Dropbox on a GUI-less Linux server —
that claims to solve this problem:

… There are GUI tools provided to manage the Dropbox
  and set it up for [Linux, Windows, and OS X].
  But what happens if you want to link a Linux computer
  that doesn't have a GUI?
  It is possible, with a bit of work, to make Dropbox run without a GUI,
  allowing you to synchronize files with servers that are running headless
  or where a user account may not be logged in all the time.
    ︙
To begin:
# mkdir -p /tmp/dropbox
# cd /tmp/dropbox
# curl -OL http://dl.getdropbox.com/u/6995/dbmakefakelib.py
# curl -OL http://dl.dropbox.com/u/637552/Dropbox/dbreadconfig.py
# curl -L -o dropbox.tar.gz http://www.dropbox.com/download?plat=lnx.x86_64

Use plat=lnx.x86 if you want the 32-bit client.
  This creates a temporary directory for our Dropbox install files,
  and downloads two necessary python scripts: dbmakefakelib.py
  which creates fake stub copies of GUI libraries so the dropboxd daemon starts,
  and dbreadconfig.py which displays dropbox configuration information.
Decide which user will be running the Dropbox client;
  this could be a dedicated user or it could be a regular user.
  You can also have more than one Dropbox instance running on the system,
  so you may opt to set it up for multiple users
  (although each user can only run one Dropbox instance).
  For this example, we will have created a special user "dropbox"
  which will run this Dropbox client.
# su - dropbox
$ cd ~/
$ tar xvzf /tmp/dropbox/dropbox.tar.gz
$ cd .dropbox-dist
$ python /tmp/dropbox/dbmakefakelib.py
dropboxd ran for 15 seconds without quitting - success?

The dbmakefakelib.py script requires gcc,
  so you must have gcc installed on the system.
  This creates fake stub copies of the GUI libraries
  so that dropboxd will start.
  At the end, you can see that it launched dropboxd;
  press Ctrl+C to exit the script.
  dropboxd should still be running in the background:
$ ps ax | grep dropboxd
24001 pts/0    S      0:00 sh -c { /home/dropbox/.dropbox-dist/dropboxd; } 2>&1

Now that dropbox is running, we need to link it to an existing account:
$ cd ~/
$ python /tmp/dropbox/dbreadconfig.py
host_id = 0bd9c5a15458fbc31f85e892faa7dac4
schema_version = 6

Grab the host_id from above.
  Login to the Dropbox web interface, and once you have logged in,
  manually visit this URL:
https://www.dropbox.com/cli_link?host_id=[HOST_ID]
Replace [HOST_ID] with the host_id that dbreadconfig.py outputs.
  When you have done that, the Dropbox site will tell you
  that you have successfully linked a new computer.
  Go to your Account settings and then My Computers
  and you will see the new computer listed.
If you have not killed the dropboxd process that dbmakefakelib.py started,
  you will find that it is already downloading the files from the Dropbox
  to ~/Dropbox/ in the background.
To start the dropboxd daemon in the background at boot,
  you can add the following to your /etc/rc.d/rc.local init script:
daemon —user dropbox /bin/sh -c "/home/dropbox/.dropbox-dist/dropboxd&"

This will start dropboxd in the background
  with the privileges of the user for which it is installed
  (in this case, the user is "dropbox").
  If you want to do a system-wide initscript,
  visit the Dropbox wiki where there are some examples you can use,
  including initscripts for Fedora / Red Hat and for Debian / Ubuntu.
  It also has examples
  for how to set up Dropbox running under DJB's daemontools.


text:
Q: DB2: How to set encoding for db2clp under Windows? I have a DB2 that was created with encoding set to UTF-8
db2 create database mydb using codeset UTF-8

My data insert scripts are also stored in encoding UTF-8.
The problem now is that the command line processor seems to work with a different encoding as the Windows installation doesn't use UTF-8:
C:\Users\Administrator>chcp
Active code page: 850

This leads to the problem that my data (which contains special characters) is not stored correctly to the database.
Under Linux/AIX I could change the command line encoding by setting
export LC_ALL=en_US.UTF-8

How do I achieve this under Windows? I already tried
chcp 65001

UPDATE:
But that won't have any effect? It seems like the db2clp can't deal with the UTF-8 encoded file because it will print out junk:
D:\Program Files\ibm_db2\SQLLIB\BIN>chcp 65001
Active code page: 65001

D:\Program Files\ibm_db2\SQLLIB\BIN>type d:\tmp\encoding.sql
INSERT INTO MY_TABLE (ID, TXT) VALUES (99, 'äöü');

D:\Program Files\ibm_db2\SQLLIB\BIN>db2 connect to mydb

Datenbankverbindungsinformationen

Datenbank-Server                                                = DB2/NT64 9.5.0
SQL-Berechtigungs-ID                                            = MYUSER
Aliasname der lokalen Datenbank                                 = MYDB

D:\Program Files\ibm_db2\SQLLIB\BIN>db2 -tvf d:\tmp\encoding.sql
INSERT INTO MY_TABLE (ID, TXT) VALUES (99, 'äöü')
DB20000I  Der Befehl SQL wurde erfolgreich ausgeführt.

A: You need to set both:
CHCP 65001
SET DB2CODEPAGE=1208

on the db2cmd command line, before running db2 -tvf. This works for databases that have CODESET set to UTF-8. To check the CODESET setup for database run:
db2 get db cfg for <your database>

and look for "Database code page" and "Database code set" they should be 1208 and UTF-8 respectively.

A: when dealing with encodings, you have to take a careful look into your envirnoments, and where you are currently. So in your case:

*

*the Server stores its data in encoding A (like UTF-8)

*the client resides in an environment which has encoding B (like windows-1252)

in your client, you have to have to use the encoding of your client (or tell the client you intentionally use another encoding on client side (like UTF-8-encoded file inside a windows-1251 environment)!). The connection between the Client and the server is doing the work for you to change encoding B into encoding A for storing the data into the database.

A: It's work for me by setting db2codepage, thanks to Mr. Zoran Regvart.
by the way, after setting, you need to execute "db2 terminate" to reset client, and then reconnect.


text:
Q: How to call a function if Invokable funtion does not exist? _helperClass?.DoSomething(param1, param2, param3);

if(_helperClass == null) // .... or any type of check
{
DoOthers();
}

I want to call a function or fire an event if _helperClass is null or not defined. I leave an example to explain what I want to do.
_helperClass?.DoSomething(param1, param2, param3) : DoOthers();

Is it possible to do this, or what is the best practice?
?: ->   These operators can't be overloaded in C#.

A: Are you performing a standalone statement or evaluating an expression?  That makes a difference in how you might structure it.  Keeping in mind that the null conditional operator is not a drop-in replacement for an if/else structure.

If you're just performing a statement then semantically you already have exactly what you want.  Define the semantics as:

If _helperClass is null, do one thing.  Else, do another.

Which makes the code clear and simple:
if(_helperClass == null)
{
    DoOthers();
}
else
{
    _helperClass.DoSomething(param1, param2, param3);
}

Or, if you prefer the opposite semantics, you can invert the condition:
if(_helperClass != null)
{
    _helperClass.DoSomething(param1, param2, param3);
}
else
{
    DoOthers();
}

Alternatively, if what you have is an expression (that is, if the result of one or the other of these method calls should be used in-line by surrounding code), then you can make use of the ternary conditional operator.  For example:
_helperClass == null ? DoOthers() : _helperClass.DoSomething(param1, param2, param3)

Or, inverting the semantics of the condition:
_helperClass != null ? _helperClass.DoSomething(param1, param2, param3) : DoOthers()

It looks like you were trying to do exactly that in your second code sample, but you weren't making use of the ? part of the conditional operator or using any kind of condition.  It appears you were confusing it with the null-conditional operator used for member access.


text:
Q: Not getting tree with expected link style in ReactJS using D3 I'm pretty new to D3.js library. I've been trying to implement it in React JS project.
I'm just using d3 functions for calculations and rendering part will be done by React JS.
I successfully created a tree but I'm getting links with weird style (Not as expected)
This is what I expected (As per D3 Documentation)

But I got the below tree :(

Also I can't able to collapse or expand...
You can find the code below.
componentDidMount() {
        const width = 800, height = 800;

        const tree = d3.tree().size([height, width - 160]);
        const stratify = d3.stratify().id((d) => {
            return d.name;
        }).parentId((d) => {
            return d.parent;
        });
        const root = stratify(this.state.data)
            .sort((a, b) => {
                return (a.height - b.height) || a.id.localeCompare(b.id);
            });

        this.setState({ paths: tree(root).links() });
        this.setState({ nodes: root.descendants() })
    }

    render() {
        let paths = this.state.paths && this.state.paths.map(item => {
            let d = d3
                .linkHorizontal()
                .x((d) => {
                    return d.y;
                })
                .y((d) => {
                    return d.x;
                });
            return <path className='link' d={d(item)} />
        })
        let nodes = this.state.nodes && this.state.nodes.map((node, i) => {
            return <g key={node.id} className={"node" + node.children ? " node--internal" : " node--leaf"}
                transform={`translate(${node.y}, ${node.x})`}>
                <circle r="10" style={{ 'fill': node.children ? 'lightsteelblue' : 'black' }} />
                <text y="0" dy="0" textAnchor="middle"
                    style={{ 'fillOpacity': 1 }}>{node.name}</text>
            </g>
        })
        return (
            <svg className="tree-chart-basic" ref={(r) => this.chartRf = r} style={{ width: '800px', height: '800px' }}>
                <g transform='translate(20,20)'>
                    {nodes}
                    {paths}
                </g>
            </svg>
        );
    }

this.state.data will be having the array as follows
    [
        { "name": "ProjectA", "parent": "" },
        { "name": "ApplicationA", "parent": "ProjectA" },
        { "name": "EnvironmentB", "parent": "ProjectA" },

        { "name": "TierC", "parent": "ApplicationA" },
        { "name": "TierD", "parent": "ApplicationA" },
        { "name": "TierE", "parent": "ApplicationA" },

        { "name": "ServiceF", "parent": "EnvironmentB" },

        { "name": "ContainerG", "parent": "EnvironmentB" },
        { "name": "ContainerH", "parent": "TierE" },
        { "name": "ContainerH", "parent": "TierE" },
        { "name": "ContainerH", "parent": "TierE" },
        { "name": "ContainerH", "parent": "TierE" },
        { "name": "ContainerH", "parent": "TierE" },
        { "name": "ContainerH", "parent": "TierE" }
    ]

*

*How can I get the expected Tree in my code?

*How can I get collapse/expand functionality?

Please tell me what I'm doing wrong. Thanks for the time. (:

A: I finally got the solution to my answer.
I need to specify the style to <path> tag as follows.
<path
fill="none"
stroke="#97a6ff"
strokeWidth="2px"
/>

A: I had the same issue when using react-tree-graph which uses d3 under the hood. Luckily you can add custom classes to customize everything. I use css-modules so I had to escape the global classnames.
import { Tree } from 'react-tree-graph';
import style from './tree.module.scss';
// ...
<Tree svgProps={{ className: style.acmeProductTree }} />

// tree.module.scss
svg.acmeProductTree path:global(.link) {
  fill: none;
  stroke: #2593b8;
  stroke-width: 1.5px;
}

As I found out just now you can alternatively apply a custom class directly to the path element:
<Tree pathProps={{ className: style.acmeProductTreeLink }} />

.acmeProductTreeLink {
  fill: none;
  stroke: #2593b8;
  stroke-width: 1.5px;
}


text:
Q: Check custom listview items on Activity start I have a custom Listview in my C# Android, each row contains one textview and one checkbox. I am saving the value (or the text) of the selected row's textview in a public list named usercoin. Each time the user opens the app, the list usercoin will contain the text of the his textview selected items, and I am doing that using SQLite. The problem is I want to re-check the items which the user have previously selected automatically when the activity starts which are stored in the usercoin list as I have previously noted. But I am not able to achieve this.
MainActivity.cs
 ListView mListView;
MyAdapter adapter;
protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);

    // Set our view from the "main" layout resource
    SetContentView(Resource.Layout.activity_main);
    mListView = FindViewById<ListView>(Resource.Id.listview);
    List<TableList> list = new List<TableList>();

    list.Add(new TableList("Germany",false));
    list.Add(new TableList("France", false));
    list.Add(new TableList("Finland", false));
    list.Add(new TableList("Germany", false));
    list.Add(new TableList("France", false));
    list.Add(new TableList("Germany", false));
    list.Add(new TableList("France", false));
    list.Add(new TableList("Finland", false));

    adapter = new MyAdapter(this, list);
    mListView.Adapter = adapter;
    mListView.ItemClick += MListView_ItemClick;
}

private void MListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
    var t = list[e.Position];
    string selected = t.name;
    var ll = e.View as LinearLayout;
    var cb = ll.GetChildAt(2) as CheckBox;
    if (cb.Checked)
    {
        cb.Checked = false;
        adapter.changeState((int)cb.Tag, false);
    }
    else
    {
        cb.Checked = true;
        adapter.changeState((int)cb.Tag, true);
    }
}

class MyAdapter : BaseAdapter
{
    Context mContext;
    List<TableList> mitems;
    public MyAdapter(Context context, List<TableList> list)
    {
        this.mContext = context;
        this.mitems = list;

    }
    public override int Count
    {
        get
        {
            return mitems.Count;
        }
    }

    public override Java.Lang.Object GetItem(int position)
    {
        return mitems[position];
    }

    public override long GetItemId(int position)
    {
        return position;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        DataViewHolder holder = null;
        if (convertView == null)
        {
            convertView = LayoutInflater.From(mContext).Inflate(Resource.Layout.CoinList, null, false);
            holder = new DataViewHolder();
            holder.tv = convertView.FindViewById<TextView>(Resource.Id.CoinName);
            holder.iv = convertView.FindViewById<ImageView>(Resource.Id.imageView1);
            holder.cb = convertView.FindViewById<CheckBox>(Resource.Id.checkBox1);
            convertView.Tag = holder;
        }
        else
        {
            holder = convertView.Tag as DataViewHolder;

        }
        holder.cb.Tag = position;

        holder.tv.Text = mitems[position].Name;
        holder.cb.Focusable = false;
        holder.cb.Checked = mitems[position].bl;
        holder.iv.SetImageResource(Resource.Drawable.dapao);
        holder.cb.CheckedChange += Cb_CheckedChange;
        return convertView;

    }

    private void Cb_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e)
    {
        var cb = sender as CheckBox;
        if (e.IsChecked && !mitems[(int)cb.Tag].bl)
        {
            mitems[(int)cb.Tag].bl = true;
            this.NotifyDataSetChanged();
        }
        else if (!e.IsChecked && mitems[(int)cb.Tag].bl)
        {
            mitems[(int)cb.Tag].bl = false;
            this.NotifyDataSetChanged();
        }
    }

    internal void changeState(int tag, bool v)
    {
        mitems[tag].bl = v;
        this.NotifyDataSetChanged();
    }
}

public class DataViewHolder : Java.Lang.Object
{
    public ImageView iv { get; set; }
    public TextView tv { get; set; }
    public CheckBox cb { get; set; }

}
public class TableList : Java.Lang.Object
{
    private string v;

    public TableList(string name, bool b)
    {
        this.Name = name;
        this.bl = b;
    }
    public string Name { get; set; }
    public bool bl { get; set; }
}
}
}

For example, when the user first run the app and select France and Germany from the listview, next time he re-opens the app, the usercoin list will contain France and Germany. Now the question is how can I check the checkboxes corresponding to those values in the listview. I have tried to do so by including this code in MyAdapter : BaseAdapter class:
if (Class1.usercoin.Contains(item.CoinAbr))
        {
            Class1.adapter[(int)holder.cb.Tag].bl = true;
            this.NotifyDataSetChanged();
        }

But when this code get executed, the previously checked items are checked plus some other items which the user haven't checked previously are also checked. So how can I check the previously checked items in the Listview on the app start ? Please help me to find a solution.


text:
Q: How can I store nodeId, direction,and speed of a vehicle in RSU in veins version 5? Thank you for reading the question. I have a simple query that when vehicles are broadcasting a message then the event happened and re-routing of vehicles are being done. But if I want to store the information of a vehicle such as nodeId, Speed, Direction, distance in RSU and other neighboring  vehicles What is the correct way to do that?
I understand all the files of tic toc and veins itself. i found Passedmsg is there cArray, cparlist and so many things. but I really want to achieve this thing in a correct way.
Please Help me. i know it may be silly question but I have no clue where to make cchanges for storage of the message content.

A: As you saw in the answer to the question you quoted, getAngleRad() returns the vehicle's heading in Radians, not degrees.
Note that, as of Veins 5.0, the same functionality is achieved by calling getHeading() and then calling getRad() on the result.
If you want to know whether the two angles are from vectors pointing into the same or opposite directions, you could check whether their difference is bigger than 0.5 Pi radians (90 degrees).
See an answer on for how to calculate the smallest difference between angles for possible ways to achieve that.


text:
Q: How to automatically change wallpaper after every 30 seconds using JobScheduler? I am creating application where there is an option of checkbox allowing user to change wallpaper automatically after 30 seconds. I am using JobScheduler and have passed arraylist of images by serializing them to JsonArray and then to String and passed it using PersistanceBundle:
JsonArray result = (JsonArray) new Gson().toJsonTree(wallpaperModelArrayList,
                        new TypeToken<List<WallpaperModel>>() {
                        }.getType());
PersistableBundle persistableBundle=new PersistableBundle();
persistableBundle.putString("wallpaper",result.toString());
mJobScheduler = (JobScheduler)
                        getSystemService(Context.JOB_SCHEDULER_SERVICE);
                JobInfo.Builder builder = new JobInfo.Builder(1,
                        new ComponentName(getPackageName(),
                                JobSchedulerService.class.getName()));
                builder.setExtras(persistableBundle);
                builder.setPeriodic(30000);

And my JobService class:
public class JobSchedulerService extends JobService {

private static final String TAG = "JobSchedulerService";
private String images;

@Override
public boolean onStartJob(JobParameters params) {
    Log.i(TAG, "onStartJob:");
    images = params.getExtras().getString("wallpaper");
    changeWallpaper(params);
    return true;
}

@Override
public boolean onStopJob(JobParameters params) {
    //Log.i(TAG, "onStopJob:");
    return true;
}

private void changeWallpaper(JobParameters params) {

    Gson gson = new Gson();
    Type listType = new TypeToken<List<WallpaperModel>>(){}.getType();
    List<WallpaperModel> list = gson.fromJson(images, listType);

    Glide.with(this)
            .load(list.get(0).getUrlImage())
            .asBitmap()
            .into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super
                        Bitmap> glideAnimation) {
                    try {
                        WallpaperManager.getInstance(getApplicationContext()).setBitmap(resource);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
    jobFinished(params, false);
}

}

I don't know how to set wallpaper(images one by one) after every 30 secs out of the list I have in JobService?Can Anyone tell me how setperiodic function works(what happens after 30secs)? This approach can be wrong. Can anyone guide me on how to do this? Thanks in advance.


text:
Q: AS3 RegEx: Match Keywords I am trying to match ANY of the few keywords in a string using RegEx in AS3. Following is an example.
var sourceString = "No, I am working on it. There might be some delay.";
var keywords = ["no", "delay"];

I need to check if any of the keywords are present in the source string. The keywords and source strings will be dynamic. I need to take the source string as an input from the user and then search some keywords in that string. Can there be one generic RegEx pattern to achieve this?

A: You can construct a new RegExp object and use that to match against the source string.
For example:
var sourceString = "No, I am working on it. There might be some delay.";
var keywords = ["no", "delay"];

var expression:RegExp = new RegExp(keywords.join("|"), "ig");

if (expression.test(sourceString)) {
    // Match found
} else {
    // No match found
}

(Untested code.)


text:
Q: Unresolved external issue when compiling multi-source files I have a project that consists of 2 CPP files (main.cpp and Car.cpp) and a header file (Car.h). The program is meant to allow a user to enter the model, make, and speed of a car and displays the modified speed. My issue is that when I compile the project, I receive a "1 unresolved externals" issue like so:
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Car::Car(void)" (??0Car@@QAE@XZ) referenced in function _main
1>C:\Users\Shaidi\Desktop\Classes\CIST 2362\Projects\main\Debug\main.exe : fatal error LNK1120: 1 unresolved externals

Here is the main.cpp file:
// main.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "Car.h"
#include <iostream>
#include <string>

using namespace std;
int main()
{
    string make;
    int model, speed;

    Car c;

    //user input and assignment for make, model, and speed
    cout << "Enter the make of the car: " <<endl;
    cin >> make;
    c.setMake(make);

    cout << "Enter the model of the car: " <<endl;
    cin >> model;
    c.setYearModel(model);

    cout << "Enter the speed of the car: " <<endl;
    cin >> speed;
    c.setSpeed(speed);

    //print make and model
    cout << "Car make: " << c.getMake() <<endl;
    cout << "Car model: " << c.getYearModel() << endl;
    cout << "Car speed: " << c.getSpeed() <<endl;

    //loops to calculate and print acceleration and braking
    for (int i = 0; i < 5; i ++){
        cout << "Car speed after acceleration: " <<c.accelerate() <<endl;
    }

    for (int i = 0; i < 5; i ++){
        cout << "Car speed after braking: " <<c.brake() <<endl;
    }
    return 0;
} //end main

Here is the Car.cpp file:
// Car.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "Car.h"
#include <cstdlib>
#include <string>
#include <iostream>

using namespace std;

Car::Car(int y, string m)
{
    string make = m;
    int year = y;
    speed = 0;
}

void Car::setYearModel(int y)
{
    yearModel = y;
}

void Car::setSpeed(int s)
{
    if (s >= 0){
        speed = s;
    } else {
        cout << "Invalid speed";
        exit(EXIT_FAILURE);
    }
}

void Car::setMake(string m)
{
    make = m;
}

int Car::getYearModel()
{
    return yearModel;
}

int Car::getSpeed()
{
    return speed;
}

string Car::getMake()
{
    return make;
}

int Car::accelerate()
{
    return speed + 5;
}

int Car::brake()
{
    return speed - 5;
}

And here is the Car.h file:
#ifndef CAR_H
#define CAR_H
#include <string>

using namespace std;

class Car
{
private:
    std::string make;
    int yearModel;
    int speed;
public:
    Car();
    Car(int, std::string);
    void setYearModel(int);
    void setSpeed(int);
    void setMake(std::string);
    int getYearModel() ;
    int getSpeed() ;
    int accelerate() ;
    int brake() ;
    std::string getMake() ;
};
#endif // CAR_H

A: You've declared Car::Car() but never defined it. Either add a definition to the .cpp file, or remove the declaration from the header.
For example:
Car::Car()
{
}

A: You miss the implementation of default constructor of Car().
class Car
{
public:
   // There is no implementation.
   Car();
}

A: It looks like you have defined the default constructor for car but have not implemented it. Then you declared a variable of type car which would require it to be implemented. Adding the code that Kerrek has above to the .cpp file should do the trick :)


text:
Q: Wrap all class methods using a meta class I'm trying to wrap all of the methods inside a class I wrote with a specific wrapper method.
My class inherits from the python dict class, and I want to wrap all of the methods of this parent class, such as __setitem__, __getitem__, etc.
In my attempts to achieve that I have written a meta class that wraps all the methods inside it's child class, using the __init__ method in the meta class, so I can access the child class's object (and not it's class definition which does not include the parent methods).
However, after running the code, I see the wrapper method is never called. Meaning the wrapping didn't succeed.
Can you help with figuring out what went wrong?
My code:
def wrapper(func):
    def wrapped(self, *args, **kwargs):
        print 'wrapper.__call__()'
        res = func(self, *args, **kwargs)
        return res
    return wrapped

class MyMeta(type):
    def __init__(cls, classname, bases, class_dict):
        print 'meta.__init__()'
        new_class_dict = {}
        for attr_name in dir(cls):
            attr = getattr(cls, attr_name)
            if hasattr(attr, '__call__'):
                attr = wrapper(attr)
            new_class_dict[attr_name] = attr
        return super(MyMeta, cls).__init__(classname, bases, new_class_dict)

class MyDict(dict):

    __metaclass__ = MyMeta

    def __init__(self, *args):
        print 'child.__init__()'
        super(MyDict, self).__init__(*args)

d = MyDict({'key': 'value'})
d['new_key'] = 'new_value'

The printout I get is:
meta.__init__()
child.__init__()

without any reference to the wrapper.__call__() print I placed inside the wrapped method...

A: When the metaclass __init__ gets called, the class object has already been built so modifying the attributes dict (class_dict in your code) at this stage is totally useless indeed. You want to use setattr instead:
class MyMeta(type):
    def __init__(cls, classname, bases, class_dict):
        for attr_name in dir(cls):
            if attr_name == "__class__":
                # the metaclass is a callable attribute too,
                # but we want to leave this one alone
                continue
            attr = getattr(cls, attr_name)
            if hasattr(attr, '__call__'):
                attr = wrapper(attr)
                setattr(cls, attr_name, attr)

        # not need for the `return` here
        super(MyMeta, cls).__init__(classname, bases, class_dict)


text:
Q: Mongoose - Finding Documents based on the IDs in an Array I have an array of mongoIDs like this
arrayOfIDs = ['mongoID1','mongoID2','mongoID3']

These are mongo-ids of documents in my collection.
Now by taking the an array of those mongoIDs ie ['mongoID1','mongoID2','mongoID3'], I need to query on each of the document specified by those ids, by using its _id and deal with its data independently in my code logic. As an example for simplicity, I have just 'printed' the output ie res.json(doc.name).
I need something like this below If at all it does exist in Mongoose/MongoDB
Shop.find({'_id':['mongoID1','mongoID2','mongoID3']})
    .exec()
    .then(doc =>{
       res.json(doc.name)
    })

I know I can use a loop for this case, like this,
for(id of arrayOfIDs){
    Shop.find({'_id': id})
        .exec()
        .then(doc =>{
           res.json(doc.name)
        })
}

But this involves querying the database multiple times based on the lenght of arrayOfIDs, something I don't want. I would like to have a native mongodb solution that just pass the Ids in mongodb query like in my example above.
Can you please show me how this can be achieved?

A: You can use the $in operator.
{ _id: { $in: ["mongoID1", "mongoID2", "mongoID3"] } }

If the type of _id is ObjectId then you need to convert them to ObjectId before passing it
{
  _id: {
    $in: [
      mongoose.Types.ObjectId("mongoID1"),
      mongoose.Types.ObjectId("mongoID2"),
      mongoose.Types.ObjectId("mongoID3"),
    ],
  },
}


text:
Q: How to monitor remote servers using Cacti without SSH tunnels? Nagios uses NRPE plugin to monitor remote processes.
So you need to open only one port on the remote machine.
For Cacti, you need to open all the required ports so the shell scripts can retrieve data.
Or we can use SSH tunneling.
Is there a NRPE equivalent for Cacti so remote monitor can be done securely?

A: Cacti was really intended to work with SNMP, so there isn't an elegant solution to this.
However: you're free to use NRPE in conjunction with cacti. It seems a bit weird at first, but it definitely works.


text:
Q: Switch DetailsTemplate in ListDetailsView between view and edit mode I do have a ListDetailsView showing some data (lets say Company as a simple example here). Normally the details of a Company are shown as readonly. However, via the ListDetailsView.DetailsCommandBar it is possible to edit a Company (and also add a new Company). A clear separation between view and edit mode seems to be a good choice for the UI. I'm using a UserControl to show details of a Company.
So here are my questions:

*

*Where should the differentiation between view- and edit-mode happen? I thought it is a good idea to have a CompanyDetailsControl and a CompanyDetailsEditControl and select between the two (both using the same CompanyDetailsViewModel). There are other solutions as well, for example, the CompanyDetailsControl could handle the edit- and view-mode internally.

*Assuming that it is a good idea to switch between two UserControl, how can that be realized with the ListDetailsView.DetailsTemplate? I though it would be easy to use a DataTemplateSelector here, but that is only available for the ItemTemplate.

Not sure what code to provide to clarify my questions. So in case you need any code to better understand my question please leave a comment.

A: Note: I have never worked with UWP app, only applying MVVM pattern from WPF.

Straight line where the split should happen is not drawn. It often depends on the developer himself, which framework is used and more.
Me personally would go in way where UI handles UIs' things and ViewModel handles data only. That means the view is responsible for showing you the controls you are expecting to see/control the application. And when the view learns that property was changed, it should update how it looks.
Since the point we know the app will have edit & readonly modes, we should prepare all necessary UI components (UserControls, Pages, ...) to handle both those states. They would be binded to ViewModel that have base in BaseViewModel that already have this edit variable inside. So that each UI component know it can work with that.
Base view model:
abstract class BaseViewModel : INotifyPropertyChanged
{
    private string mIsInEditMode;
    public string IsInEditMode
    {
        get { return mIsInEditMode; }
        set
        {
            if(mIsInEditMode == value) return;

            mIsInEditMode = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(IsInEditMode));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

All "normal" ViewModels inherit from it:
class CompanyViewModel : BaseViewModel
{ /* props and logic of company */ }

UI component (UserControl) would have either trigger (<Style.Triggers/>) or binded properties Visibility and IsEnabled to the BaseViewModel. Those bindings would handle this logic of showing/hiding and you have potential to control whole layouts, hide controls etc.
<UserControl d:DataContext="{x:Bind local:CompanyViewModel}">
  <UserControl.Resources>
      <local:BoolInverterConverter x:Key="BoolInvert"/>
  </UserControl.Resources>

  <Grid>

     <Grid IsVisible="{Binding IsInEditMode}" IsEnabled="{Binding IsInEditMode}">
       <!-- Controls for edit mode -->
     </Grid>

     <Grid IsVisible="{Binding IsInEditMode, Converter={StaticResource BoolInvert}}"
           IsEnabled="{Binding IsInEditMode, Converter={StaticResource BoolInvert}}">
       <!-- Controls for readonly mode -->
     </Grid>

  </Grid>
</UserControl>

Note: I've used property IsVisible, You would actually use Visibility with some custom converter.


text:
Q: Passing query string to JS window.open in IE7 doesn't work? I can run the following via the address bar in Firefox just fine:
javascript:window.open("http://my.hostname.com/test.php?id=12345", "exportWindow");

When I print_r($_GET), I see the $_GET array with the values I specified in the URL. But when I do so in IE7, it just prints "null" on screen.
EDIT
Turns out that was due to a popup blocker. However, the actual code that uses that snipped doesn't work--I get Array() in IE when print_r-ing:
  $Page->addJQuery('$("#pageForm div.export").click(function() { ' . $jQueryVars . 'window.open("' . $this->getUrl() . '"' . $jQueryParams . ', "exportWindow"); return false; });');

A: IE is blocking the popup. The 'null' you see is the return value of the JavaScript call. Turn off the popup blocker and it should work.

A: Turns out that for SOME REASON I needed to use .live("click", function() rather than .click(function(). No idea why, as I use .change in several other places which works in IE...but it fixed the problem, nevertheless.

A: It turned out that I needed to use jQuery's .live rather than .click.


text:
Q: How to declare a json object or array collection with variable size in javascript I need to create an array or json that can be filled when detects the counter like an auxiliarJson with variable size but i dont know how can i do it

TypeError: lAttrsPorDia is undefined
lAttrsPorDia[j] = __oATTRS[i];

    var lAttrsPorDia;
    var j = 0;
    for (var i = 0; i < __oATTRS.length; i++) {
        if (__oATTRS[i].Dia == counter) {
            lAttrsPorDia[j] = __oATTRS[i];
            j++;
            alert(JSON.stringify(lAttrsPorDia));
        }
    }

A: JavaScript arrays already do have variable size:
var arr = [];
arr.push('Hello');


text:
Q: Session variables not accessible in subdirectory When we moved our project from the beta test server to our live server we experienced the following:
Session variables are only accessible if the file accessing them is in the same folder as the file that created them. This was not the case on our beta server. So I've created three very simple test files:
test.php
<?php
session_id("581186accf44d7e80df40d0b5a47fb7d");
session_start();
$_SESSION['myvariable'] = 'Hello World';
?>

Same folder test

Subfolder test

Then we have the following file duplicated in the same folder and in the test/ folder.
page2.php
<?php
session_start();
print 'Here is page two, my session variable and my session cookie: ';
print $_SESSION['myvariable'];
print $_COOKIE['PHPSESSID'];
exit;
?>

and here are the results:
page2.php
Here is page two, my session variable and my session cookie: Hello
World581186accf44d7e80df40d0b5a47fb7d

test/page2.php
Here is page two, my session variable and my session cookie: 581186accf44d7e80df40d0b5a47fb7d

As you can see, the session variable has disappeared. But the session ID cookie is preserved in the subdirectory, so it isn't a cookie issue.
I've looked at the session block in phpinfo(); and aside from session.save_path, which is set on the beta server but not on the live server (which presumably means it will default to /tmp), the configuration is identical on both.
Also, we don't have a .htaccess file which might change domain.com paths to www.domain.com paths.
Because this test works on our beta server, I have concluded that it's a php configuration issue, but if someone could point me toward the parameter that needs changing, that would be much appreciated!

A: Ok, it appears that the problem occurred, in part, due to my lack of understanding of what putting my own php.ini in the public_html folder would do.
Because we can't use ini_set() on our shared server (it's disabled) I created a local copy of php.ini that contained the following lines to override dud default settings...
date.timezone =  Australia/Melbourne
magic_quotes_gpc = Off

I assumed that the values in this local version of php.ini would simply override the values in the master php.ini.
Unfortunately this is not what happens on the Jumba / UberGlobal hosting.
Creating this local php.ini meant that the entire configuration reverted to default values, except for these two settings.
The solution was for a tech from Jumba / Uberglobal to make a copy of their php.ini file (with just the above two values changed) and place it in our public_html folder.
This has fixed the problem.
Thanks for everyone's help!

A: I had a similar issue. I was able to fix it by making sure a copy of the php.ini file was present in every subdirectory that I want to access.

A: That should not occur... but ok. You can try one thing, create a file in the root and include it in all the files. That way you can run the session_start in that common file.
/common.php
/file1.php (include common.php)
/test/file2.php (include ../common.php - check paths and such)

and see if it still goes wrong.


text:
Q: I can't seem to be able to pull the tweets using the Twitter API method .. where did I go wrong? So I am testing if the variable returns the JSON data of the specified user's screen name tweets .. but it doesn't return anything and I am using the right get method .. Where did I go wrong .. Below is the code ..
 <?php
$url= "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=agasaro&count=5";
$results = json_decode(file_get_contents($url));
var_dump($results);

VAR_DUMP returns this
 Warning: file_get_contents(http://api.twitter.com/1/statuses/user_timeline.json?screen_name=agasaro&count=5) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in

A: Well you never sent that request to the twitter server.. What you did is just created a url string and then just used json_decode that same string. No API function was called so some data can be returned.
In your browser go to the url string you made. You will get the JSON output.
Either you must use an API function and pass this url to that funciton so that it returns something else use curl to do a request to that url manually and get the data and then json_decode it.
EDIT : With the edited question, I cant reproduce the error. Its working fine here. see this output.
array (size=2)
0 =>
object(stdClass)[2]
  public 'created_at' => string 'Thu Dec 20 11:11:29 +0000 2012' (length=30)
  public 'id' => float 2.8171845961476E+17
  public 'id_str' => string '281718459614760960' (length=18)
  public 'text' => string 'RPF'S 25-YEAR JOURNEY - The New Times Rwanda http://t.co/BvEuZz06 via @NewTimesRwanda' (length=87)
  public 'source' => string 'Tweet Button' (length=72)
  public 'truncated' => boolean false
  public 'in_reply_to_status_id' => null
  public 'in_reply_to_status_id_str' => null
  public 'in_reply_to_user_id' => null
  public 'in_reply_to_user_id_str' => null
  public 'in_reply_to_screen_name' => null
  public 'user' =>
    object(stdClass)[3]
      public 'id' => int 17686705
      public 'id_str' => string '17686705' (length=8)
      public 'name' => string 'Angelica Gasaro' (length=15)
      public 'screen_name' => string 'agasaro' (length=7)
      public 'location' => string 'SW florida' (length=10)
      public 'url' => null
      public 'description' => string '' (length=0)
      public 'protected' => boolean false
      public 'followers_count' => int 63
      public 'friends_count' => int 43
      public 'listed_count' => int 0
      public 'created_at' => string 'Thu Nov 27 19:42:59 +0000 2008' (length=30)
      public 'favourites_count' => int 5
      public 'utc_offset' => int -18000
      public 'time_zone' => string 'Eastern Time (US & Canada)' (length=26)
      public 'geo_enabled' => boolean true
      public 'verified' => boolean false
      public 'statuses_count' => int 70
      public 'lang' => string 'en' (length=2)
      public 'contributors_enabled' => boolean false
      public 'is_translator' => boolean false
      public 'profile_background_color' => string 'B2DFDA' (length=6)
      public 'profile_background_image_url' => string 'http://a0.twimg.com/images/themes/theme13/bg.gif' (length=48)
      public 'profile_background_image_url_https' => string 'https://si0.twimg.com/images/themes/theme13/bg.gif' (length=50)
      public 'profile_background_tile' => boolean false
      public 'profile_image_url' => string 'http://a0.twimg.com/profile_images/2849801480/1d045f13f7b8d248516900a1960be54c_normal.jpeg' (length=90)
      public 'profile_image_url_https' => string 'https://si0.twimg.com/profile_images/2849801480/1d045f13f7b8d248516900a1960be54c_normal.jpeg' (length=92)
      public 'profile_banner_url' => string 'https://si0.twimg.com/profile_banners/17686705/1352931714' (length=57)
      public 'profile_link_color' => string '93A644' (length=6)
      public 'profile_sidebar_border_color' => string 'EEEEEE' (length=6)
      public 'profile_sidebar_fill_color' => string 'FFFFFF' (length=6)
      public 'profile_text_color' => string '333333' (length=6)
      public 'profile_use_background_image' => boolean true
      public 'default_profile' => boolean false
      public 'default_profile_image' => boolean false
      public 'following' => null
      public 'follow_request_sent' => null
      public 'notifications' => null
  public 'geo' => null
  public 'coordinates' => null
  public 'place' => null
  public 'contributors' => null
  public 'retweet_count' => int 0
  public 'favorited' => boolean false
  public 'retweeted' => boolean false
  public 'possibly_sensitive' => boolean false
1 =>
object(stdClass)[4]
  public 'created_at' => string 'Sun Dec 09 15:19:29 +0000 2012' (length=30)
  public 'id' => float 2.777946036069E+17
  public 'id_str' => string '277794603606896640' (length=18)
  public 'text' => string '"@RichardDreyfuss: The Island Where People Forget to Die http://t.co/rhN3s5E9â€' (length=82)
  public 'source' => string 'Twitter for iPhone' (length=82)
  public 'truncated' => boolean false
  public 'in_reply_to_status_id' => null
  public 'in_reply_to_status_id_str' => null
  public 'in_reply_to_user_id' => null
  public 'in_reply_to_user_id_str' => null
  public 'in_reply_to_screen_name' => null
  public 'user' =>
    object(stdClass)[5]
      public 'id' => int 17686705
      public 'id_str' => string '17686705' (length=8)
      public 'name' => string 'Angelica Gasaro' (length=15)
      public 'screen_name' => string 'agasaro' (length=7)
      public 'location' => string 'SW florida' (length=10)
      public 'url' => null
      public 'description' => string '' (length=0)
      public 'protected' => boolean false
      public 'followers_count' => int 63
      public 'friends_count' => int 43
      public 'listed_count' => int 0
      public 'created_at' => string 'Thu Nov 27 19:42:59 +0000 2008' (length=30)
      public 'favourites_count' => int 5
      public 'utc_offset' => int -18000
      public 'time_zone' => string 'Eastern Time (US & Canada)' (length=26)
      public 'geo_enabled' => boolean true
      public 'verified' => boolean false
      public 'statuses_count' => int 70
      public 'lang' => string 'en' (length=2)
      public 'contributors_enabled' => boolean false
      public 'is_translator' => boolean false
      public 'profile_background_color' => string 'B2DFDA' (length=6)
      public 'profile_background_image_url' => string 'http://a0.twimg.com/images/themes/theme13/bg.gif' (length=48)
      public 'profile_background_image_url_https' => string 'https://si0.twimg.com/images/themes/theme13/bg.gif' (length=50)
      public 'profile_background_tile' => boolean false
      public 'profile_image_url' => string 'http://a0.twimg.com/profile_images/2849801480/1d045f13f7b8d248516900a1960be54c_normal.jpeg' (length=90)
      public 'profile_image_url_https' => string 'https://si0.twimg.com/profile_images/2849801480/1d045f13f7b8d248516900a1960be54c_normal.jpeg' (length=92)
      public 'profile_banner_url' => string 'https://si0.twimg.com/profile_banners/17686705/1352931714' (length=57)
      public 'profile_link_color' => string '93A644' (length=6)
      public 'profile_sidebar_border_color' => string 'EEEEEE' (length=6)
      public 'profile_sidebar_fill_color' => string 'FFFFFF' (length=6)
      public 'profile_text_color' => string '333333' (length=6)
      public 'profile_use_background_image' => boolean true
      public 'default_profile' => boolean false
      public 'default_profile_image' => boolean false
      public 'following' => null
      public 'follow_request_sent' => null
      public 'notifications' => null
  public 'geo' => null
  public 'coordinates' => null
  public 'place' => null
  public 'contributors' => null
  public 'retweet_count' => int 0
  public 'favorited' => boolean false
  public 'retweeted' => boolean false
  public 'possibly_sensitive' => boolean false

NOTE : check the links
file_get_contents throws 400 Bad Request error PHP  &  https://dev.twitter.com/discussions/678
May be you have reached the api limit for the day thats why they are blocking you and sending you a 400 response.