text:
Q: cygwin /dev/sd* disk association to hard drive Under cygwin on Windows 7, how would I certainly determine the hard drive that some path /dev/sd*  corresponds in Windows?
For example, given cygwin path /dev/sdc, which Windows letter drive does it correspond, C:\, D:\, etc.?
The following don't appear available within cygwin; tool lshw, tool parted, path /dev/disk/....

A: Assuming you are asking how to map Windows Disk to devices:
$ cat /proc/partitions
major minor  #blocks  name   win-mounts

    8     0 175825944 sda
    8     1 175824896 sda1   C:\
    8    16 1953514582 sdb
    8    17 1953512448 sdb1   E:\


text:
Q: Click handling function is not initiated JS fiddle: http://jsfiddle.net/d9nat0gk/20/

let album_images_slider = new Swiper("#album_images_slider", {
    direction: "horizontal",
    slidesPerView: 1,
    loop: true,
    allowTouchMove: false,
    speed: 600,
    autoplay: {
        delay: 3000
    },

    navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev"
    }
});

$(function() {
    console.log("hello");

    $("#album_images_slider").click(function(e) {
        console.log("hello, mate!");
        console.log(e.target.className);
        if (e.target.classList.contains("swiper-slide")) {
            console.log("hello!");
            $("body *").hide();
            $("body").before(`<div class="layer">Hey!</div>`);
        }

    });

    $(".layer").on("click", function() {
        console.log("Hi");
        $(".layer").remove();
    });
});

Block .layer is succesfully displayed on the screen, but for some reason when I click on .layer, .layer click handling isn't invoked.
What is the problem? And how can I solve that?
Any help would be highly appreciated!

A: The evaluation of the method $(".layer").on is performed on the elements when you call it, so if you try to console.log($(".layer")) just before that line, you will see that there are no elements with .layer at that point.
You should create and hide the
 at the start of your script or in the HTML, otherwise you can move the  $(".layer").on(...) piece of code after you create the element (after $("body").before("
Hey!
");)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Desativar Bootstrap Collapse após primeiro clique Tenho uma página, na qual apliquei a classe bootstrap collapse, onde ao clicar ele expande uma determinada área e a página rola até aquela parte do site. Quero que, ao clicar e expandir essa área, o botão perca essa funcionalidade, ou seja, quando expandido, mesmo o usuário clicando novamente no botão, a área permaneça aberta e não feche. Tem como fazer isso em css ou somente m javascript?

A: Ao invés de colocar as tags HTML (data-toggle="collapse" e "data-target") no botão que mostra o seu componente, mostre-o pelo js e depois desabilite o clique no botão:
$('#meu-botao').click(function(){

    $('#element-alvo-do-collapse').collapse('show');
    $('#meu-botao').unbind('click')

});

A: O collapse do bootstrap tem uma série de eventos e você pode usa-los para evitar ficar fazendo bind e unbind de eventos de click e etc.
$('.panel').on('hide.bs.collapse', function (e) {
    e.preventDefault();
});

Esse código previne que um painel aberto seja fechado.
Também existem esses eventos

show.bs.collapse  Occurs when the collapsible element is about to be
  shown
shown.bs.collapse     Occurs when the collapsible element is fully shown
  (after CSS transitions have completed)
hide.bs.collapse  Occurs when the collapsible element is about to be
  hidden
hidden.bs.collapse    Occurs when the collapsible element is fully
  hidden (after CSS transitions have completed)


text:
Q: Acess variable from another program c++ I want to create program that reads my HP in a game and automatically ask for heal when HP was below a certain amount. For that i need to read the HP variable in the game, it's an online game, Urban Terror more specifically, but i just need to check HP amount and not change it. I believe it's possible to extract the location of the memory with cheat engine.

A: I recommend you choose other projects to improve your C++ and programming knowledge.
You will need to know:
1) How to have the Game program generate an event when the HP change.
2) Find out where in memory the HP are stored.
3) Find out when the HP are valid.  For example, the HP could be stored on the stack and only valid for a given duration.
4) Research your operating system to find out how to detect when a memory location changes, it may not have any API for this.
5) Write a program that is constantly polling the HP memory location to detect a change, then activate an event when the change occurs.  You should research on the frequency that is needed for polling.


text:
Q: How to modify specify localstorage item in vuex? I want to change specify localstorage item in vuex.
For example, I have localstorage item like this:
{
  'id' = 1, 'another' = 2
}

I want to change just id, how can I do this?
I just know the basic usage like this:
localStorage.setItem("user", JSON.stringify(state.currentUser))

I tried something like this but looks like its not working
localStorage.setItem("user.id", "2")

A: You can use getItem() to get current value and spread operator to assign values as following:
const newValue = {
   ...JSON.parse(localStorage.getItem("user")),
   id: 2
}

localStorage.setItem("user", JSON.stringify(newValue))

A: You can't exactly because localStorage stores everything as strings. Best is just to replace the entire object by JSON.stringify-ing the object again after modifying it.
So essentially:
// Get the user from localStorage and parse into object
let user = JSON.parse(localStorage.getItem("user"));
// Update an attribute on the user object
user.id = 2;
// Update the user in localStorage and stringify to string
localStorage.setItem("user", JSON.stringify(user));


text:
Q: Function for regaining park capacity for visitors? I am getting used to Vensim for Modelling System Dynamics. To train, I am busy with a System Dynamics of Park Visitors. Where I have modelling the following Stock and Flow Diagram:

For the equation of 'Max Capacity' I have defined it as:

max capacity = - ( 0.05 * amount of visitors )

And also I have set the initial value to 400.000 visitors per year as a max.
This means that the carrying capacity gets lower by 5% of the total amount of visitors of the previous year. This results into the following diagram:

Now I want to make the park regain its capacity again. I initially thought of something like:

IF THEN ELSE( Max Capacity < 250000 , 0.05 * Max Capacity, - ( 0.05 *
  Amount of visitors ))

This gives the following diagram:

As you see, it doesn't really it just prevents the capacity from ever continuing to decay with 5%.
How can I make it so that the capacity regains again to 400.000 over time?


text:
Q: Python: why would Python stop saving in the present working directory Whenever I would save a file in Python, it would save in the present working directory. For some unknown reason, Python has stopped saving in the pwd.  My figures are now being saved in the directory below it.  So instead of saving in /Documents/.../OrbitalMechanics/OrbitalNotes they are now being saved in /Documents/.../OrbitalMechanics.  My operating system is Ubuntu 13.04, I am using Emacs, and writing the program from the terminal.  When I am calling my .py file, the path is emacs ~/Documents/.../OrbitalMechanics/OrbitalNotes/stumpff.py.  Therefore, I am in the correct directory.
What would cause this problem?  I haven't altered anything I normal do when I save a figure.
The program where this is occurred is below:
#!/usr/bin/env ipython
#  This program plots the Stumpff functions C(z) and S(z)

import numpy as np
import pylab
from matplotlib.ticker import MaxNLocator

def C(z):
    if z > 0:
        return (1 - np.cos(z ** 0.5)) / z
    elif z < 0:
        return (np.cosh(np.sqrt(-z)) - 1) / -z
    return 0.5

def S(z):
    if z > 0:
        return (np.sqrt(z) - np.sin(z ** 0.5)) / np.sqrt(z) ** 3
    elif z < 0:
        return (np.sinh(np.sqrt(-z)) - np.sqrt(-z)) / np.sqrt(-z) ** 3
    return 1.0 / 6.0

vC = np.vectorize(C)
vS = np.vectorize(S)

z = np.linspace(-50.0, 500.0, 500000.0)
y = vC(z)
y2 = vS(z)

fig = pylab.figure()
ax = fig.add_subplot(111)
ax.plot(z, y, 'r')
ax.plot(z, y2, 'b')
pylab.legend(('$C(z)$', '$S(z)$'), loc = 0)
pylab.xlim((-50, 0))
pylab.ylim((0, 15))
pylab.xlabel('$z$')
pylab.gca().xaxis.set_major_locator(MaxNLocator(prune = 'lower'))
pylab.savefig('stumpffneg50to0.eps', format = 'eps')

Edit:
Previously, when I saved a figure, the figure would save in the directory where the .py file was located even if I wasn't in that directory.  That is, I could be in the home directory, run the file in emacs, and the file would be where I wanted it to save.  Now, this isn't the case even though the file used to always save in the location of the python script.
If I run the file from the terminal as ipython ~/path/to/file, the figures will save where the .py file is located.
If I open the file in emacs and use C-c C-c to run the file, the files will save one level down from the directory the .py file is in.
If I cd to the directory then open the file in emacs, the file again will save one level down.

A: When you start Python, it inherits its current working directory from the shell. So, for example:
$ cd ~
$ ~/Documents/.../OrbitalMechanics/OrbitalNotes/stumpff.py

In this case, the current working directory is ~, not ~/Documents/.../OrbitalMechanics/OrbitalNotes/.
This means that any relative paths are relative to ~, so if you just create a file named foo.data, it ends up as ~/foo.data.
So, what if you want to get files into paths like ~/Documents/.../OrbitalMechanics/OrbitalNotes/foo.data? There are two basic ways to do it—either set the cwd to the script path, or use the script path explicitly. And there are two ways to do the first part, from outside or inside of the Python script. And… well, let's just go over all the variations one by one.

If you want to launch the script from its own working directory, you can of course manually cd to that directory first, or you can write a bash alias or function or script that does something like:
$(cd $(dirname $1) ./$(basename $1))

Obviously you'll want to get a bit fancier if you want to pass multiple arguments, or if you want to be able to use it on python  ~/Documents/.../OrbitalMechanics/OrbitalNotes/stumpff.py instead of just ~/Documents/.../OrbitalMechanics/OrbitalNotes/stumpff.py so the script is $2, etc. But it's all basic sh stuff from here.

If you want the script to change its own working directory, you can do that at the start of the script:
import os
import sys

scriptpath = os.path.dirname(__file__)
os.chdir(scriptpath)

(In some cases, you might want to use sys.argv[1] instead of __file__, but the details are hard to explain. If you want to learn, you can read the docs for each. If you don't want to learn, and you run into a problem, print out __file__ and see if it looks right, and, if not, try the other one.)

Or, you can just explicitly use scriptpath as a base instead of using cwd-relative paths. In this case, you'll probably want to use the absolute path to your script as a base (so later calls to chdir won't affect you):
import os
import sys

scriptpath = os.path.abspath(os.dirname(__file__))

# ...

datapath = os.path.join(scriptpath, 'foo.data')
with open(datapath, 'w') as datafile:
    # ...


text:
Q: builtin provider com.databricks.spark.csv not found in SnappyData v.0.5.2 SnappyData v.0.5.2
I am using this SnappyData version to get a fix for SNAP-961.
However, now I am unable to load data from a CSV anymore, after moving from the preview release v0.5 to v0.5.2.
ERROR IS:

ERROR 38000: (SQLState=38000 Severity=-1)
  (Server=ip-10-0-18-66.us-west-2.compute.internal[1528],Thread[DRDAConnThread_28,5,gemfirexd.daemons])
  The exception 'Failed to find a builtin provider
  com.databricks.spark.csv;' was thrown while evaluating an expression.

Here is what I am executing:
-- creates in-memory table from csv
CREATE TABLE STAGING_ROAD (road_id string, name string) USING com.databricks.spark.csv OPTIONS(path 'roads.csv', header 'true', inferSchema 'false');

A: There has been an alignment of SQL and Spark APIs so now only builtin datasources (column, row, streaming/AQP ones) can use "CREATE TABLE" while others have to use "CREATE EXTERNAL TABLE". Similar was the case with SnappyContext where createTable API could be used only for builtin sources while for others createExternalTable was required. The following should work with both older releases and newer ones:
CREATE EXTERNAL TABLE STAGING_ROAD (road_id string, name string) USING com.databricks.spark.csv OPTIONS(path 'roads.csv', header 'true', inferSchema 'false')


text:
Q: Insert CSV line by line Into Postgres using PHP PDO I am trying to have the user upload a file and then have the file be inserted into a postgres database line by line.
I have this code and I am getting the following error with my syntax:

Array ( [0] => 42601 [1] => 7 [2] => ERROR: syntax error at or near
  ""INSERT INTO "" LINE 1: "INSERT INTO "public"."tblSedimentGrabEvent"
  VALUES ('A1000'... ^ )

I have been looking at the PHP PDO manual and the Postgres site as well as searching for the error code but still no success. I know its probably something small but its got me stumped.
<?php
try {
    $db = new PDO("pgsql:dbname=name;host=host","user","pass");
}
catch(PDOException $e) {
    echo $e->getMessage();
}

if ($_FILES["file"]["error"] > 0)
{
    echo "Error: " . $_FILES["file"]["error"] . "
";
}
else
{
    echo "Uploaded Successfully!
";
    echo "File Name: " . $_FILES["file"]["name"] . "
";
    echo "Type: " . $_FILES["file"]["type"] . "
";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB
";
    echo "Temp file: " . $_FILES["file"]["tmp_name"]. "
";
    {
        move_uploaded_file($_FILES["file"]["tmp_name"],
        "D:/Apapub/public_html/databases/B13/temp/" . $_FILES["file"]["name"]);
        echo "Stored in: " . "D:\Apapub\public_html\databases\B13\temp" . $_FILES["file"]["name"]. "
";
    }

 }

$file_handle = fopen("D:/Apapub/public_html/databases/B13/temp/grabevents.txt", "r");

while (!feof($file_handle) ) {

    $text_file = fgetcsv($file_handle);

    print_r($text_file);

    $query=<<<eof
"INSERT INTO "public"."tblSedimentGrabEvent" VALUES ('$text_file[0]','$text_file[1]','$text_file[2]','$text_file[3]','$text_file[4]','$text_file[5]','$text_file[6]','$text_file[7]','$text_file[8]','$text_file[9]','$text_file[10]','$text_file[11]','$text_file[12]','$text_file[13]','$text_file[14]','$text_file[15]','$text_file[16]','$text_file[17]','$text_file[18]','$text_file[19]','$text_file[20]','$text_file[21]','$text_file[22]','$text_file[23]')"
    eof;
    $sth = $db->query($query);
}
if (!$sth) {
    echo "
\nPDO::errorInfo():\n
";
    print_r($db->errorInfo());
}
fclose($file_handle);

echo "
Records Imported
";

?>

Here is the sample array:
A1000,24,M,28/Mar/2013,11:45:27,1,SCCWRP,Singel Van Veen,33.1234,-118.523,AGPS,12,cm,Olive Green,Sand,None,Yes,No,No,No,None,Test Record # 1,No,22/May/2013
A1000,24,M,28/Mar/2013,11:45:27,1,SCCWRP,Singel Van Veen,33.1334,-118.543,AGPS,12,cm,Olive Green,Sand,None,Yes,No,No,No,None,Test Record # 1,No,15/May/2013
A1000,24,M,28/Mar/2013,11:56:33,2,SCCWRP,Single Van Veen,33.1635,-118.593,AGPS,12,cm,Olive Green,Sand,None,No,Yes,No,No,None,Test Record #2,No,15/May/2013
A1000,24,M,28/Mar/2013,12:06:33,3,SCCWRP,Single Van Veen,33.1534,-118.563,AGPS,12,cm,Olive Green,Sand,None,No,No,Yes,No,None,Test Record #3,No,15/May/2013
A1000,24,M,28/Mar/2013,12:12:33,4,SCCWRP,Single Van Veen,33.1034,-118.503,AGPS,12,cm,Olive Green,Sand,None,No,No,No,yes,None,Test Record #4,No,15/May/2013

I was successful using the COPY command but my supervisor wants it to parse in line by line to run some checks later on
!!ANSWER!!
I dont know how to give props to @Spudley but he helped me to answer the question.
After doing what he said I found that I dont need quotes around the query ( I guess its becuase I'm using heredoc?).
This worked (but: edit by Craig Ringer, this is still dangerously insecure and should never be used, do not copy this as example code):
$query=<<<eof
INSERT INTO "public"."tblSedimentGrabEvent" VALUES ('$text_file[0]','$text_file[1]','$text_file[2]','$text_file[3]','$text_file[4]','$text_file[5]','$text_file[6]','$text_file[7]','$text_file[8]','$text_file[9]','$text_file[10]','$text_file[11]','$text_file[12]','$text_file[13]','$text_file[14]','$text_file[15]','$text_file[16]','$text_file[17]','$text_file[18]','$text_file[19]','$text_file[20]','$text_file[21]','$text_file[22]','$text_file[23]')
eof;
$sth = $db->query($query);

Thanks Again!

A: Doing text substitution into SQL is error prone, insecure, hard to debug, and terrible style. Use parameterised statements, either with PDO or with pg_query_params. Your "answer" is totally insecure, please do not use it.
That will not only fix your problem, it will protect you against a whole class of severe security vulnerabilities including SQL injection. See wikipedia, bobby tables and the PHP manual.
See this prior answer too.
While you're at it, consider using COPY, which is vastly more efficient, to just stream the CSV directly into a table in PostgreSQL. See pg_copy_from or the lower level pg_put_line function.

A: I got the answer from this page:
PHP PDO: Can I bind an array to an IN() condition?
My code ended up like so:
$file_handle = fopen("D:/Apapub/public_html/databases/B13/temp/grabevents.txt", "r");

while (!feof($file_handle) ) {

$text_file = fgetcsv($file_handle);

foreach($text_file as &$val)
$val=$db->quote($val);

$data = implode(',',$text_file);

$q = $db->prepare('Insert Into "public"."tblSedimentGrabEvent" Values ('.$data.')');

$q->execute();
}

And now it works perfectly while hopefully preventing SQL Injections.


text:
Q: Variance and Likelihood my friend recently asked me this question but I do not know how to answer him. Could you help me out with it?
Everyday, John buys a $1 falafel sandwish at the food cart with a probability of 50%. Let F be the amount he spends on falafel sandwiches over the next 180 days.
1)Find E[F] and Var[F]
2)Approximate the likelihood that F>210
I got E[F] to be $90 but i cannot get Var[F] and isn't the likelihood that F>210 equals zero?

A: The distribution that is appropriate here is the binomial distribution with $n= 180$ and $p=0.5$. For that distribution the mean is $np =90$ and the variance is $np(1-P)= 90\cdot 0.5 = 45 $
I agree that $F$ being greater than 210 is impossible as the maximum value is 180.  Perhaps what they are after is the normal approximation to the binomial distribution which allows you to answer questions like probability that money spent is $>110$ (a more sensible question!).
Check out the normal approximation to the binomial - it should give a worked example you can follow.


text:
Q: Pycharm. Switch off hierarchy/navigation bar After upgrading to 2017 version, new hierarchy bar appeared:
How to switch it off?
There is no name for this bar in "View" options, so I even don't know how to search for it.

A: It's breadcrumbs.
You can switch them off in File - Settings - Editor - General - Appearance - Show breadcrumbs.


text:
Q: Putting Text in between 2 Input Boxes React I am attending to have 2 input boxes next to each other with text in between them. Something like this
[0...    ] < Ranking < [1000...]

However, the most I've been able to get is the two input boxes with no text in between.
This is my code so far attending to put the text in between them.
return(

                <input type={"text"} required={true} placeholder={"0..."} name={"id"}  onChange={update} />

            <text> < Ranking < </text>

                <input type={"text"} required={true} placeholder={"1000..."} name={"id"}  onChange={update} />

    );

And my CSS file

.two-col {
    overflow: hidden;/* Makes this div contain its floats */
}

.two-col .col1,
.two-col .col2 {
    width: 50%;
    background: #f2f2f2;
}

.two-col .col1 {
    float: left;
}

.two-col .col2 {
    float: right;
}

Any help is much appreciated.

A:

    <input type={'text'} required={true} placeholder={'0...'} name={'id'} onChange={update} />

 < Ranking <

    <input type={'text'} required={true} placeholder={'...1000'} name={'id'} onChangeonChange={update} />

Using flex
.container {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}

You can have more control over the row using display: grid (not as well supported as flexbox).
EDIT: graph container

      <input
        type={"text"}
        required={true}
        placeholder={"0..."}
        name={"id"}
        onChange={"update"}
      />

 < Ranking <

      <input
        type={"text"}
        required={true}
        placeholder={"...1000"}
        name={"id"}
        onChange={"update"}
      />

    graph view

CSS
.container {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}

.container.inputs {
  width: 50%;
}

.graphview {
  width: calc(50% - 10px);
  border: 5px solid rgba(0, 0, 0, 1);
}

When using percents and borders, you have to calculate the width.

A: Try to use flexbox
.two-col {
    display: flex;
}

.two-col .col1,
.two-col .col2 {
    background: #f2f2f2;
}

and remove other css


text:
Q: Moving a File with AppleScript Today is my first day of even knowing AppleScript exists so I apologize if this is a stupid question. I've searched and can't find the answer on how to simply move a file with AppleScript
All I need to do is move a file from ~/Downloads/blank.potx to ~/Library/Application Support/Office/User Templates/My Templates
This is what I have in AppleScript right now:
tell application "Finder"
     move "~/Downloads/blank.potx" to "~/Library/Application Support/Microsoft/Office/User Templates/My Templates/blank.potx"
end tell

When I run this it gives me an error:
error "Finder got an error: AppleEvent handler failed." number -10000

Again, first day using AppleScript and I'm lost.  Any help you can provide would be awesome.
If there's a better way to do this please let me know as well.
Thanks!

A: Search is your friend. You can easily find the syntax on stack overflow. Such as here:
tell application "Finder"
    move POSIX file "/Users/xx/Documents/img.jpg" to POSIX file "/Users/xx/Documents/State" with replacing
end tell

If you're gonna use Posix file paths, you need to indicate so, and you need to name the string as a file.


text:
Q: How can I fix DLL loadfailed with Polygonize in QGIS 1.8?
Possible Duplicate:
Qgis polygonize problem - DLL load fail

I'm getting the following error message when I try to use the polygonize tool in QGIS 1.8 (windows 7):
Traceback (most recent call last):
File "C:\PROGRA~2\Quantum GIS Lisboa\bin\gdal_polygonize.py", line 34, in
import gdal, ogr, osr
File "C:\PROGRA~2\Quantum GIS Lisboa\apps\Python27\lib\site-packages\gdal.py", line 2, in
from osgeo.gdal import deprecation_warn
File "C:\PROGRA~2\Quantum GIS Lisboa\apps\Python27\lib\site-packages\osgeo\__init__.py", line 21, in
_gdal = swig_import_helper()
File "C:\PROGRA~2\Quantum GIS Lisboa\apps\Python27\lib\site-packages\osgeo\__init__.py", line 17, in swig_import_helper
_mod = imp.load_module('_gdal', fp, pathname, description)
ImportError: DLL load failed: No se encontró el proceso especificado.

I can perform this operation with the same raster file on QGIS 1.7 on this very same computer. (This is for a class I'm giving and all the students have installed 1.8).

A: Could you try adding  C:\PROGRA~2\Quantum GIS Lisboa\bin\ to the beginning of your PATH variable and see if it works?

Is C:\QGIS\python (or C:\Python26\Lib\site-packages\PyQt4\bin ) or something similar in your PYTHONPATH environment variable? You might want to remove it. This seems like Python module version mismatch. QGIS 1.7 uses Python 2.6 while 1.8 uses 2.75.
I'm betting that QGIS 1.8 is getting the DLLs for QGIS 1.7 as it may be in your PYTHONPATH.


text:
Q: problems with onCellLocationChanged I need to start service when my device change cell connection and I presume to do that with onCellLocationChanged() implements below but the beeps start only if I receive incoming calls...
my listener:
public class CellLocationListener extends PhoneStateListener {

    @Override
    public void onCellLocationChanged(CellLocation location) {
        super.onCellLocationChanged(location);

        int cid = 0;
        int lac = 0;

        if (location != null) {
            if (location instanceof GsmCellLocation) {
                cid = ((GsmCellLocation) location).getCid();
                lac = ((GsmCellLocation) location).getLac();
            }
            else if (location instanceof CdmaCellLocation) {
                cid = ((CdmaCellLocation) location).getBaseStationId();
                lac = ((CdmaCellLocation) location).getSystemId();
            }
        }

        String cellInfo = Integer.toString(lac)+"-"+Integer.toString(cid);

        Log.v("logg","CELL CHANGED:"+cellInfo);
    }
}

I've used the same cellInfo on mainactivity and when I start it cellInfo chages its value but no beeps from broadcas receiver....
on manifest:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_UPDATES" />

<receiver android:name="dado.auto3gdataswitch.CellChangeReceiver">
    <intent-filter>
        <action android:name="android.intent.action.PHONE_STATE" />
    </intent-filter>
</receiver>

my broadcastReceiver
  public class CellChangeReceiver extends BroadcastReceiver {

     TelephonyManager telephony;

     public void onReceive(Context context, Intent intent) {
        CellLocationListener phoneListener = new CellLocationListener();
        telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        telephony.listen(phoneListener, CellLocationListener.LISTEN_CALL_STATE);

        Toast.makeText(context, "ON receiver", Toast.LENGTH_LONG).show();

        final MediaPlayer mp = MediaPlayer.create(context, R.raw.beep);
        mp.start();
        mp.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.stop();
                mp.release();
            }
        });

        Log.v("logg","onreceiver");

    }
}

I hear a beep only if I receive incoming call and not if I change cell....
What's wrong??

A: You are listening to CellLocationListener.LISTEN_CALL_STATE, but you should listen for CellLocationListener.LISTEN_CELL_LOCATION. And if you want the sound to be played on cell change, you should move the corresponding code to the onCellLocationChanged. And your cell change listener will be registered only when android.intent.action.PHONE_STATE will be received.

A: I've foud a better solution!!!
in my mainActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final TelephonyManager telm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    int events = PhoneStateListener.LISTEN_CELL_LOCATION;
    telm.listen(phoneStateListener, events);

.....
}

private final PhoneStateListener phoneStateListener = new PhoneStateListener() {

    @Override
    public void onCellLocationChanged(CellLocation location) {
        super.onCellLocationChanged(location);

        int cid = 0;
        int lac = 0;

        if (location != null) {
            if (location instanceof GsmCellLocation) {
                cid = ((GsmCellLocation) location).getCid();
                lac = ((GsmCellLocation) location).getLac();
            }
            else if (location instanceof CdmaCellLocation) {
                cid = ((CdmaCellLocation) location).getBaseStationId();
                lac = ((CdmaCellLocation) location).getSystemId();
            }
        }

        String cellBase = Integer.toString(lac)+"-"+Integer.toString(cid);

        Toast.makeText(getBaseContext(), cellBase, Toast.LENGTH_LONG).show();
        Log.v("logg", "cell:"+cellBase);

        final MediaPlayer mp = MediaPlayer.create(getBaseContext(), R.raw.beep);
        mp.start();
        mp.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {

                mp.stop();
                mp.release();
            }
        });
    }
};


text:
Q: substitute for MYSQL variable setting in select statement in postgres? I have MYSQL statements performing procedural processing and try to convert these
statements into postgresql.
Mysql statements in simple version is following:
select
 case when (eventcode = 10 or eventcode = 30) and @ssid < tmstamp then @ssid := tmstamp
      when eventcode = 50 and @ssid is null then @ssid := tmstamp
      else @ssid end as sessionid
from sometable
order by tmstamp;

The point is that allocating value of current row is possible and that value should
be referenced at next row.
I tried several method including sub-query & inline views.
But I can't get solution.
Is there any idea?


text:
Q: CSS scaling a border-image I am seeking some assistance creating a border that scales with different screen sizes/devices.  I've attached both the desired outcome, html/css I've written so far and a live page to preview the results so far.
Issues/Questions:

*

*The border is set using pixels, and I'm concerned that it won't scale to the proper proportions on different devices/browsers.

*The corners don't match very well.

*Is there a better way to achieve the desired border so as to scale proportionally and achieve the desired corner formatting? Maybe a vector image?

I'm close to achieving a match, but there must be a (more simple? better?) way to re-create that type of border.  Many thanks for looking this over and for your input.
Regards,
Zephyr
EDIT/UPDATE:
I've also tried using background-image: and creating six .png files, one for each corner with a solid white background, and one each for the top/bottom and left/right sides of the "border".  Again, it's close but the images don't always line up correctly.
There must be a way to do this, perhaps in a svg image that scales itself depending on the size of the section its in, but that is way beyond my talents.
Thanks for considering the issue!

The desired formatting:
See the desired formatting here
The current results & html/css:
See the border-image: results here
See the background-image: results here
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>
        EP Layout Test
    </title>

        This is some regular text.

            SINGLE-ENGINE FAILURE/FLAMEOUT

            Symptoms:

                TGT, Ng, torque, and Np on malfunctioning engine decreasing toward zero.

                NO. 1 ENG OUT or NO. 2 ENG OUT warning light illuminated.

            Corrective Action:

                Nr - MAINTAIN.

                CONTGCY PWR - ON.

                Altitude/Airspeed - AS REQUIRED.

                Fuel/stores - JETTISON AS REQUIRED.

                ENG Anti-ice - AS REQUIRED.

                Analyze.

            If no indication of mechanical malfunction or engine fire:

                Perform Engine Restart Procedure.

            If Engine Restart Procedure is not to be performed:

                Conduct EMER ENG SHUTDOWN.

                LAND AS SOON AS PRACTICABLE.

        This is some regular text.

Original code using border-image
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>
        EP Layout Test
    </title>

        This is some regular text.

            SINGLE-ENGINE FAILURE/FLAMEOUT

            Symptoms:

                TGT, Ng, torque, and Np on malfunctioning engine decreasing toward zero.

                NO. 1 ENG OUT or NO. 2 ENG OUT warning light illuminated.

            Corrective Action:

                Nr - MAINTAIN.

                CONTGCY PWR - ON.

                Altitude/Airspeed - AS REQUIRED.

                Fuel/stores - JETTISON AS REQUIRED.

                ENG Anti-ice - AS REQUIRED.

                Analyze.

            If no indication of mechanical malfunction or engine fire:

                Perform Engine Restart Procedure.

            If Engine Restart Procedure is not to be performed:

                Conduct EMER ENG SHUTDOWN.

                LAND AS SOON AS PRACTICABLE.

        This is some regular text.

A: Could this solve your problem? http://jsfiddle.net/65nhJ/

Text

CSS:
#borderImage{
   /* background-image: url(chapter_3_background-small.png); */ /*Your border image*/
    background-color: red; /*removeme*/
    width: 70%;
    margin: 0 auto;
    padding: 20px; /*Border size*/
}
.ep {
    background-color: white;
}

Instead of use a real border-image use a fake parent div with the background of your image (repeated) and then set to white the background to don't show background (border) of the parent div.
I you need more help just comment.

A: SOLUTION!
As suggested by José Cabo (above) I stumbled across an example of the repeating-linear-gradient property here and coupled with a solid white background for the content div, I have exactly what I was hoping to achieve - all with only a few lines of CSS.
No messing with images and corners and pixel widths... grrr.
Simple, elegant, scalable - beautiful!
I have more testing to do using other browsers, but it works in Safari, and that's a giant leap toward what I'm trying to achieve.
See the solution here
Regards,
Zephyr
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>
        EP Layout Test
    </title>

        This is some regular text.

                SINGLE-ENGINE FAILURE/FLAMEOUT

                Symptoms:

                    TGT, Ng, torque, and Np on malfunctioning engine decreasing toward zero.

                    NO. 1 ENG OUT or NO. 2 ENG OUT warning light illuminated.

                Corrective Action:

                    Nr - MAINTAIN.

                    CONTGCY PWR - ON.

                    Altitude/Airspeed - AS REQUIRED.

                    Fuel/stores - JETTISON AS REQUIRED.

                    ENG Anti-ice - AS REQUIRED.

                    Analyze.

                If no indication of mechanical malfunction or engine fire:

                    Perform Engine Restart Procedure.

                If Engine Restart Procedure is not to be performed:

                    Conduct EMER ENG SHUTDOWN.

                    LAND AS SOON AS PRACTICABLE.

        This is some regular text.


text:
Q: Episerver 6 property with condition This get; How do I adjust this get set to work in a class that inherits from TypedPageData (Episerver 6)
[PageTypeProperty(
 EditCaption = "Caption",
 HelpText = "Hint here",
 Type = typeof(PropertyUrl),
 Tab = typeof(ComposerTab))]

     public virtual string Property1 {
      get
      {
       if (String.IsNullOrWhiteSpace(Property1.ToString()))
        return "http://www.blabla.com";
       return "sdfsdf";
      }
      set { Property1 = value; }
     }

At the moment it has no value.
Probably to do with how properties are defined in Epi? Thanks

A: You can do the following:
public virtual string Property1 {
      get
      {
       if (String.IsNullOrWhiteSpace(this.GetPropertyValue(page => page.Property1)))
        return "http://www.blabla.com";
       return "sdfsdf";
      }
      set { this.SetPropertyValue(page => page.Property1, value); }
     }

`


text:
Q: Runtime Chart on Web using C# I want to make runtime chart on the web using ASP.net c#.
However, everytime update panel triggered by the timer_tick event(1 second), whole the datapoints are going lost.
Here is the code snippet aspx;
<ig:WebScriptManager ID="WebScriptManager1" runat="server">
        </ig:WebScriptManager>
        <asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick">
        </asp:Timer>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" ViewStateMode="Enabled">
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="Timer1" />
            </Triggers>
            <ContentTemplate>
             StackedareaChart Content here ...

Here is c# code;
int maxDataPoints=60;

   public void Timer1_Tick(object sender, EventArgs e)
   {
     foreach (NumericSeries series in this.MonitorChart.Series)
     {
       for (int i = 0; i <= maxDataPoints; i++)
        {
            NumericDataPoint nd = new NumericDataPoint(0, string.Empty, false);
            series.Points.Add(nd);
        }

    if (series.Points.Count >= maxDataPoints)
        {
        series.Points.RemoveAt(0);
        }
     if (series.Label == "User I/O")
        {
            getCurrentValues(cmdUserIO, series);
        }
    else if (series.Label == "Administrative")
        {
            getCurrentValues(cmdAdministrative, series);
        }
}
}

      public void getCurrentValues(string cmdOrcl, NumericSeries series)
{
    OracleConnection con = new OracleConnection(oradb);
    OracleCommand cmd = new OracleCommand(cmdOrcl, con);
    con.Open();
    OracleDataReader dr = cmd.ExecuteReader();
    dr.Read();

    if (dr.HasRows == false)
    {
        NumericDataPoint nd = new NumericDataPoint(0, string.Empty, false);
        series.Points.Add(nd);
    }

    else if (dr.HasRows == true)
    {
        drCurrent = dr.GetDouble(0) / (timeInvertal * 100);

        if (cmdOrcl == cmdUserIO)
        {
            NumericDataPoint nd = new NumericDataPoint(drCurrent - tempCPU, string.Empty, false);
            series.Points.Add(nd);
            tempCPU = drCurrent;
        }
        else if (cmdOrcl == cmdAdministrative)
        {
            NumericDataPoint nd = new NumericDataPoint(drCurrent - tempAdministrative, string.Empty, false);
            series.Points.Add(nd);
            tempAdministrative = drCurrent;
        }
    }
}

How can i solve this problem ?


text:
Q: How to get a database and collection from MongoDB ClientSession I am trying to create a connection to a database - collection using a ClientSession in pymongo 3.7.1. From the example provided by the doc here : https://docs.mongodb.com/manual/core/transactions/, it seems possible to get a connection to a database and cursor.
I tried something really similar :
import pymongo
client = pymongo.MongoClient('mongodb://localhost:27017')
session = client.start_session()
session.get_database('test')

But the last line raise the following exception :

AttributeError: 'ClientSession' object has no attribute 'get_database'

I also tried two other more direct access to the database :
session['test_database']
session.test_database

which raised :

TypeError: 'ClientSession' object has no attribute 'getitem'
  AttributeError: 'ClientSession' object has no attribute 'db_test'

How does the ClientSession behaves ? Apparently is does not inherit from the Client object, otherwise the previous line would work...
Does someone have an idea ?

A: Edit I just found, I have to use session.client to retrieve the Client from the ClientSession


text:
Q: Using OpenSSL without threads Whenever I bash into OpenSSL on Windows or Mac I always make my own memory BIOs, and link them up to the platforms message based (asynchronous non blocking) socket implementation. (WSAAsyncSelect on windows: CFSocket on Mac)
Secure programming with the OpenSSL API hosted on ibm.com seems to be the best reference on implementing OpenSSL - but it implements a very simple blocking connection.
Is there a standard way to setup and use OpenSSL with non blocking sockets - such that calls to SSL_read will not block if there is no data for example?

A: SSL_read() (and the other SSL functions) work fine if the underlying socket is set non-blocking.  If insufficient data is available, it will return a value less than zero; SSL_get_error() called on the return value will return SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, indicating what SSL is waiting for.

A: Using BIO_set_nbio with either BIO_new_socket or BIO_new_connect/accept is probably less code than creating memory BIOs. Not sure if there's anything more standard than that. The docs explain this in more detail:
http://www.openssl.org/docs/crypto/BIO_s_connect.html


text:
Q: Excluding a Word in Regex Java | Mobile vision API |Text block I made a simple license plate scanning application when i am scanning it only Detect a word "SINDH" not the above number like AFR-2020 it only detects "SINDH" an goes to Textblock
AFR-2020 is above "SINDH"
below is the regex how can i exclude SINDH
String REGEX = "[a-zA-z]{1,4}\\s*[-]*[0-9]{0,2}\\s*[-]*[0-9]{3,4}$";
    Pattern number;
    Matcher matcher;
    text = mText.getValue();

A: the following regex matches AFR-2020 but not SINDH
String regex = "[A-Z]+\\-\\d+";

matches at least one uppercase character followed by a - followed by at least one digit


text:
Q: Getting Issue when running migration but through console its works When i am running this query through migration it gives Error-
Query -
ActionEvent.includes([:historic_task_allocation, {:task_results =>[:task_result_status, :user]}]).where("action_events.ae_type = 0 AND action_events.result_status <> 2 AND task_result_statuses.is_completion AND users.id NOT IN (SELECT user_id FROM allocation_user_links aul WHERE aul.task_allocation_id = task_allocations.id AND aul.valid_from < action_events.date AND (aul.valid_to > action_events.date OR aul.valid_to IS NULL))")

Error -

Mysql2::Error: Unknown column 'task_allocations.can_complete_late' in
  'field list':

But through console its work.
Where is the problem?

A: Resolved This Issue By just adding the below line in above the query in self.up methods.
  TaskAllocation.reset_column_information  # Resets all the cached information about columns, which will cause them to be reloaded on the next request.


text:
Q: the import of com google android gms appstate cannot be resolved after update sdk using eclipse After update sdk to version 6 api23 cannot compile the program in eclipse with error:

the import of com google android gms appstate cannot be resolved.

While it was perfectly OK the moment just before i did update the SDK.
There is the same situation found on stackoverview but it was solved using android studio gradle and not using eclipse.


text:
Q: ASP.NET Nested OOP Best Approach for Query Performance //option 1
public class division
{
    public int DivisionId { get; set; }
    public string DivisionName { get; set; }
    public employee Employee { get; set; }

    public class employee
    {
        public int EmpId { get; set; }
        public string EmpName { get; set; }

        public employee(int id)
        {
            sql = new SqlCommand("select empid,empname from employee where divisionid = '" + id + "'", conn);
            conn.Open();
            dt = sql.ExecuteReader(CommandBehavior.SingleRow);
            if (dt.Read())
            {
                EmpId = id;
                EmpName = (string)dt["empname"];
            }
            dt.Close();
            conn.Close();
        }
    }
    public division(int id)
    {
        sql = new SqlCommand("select divisionid,divisionname from division where divisionid = '" + id + "'", conn);
        conn.Open();
        dt = sql.ExecuteReader(CommandBehavior.SingleRow);
        if (dt.Read())
        {
            DivisionId = id;
            DivisionName = (string)dt["divisionname"];
            Employee = new employee((int)dt["divisionid"]);
        }
        dt.Close();
        conn.Close();
    }
}

//option 2
public class division
{
    public int DivisionId { get; set; }
    public string DivisionName { get; set; }
    public employee Employee { get; set; }

    public class employee
    {
        public int EmpId { get; set; }
        public string EmpName { get; set; }

        public employee()
        {
        }
    }
    public division(int id)
    {
        sql = new SqlCommand("select divisionid,divisionname from division a join employee b on a.divisionid = b.divisionid where a.divisionid = '" + id + "'", conn);
        conn.Open();
        dt = sql.ExecuteReader(CommandBehavior.SingleRow);
        if (dt.Read())
        {
            DivisionId = id;
            DivisionName = (string)dt["divisionname"];
            Employee = new employee();
            Employee.EmpId = (int)dt["empid"];
            Employee.EmpName = (string)dt["empname"];
        }
        dt.Close();
        conn.Close();
    }
}

The question I want to ask is, which of these two snippets perform better.
The first method, which made it convenient to call each Attribute on the class, but it require a nested connection to call the class and its attribute.
Example(option1), 2 roundtrip to database, first one is when we call Division, and the second connection is when we call Employee.
But SQL required for each connection trip to database is very convenient to code(simple and shorter).
The second method, using the join query to call employee from each division.
It only require 1 roundtrip to database but with more complicated code.
These example are a simple form of Nested OOP, but what happened when the related table are complicated(eg. 5-6 table relationship), which means we need a long and complicated query using join for each table.

A: The roundtrips to the database are expensive, so the second option performs better. If you need the join to perform better, add an index on divisionid column of the employee table.
The second option is kind wrong now, maybe you didn't show here the latest version of it. Instead of
sql = new SqlCommand("select divisionid,divisionname from ..

it should be
sql = new SqlCommand("select a.divisionid, divisionname, empid, empname  from ..

Are you sure the division has only one employee?


text:
Q: Configuration proxy due iptables i have to configure my server to redirect from 80 and 443 port due to 8443 using iptables
          -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
          -A INPUT -p tcp -m tcp --dport 8443 -j ACCEPT
          -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
          -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
          -A PREROUTING -i eth0 -p tcp -m tcp --dport 80:443 -j REDIRECT --to-ports 8443

when i browse like https protocol everything is working, but when from http, i can just donwnload a file, and don't see anything

A: 8443 port is intended mainly to use as HTTPS proxy. Sending plain HTTP to this port will not work. You should keep separated HTTP and HTTPS traffic by sending them to a different port (normally 8080) of your transparent proxy.

A: using this rule :
-A PREROUTING -i eth0 -p tcp -m tcp --dport 80:443 -j REDIRECT --to-ports 8443
you allowed only incoming traffic to to be sent to port 8443, but still the outgoing traffic needs to be routed


text:
Q: Adding attribute list to collection in form I'm aiming to have a drop down box in a form that will give the user a list of all the 'specialties' already available.
I have a guidelines model and this model has an attribute :specialty but I'm not sure how to add this in my form in views/guidelines/_form.html.erb (I'm using simple_form)
guidelines_controller.rb
def listspecialty
@speclist = Guideline.order(:specialty).uniq.pluck(:specialty)

def topicspecialty
 @guidelines = Guideline.find_all_by_specialty(params[:specialty])

views/guidelines
new.html.erb
<%= render 'form', speclist: @speclist %>

*_form.html.erb*
<%= f.input :specialty, as: :select, collection: speclist %>

listspecialty.html.erb
    <% @speclist.each do |specialty| %>
<%= link_to specialty, :action => :topicspecialty, :specialty => specialty %>

ROUTES
get "guidelines/listspecialty"
  get "guidelines/topicspecialty"
  match "specialty", to: "guidelines#listspecialty", as: :specialty
  get '/:id', to: 'guidelines#topic'
  get '/:id', to: 'guidelines#topicspecialty'

A: For simple_form try this:
<%= f.input :specialty, as: :select, collection: @list %>

Also you could simplify your array code to:
@list = @guidelines.map(&:specialty).uniq

Or if you're getting the guidelines just for the @list then do:
@list = Guideline.order(:specialty).uniq.pluck(:specialty)

To pass @list to your form you might have to pass it to the partial:
# guidelines controller
def list_specialty
  #some code
  @list = Guideline.order(:specialty).uniq.pluck(:specialty)
end

# routes, something like:
match "specialty", to: "guidelines#list_specialty", as: :specialty

# where you add your partial
<%= render 'form', list: @list %>

# then in your form
<%= f.input :specialty, as: :select, collection: list %>

Update
new.html.erb correlates to the guidelines#new action, so any code you want to use in the view should also be in the action, e.g:
# guidelines controller
def new
  @specialties = Guideline.order(:specialty).uniq.pluck(:specialty)
  @guideline = Guideline.new
end

# in guidelines/new.html.erb
<%= simple_form_for @guideline do |f| %>
  <%= f.input :some_attr %>
  <%= f.input :specialty, as: :select, collection: @specialties %>
  ....
<% end %>


text:
Q: How to get 's that appear after a specific ? This is the layout of the webpage:

Featured Ads

Ads

There is nothing in the class of the regular Ads that I can use to differentiate them. What would be an efficient way to only return the 's that appear after
Ads
?
Update:
Here's the final code
h2 = soup.find("h2", text="Ads")
articles = h2.find_next_siblings("article")

for article in articles:
    for div in article.find_all('div', {'class': 'address'}):
        for link in div.find_all('a', href=True):
            print (link['href'])

Update 2: had to refactor...
articles = soup.find("h2", text="Ads").find_next_siblings("article")
for article in articles:
    ad_url = article.find('a', href=True)['href']

A: Locate the h2 element and find the next a sibling:
h2 = soup.find("h2", text="Ads")
a = h2.find_next_sibling("a")


text:
Q: Solving the functional equation $f(a + b) = a + f(b)$ How would you solve:
$$f(a+b)=a+f(b) ?$$
It seems similar to the Cauchy equation $$f(a+b)=f(a)+f(b),$$ but I'm not sure what to do with this. I have a feeling the only solution is $f(k)=k$ but idk.
Thanks for the help, Guys!

A: Hint Setting $b = 0$ gives $$f(a) = a + f(0),$$ so any such function is determined by $f(0)$.

A: If $f(a + b) = a + f(b)$ for every $a$ and $b$, then, putting $c = f(0)$,  $f(x) = f(x + 0) = x + f(0) = x + c$ for any $x$. Conversely for any given $c$ if you define $f(x) = x + c$, then $f$ satisfies $f(a+b) = a + b + c = a + f(b)$. So the solutions are all functions of the form $f(x) = x + c$.

A: Another approach would be to notice that in
$$f(a+b)=a+f(b)$$
the left hand side is symmetric in $a$ and $b$, while the right hand side is not, and we can exploit this: swap $a$ and $b$. The left hand side remains unchanged, and hence so must the right hand side, and so we must have that
$$a+f(b)=b+f(a)$$
for all $a$ and $b$.
This gives us that for all $a$ and $b$,
$$f(a)-a=f(b)-b$$ and so
$$f(x)-x$$
is constant. We thus have that $f(x)=x+c$ for all $x$ for some constant $c$, and we can easily check that any such function satisfies the functional equation.


text:
Q: python post large files to django I am trying to find the best way (most efficient way) to post large files from a python application to a Django server.
If I rely on raw_post_data on the Django side then all the content needs to be in RAM before I can read it which doesn't seem efficient at all if the file received is 100s of megs.
Is it better to use the file uploads methods Django has. This means using a multipart/form-data post.
or maybe something better ?
Laurent

A: I think only files less than 2.5MB are stored in the memory, any file that is larger than 2.5MB is streamed or written to temporary file in temp directory..
reference:
http://simonwillison.net/2008/Jul/1/uploads/ and here http://docs.djangoproject.com/en/dev/topics/http/file-uploads/

A: If you really want to optimize it and don't want Django to suffer whilst the bytes are being streamed and thus occupying one of the Django threads you can use the nginx upload module
(see also this blog post)


text:
Q: How to create a common shadow for multiple strokes in a single canvas? I'm trying to draw multiple strokes on a canvas and I'd like them to have a common shadow. Currently the cast shadows on one another which is not what I want.
Ideal result

What I've tried

*

*Creating shadow using ctx.shadowColor jsfiddle

*Creating shadow using ctx.filter jsfiddle

*Creating shadow using css box-shadow on the canvas -- draws shadow on the whole box

*Creating shadow using css filter on the canvas -- draws shadow on the whole box

A: If you need each stroke to be independent (i.e so that they have each their own strokeStyle or lineWidth), you will need to use a second detached canvas:

*

*on this detached canvas you draw all your strokes without shadow

*you drawImage that detached canvas on the visible one with the shadow:

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const detached = canvas.cloneNode();
const detachedCtx = detached.getContext("2d");
const colors = ["green", "blue", "yellow", "orange", "aqua"];

detachedCtx.lineWidth = 5;
for (let color of colors) {
  // draw on the detached canvas
  detachedCtx.beginPath();
  for (let i = 0; i<5; i++) {
    detachedCtx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
  }
  detachedCtx.strokeStyle = color;
  detachedCtx.lineWidth = Math.random() * 8 + 2;
  detachedCtx.stroke();
}

// now draw all this with shadows on the visible canvas
ctx.shadowOffsetX = 3;
ctx.shadowOffsetY = 3;
ctx.shadowBlur    = 3;
ctx.shadowColor   = "red";
ctx.drawImage(detached, 0, 0);
<canvas></canvas>

But to produce the image you have all you need is to call stroke() only once after you did compose your full path:

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

ctx.fillStyle = "#0F0";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.lineWidth = 5;
ctx.shadowOffsetX = -3;
ctx.shadowOffsetY = -3;
ctx.shadowBlur    = 3;
ctx.shadowColor   = "red";
ctx.moveTo(10, 50);
ctx.lineTo(90, 50);
ctx.moveTo(50, 10);
ctx.lineTo(50, 90);
ctx.stroke(); // stroke only once, with the full path being traced
<canvas width=100 height=100></canvas>

A: You can use Path2D and add all your segments to one path, then do the stroke to that path.
Here is your jsfiddle using ctx.filter with my recommendation.

const segments = [
 [{x: 10, y: 50}, {x: 50, y: 50}],
 [{x: 50, y: 10}, {x: 50, y: 50}],
 [{x: 90, y: 50}, {x: 50, y: 50}],
 [{x: 50, y: 90}, {x: 50, y: 50}],
]

let path = new Path2D()
segments.forEach(segment => {
  path.moveTo(segment[0].x, segment[0].y)
  path.lineTo(segment[1].x, segment[1].y)
})

const ctx = document.getElementById('my-canvas').getContext('2d')
ctx.lineWidth = 5
ctx.filter = 'drop-shadow(-3px -3px 3px #f00)';
ctx.strokeStyle = 'black'
ctx.stroke(path)
<canvas width="100" height="100" id="my-canvas" style="background: #00ff00"/>

You can read more about Path2D here:
https://developer.mozilla.org/en-US/docs/Web/API/Path2D/Path2D


text:
Q: Javascript/jQuery: Read data from Active directory Is it possible to read user information from Active directory using JavaScript / jQuery ? I am trying to read the location, manager name and other details from company LDAP.
How to read data from LDAP using JavaScript / jQuery ?
Thanks


text:
Q: Excel - Sum values based on date I have a cell that includes a drop down list of months for a user to select from.
What I would like to do is use whatever month is selected in the drop down to drive sums in the workbook.
For example, in one sheet I have the the drop down list of months in C4.
In another sheet I have dates and corresponding data (starting in A1 and A2):
July  August  September  October  etc...      YTD Total
50    100     75         60       etc...      ?

So what I'm looking to achieve here is to sum the monthly figures up to the date selected in the drop down menu by the user, i.e. if September is selected in the drop down - then the YTD total will include July, August, September (NB - financial year starts in July, not Jan).
Thanks in advance people.

A: Using INDIRECT you can create the range reference for the SUM from a string.
Something like this:
=SUM(INDIRECT("R2C1:R2C"&MATCH(C4,A1:E1,0),FALSE))


text:
Q: Web.API works in some deployments but returns 404 in others I have an ASP.NET WebForms app that is widely distributed. My new version adds Web.API and users have been playing with a beta. In most beta installations everything works fine, but for some installs all the Web.API calls return HTTP 404 Not Found errors. I can't figure out why the Web.API calls fail on some servers but works fine on others.
My guess is there is some kind of server configuration that is breaking the routing, but I can't figure out what it is. I've even RDP'd into one of these sites and can't find anything obvious.
This is an example API call:
GET http://site.com/api/events/27
The code:
namespace GalleryServerPro.Web.Api
{
  public class EventsController : ApiController
  {
    public string Get(int id)
    {
      return "Event data for ID " + id;
    }
  }
}

The route definitions, which are called from the Init event of a custom HTTP module named GspHttpApplication:
private void RegisterRoutes(RouteCollection routes)
{
  routes.MapHttpRoute(
    name: "GalleryApi1",
    routeTemplate: "api/{controller}"
  );

  routes.MapHttpRoute(
    name: "GalleryApi2",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { },
    constraints: new
    {
      id = @"\d*",
    }
  );

  routes.MapHttpRoute(
    name: "GalleryApi3",
    routeTemplate: "api/{controller}/{id}/{action}",
    defaults: new
    {
    },
    constraints: new
    {
      id = @"\d*"
    }
  );

  // Add route to support things like api/meta/galleryitems/
  routes.MapHttpRoute(
    name: "GalleryApi4",
    routeTemplate: "api/{controller}/{action}",
    defaults: new
    {
    },
    constraints: new
    {
    }
  );
}

The example GET above should match the route named GalleryApi2, and like I said in most installations it does.
I know WebDAV can cause trouble (405 errors), so I already remove it in web.config:
<system.webServer>
  <modules>
    <remove name="WebDAVModule" />
    <add name="GspApp" type="GalleryServerPro.Web.HttpModule.GspHttpApplication, GalleryServerPro.Web" />
  </modules>
  <handlers>
    <remove name="WebDAV" />
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
  ...
</system.webServer>

So it all comes down to figuring out why this configuration works for some web installs and not others.
Roger


text:
Q: Get the Next/Previous record in ActiveRecord on Ruby on Rails I am trying to get the next/previous record by ActiveRecord. The records should be retrieved according to the order by 'updated_at' column.
The name of the Model is 'Youtube'. And as the following console, this code couldn't get the right record and I guess the idea of my code seems bad because updated_at is not always unique so some records might have the same time stamp.
How do you get the next/previous record in a right way?
Console said below.
[57] pry(main)> Youtube.find(1000)
  Youtube Load (0.5ms)  SELECT "youtubes".* FROM "youtubes" WHERE "youtubes"."id" = $1 ORDER BY updated_at DESC LIMIT 1  [["id", 1000]]
=> #<Youtube id: 1000, author_id: 2, category_label: nil, generated_by: 1, title: "Is Kenya Mall Shooting Over? Were Americans Among A...", video_id: "4T1szQIQcNI", created_at: "2013-09-30 18:31:21", updated_at: "2013-10-27 02:19:56", subtitles: nil>
[58] pry(main)> Youtube.find(1000).next
  Youtube Load (0.6ms)  SELECT "youtubes".* FROM "youtubes" WHERE "youtubes"."id" = $1 ORDER BY updated_at DESC LIMIT 1  [["id", 1000]]
Sun, 27 Oct 2013 02:19:56 UTC +00:00
  Youtube Load (256.6ms)  SELECT "youtubes".* FROM "youtubes" WHERE (updated_at > '2013-10-27 02:19:56.593969') ORDER BY updated_at DESC LIMIT 1
=> #<Youtube id: 67003, author_id: 75, category_label: nil, generated_by: 1, title: "Jewelry Photography : Lenses for Jewelry Photograph...", video_id: "NqA7OZL4tzw", created_at: "2013-10-09 17:18:53", updated_at: "2013-10-28 02:17:33", subtitles: nil>
[59] pry(main)> Youtube.find(1000).previous
  Youtube Load (0.6ms)  SELECT "youtubes".* FROM "youtubes" WHERE "youtubes"."id" = $1 ORDER BY updated_at DESC LIMIT 1  [["id", 1000]]
Sun, 27 Oct 2013 02:19:56 UTC +00:00
  Youtube Load (56.3ms)  SELECT "youtubes".* FROM "youtubes" WHERE (updated_at < '2013-10-27 02:19:56.593969') ORDER BY updated_at DESC LIMIT 1
=> #<Youtube id: 999, author_id: 8, category_label: nil, generated_by: 1, title: "Authors@Google: Richard Moore, Ned Boulting, and Da...", video_id: "4SCzfuJAyJw", created_at: "2013-09-30 18:31:21", updated_at: "2013-10-27 02:19:55", subtitles: nil>

Youtube has the following default_scope. Although this might be changed according to some situation, but I hope this code would be kept to keep the existing behaviour.
  default_scope order('updated_at DESC')

My trial code for Youtube Model is below.
  scope :next, lambda{|updated_at| where("updated_at > ?",
    updated_at).order("updated_at DESC")}
  scope :previous, lambda {|updated_at| where("updated_at < ?",
    updated_at).order("updated_at DESC")}

...
  def next
    self.class.next(updated_at).first
  end

  def previous
    self.class.previous(updated_at).first
  end

A: I did try and error and found below is one of the solutions.
code is here.
  def next
    self.class.unscoped.where("updated_at <= ? AND id != ?", updated_at, id).order("updated_at DESC").first
  end

  def previous
    self.class.unscoped.where("updated_at >= ? AND id != ?", updated_at, id).order("updated_at ASC").first
  end

test is here.
[210] pry(main)> Youtube.find(100)
  Youtube Load (0.8ms)  SELECT "youtubes".* FROM "youtubes" WHERE "youtubes"."id" = $1 ORDER BY updated_at DESC LIMIT 1  [["id", 100]]
=> #<Youtube id: 100, author_id: 5, category_label: nil, generated_by: 1, title: "Woman's Profane Dunkin Donuts Rant Goes Viral", video_id: "-aqN7KdWgQE", created_at: "2013-09-30 18:19:42", updated_at: "2013-10-27 00:47:37", subtitles: nil>
[211] pry(main)> Youtube.find(100).next
  Youtube Load (0.7ms)  SELECT "youtubes".* FROM "youtubes" WHERE "youtubes"."id" = $1 ORDER BY updated_at DESC LIMIT 1  [["id", 100]]
  Youtube Load (95.9ms)  SELECT "youtubes".* FROM "youtubes" WHERE (updated_at <= '2013-10-27 00:47:37.241076' AND id != 100) ORDER BY updated_at DESC LIMIT 1
=> #<Youtube id: 99, author_id: 6, category_label: nil, generated_by: 1, title: "Editing physical locations in Google Maps", video_id: "-amPC4fcY0U", created_at: "2013-09-30 18:19:42", updated_at: "2013-10-27 00:47:36", subtitles: nil>
[212] pry(main)> Youtube.find(100).next.previous
  Youtube Load (0.7ms)  SELECT "youtubes".* FROM "youtubes" WHERE "youtubes"."id" = $1 ORDER BY updated_at DESC LIMIT 1  [["id", 100]]
  Youtube Load (68.8ms)  SELECT "youtubes".* FROM "youtubes" WHERE (updated_at <= '2013-10-27 00:47:37.241076' AND id != 100) ORDER BY updated_at DESC LIMIT 1
  Youtube Load (79.5ms)  SELECT "youtubes".* FROM "youtubes" WHERE (updated_at >= '2013-10-27 00:47:36.162671' AND id != 99) ORDER BY updated_at ASC LIMIT 1
=> #<Youtube id: 100, author_id: 5, category_label: nil, generated_by: 1, title: "Woman's Profane Dunkin Donuts Rant Goes Viral", video_id: "-aqN7KdWgQE", created_at: "2013-09-30 18:19:42", updated_at: "2013-10-27 00:47:37", subtitles: nil>
[213] pry(main)> Youtube.find(100) === Youtube.find(100).next.previous
  Youtube Load (0.8ms)  SELECT "youtubes".* FROM "youtubes" WHERE "youtubes"."id" = $1 ORDER BY updated_at DESC LIMIT 1  [["id", 100]]
  Youtube Load (4.8ms)  SELECT "youtubes".* FROM "youtubes" WHERE "youtubes"."id" = $1 ORDER BY updated_at DESC LIMIT 1  [["id", 100]]
  Youtube Load (99.7ms)  SELECT "youtubes".* FROM "youtubes" WHERE (updated_at <= '2013-10-27 00:47:37.241076' AND id != 100) ORDER BY updated_at DESC LIMIT 1
  Youtube Load (79.6ms)  SELECT "youtubes".* FROM "youtubes" WHERE (updated_at >= '2013-10-27 00:47:36.162671' AND id != 99) ORDER BY updated_at ASC LIMIT 1
=> true

A: I wrote a gem that generates such queries automatically, order_query:
class YouTube < ActiveRecord::Base
  include OrderQuery
  order_query :order_display, [
    [:updated_at, :desc],
    [:id, :desc]
  ]
end

video = YouTube.find(42)
pos = video.order_display
video.next
video.after
video.position
video.prev
video.before

A: I would do it like this (might be better ways)...
scope :in_order, lambda{ order("updated_at DESC, id ASC") }

def next
  self.class.in_order.where("updated_at >= ? AND id != ?", updated_at, id).first
end

def previous
  self.class.in_order.where("updated_at <= ? AND id != ?", updated_at, id).first
end


text:
Q: ld: -bundle and -bitcode_bundle (Xcode setting ENABLE_BITCODE=YES) cannot be used together I want to build my app with Bitcode enabled. As far as I know all my 3rd party library dependencies are Bitcode enabled. But when I do a build, I get this error:
ld: -bundle and -bitcode_bundle (Xcode setting ENABLE_BITCODE=YES) cannot be used together
How do I fix this?

A: I had erroneously set my DEBUG and TEST configurations to build with Bitcode, and this was what caused the above error. Enabling Bitcode only for RELEASE fixed it:

(Your App and any embedded framework targets should look like this—don't enable Bitcode at all on your test and UI testing targets.)


text:
Q: MulitModule project dependency management I am working on the project with the project structure as
root
 lib
  xyz.jar
 modules
  module1
  module2
Now I want to include the xyz.jar in the module1 but owing to the multimodule structure of the project, I am not able to add the jar directly through maven.
I tried using
<plugin>
                <groupId>org.commonjava.maven.plugins</groupId>
                <artifactId>directory-maven-plugin</artifactId>
                <version>0.1</version>
                <executions>
                    <execution>
                        <id>directories</id>
                        <goals>
                            <goal>highest-basedir</goal>
                        </goals>
                        <phase>initialize</phase>
                        <configuration>
                            <property>multi.module.project.root.dir</property>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

and then using
<dependency>
            <groupId>org.abc.com</groupId>
            <artifactId>xyz</artifactId>
            <version>0.1.0</version>
            <scope>system</scope>
            <systemPath>${multi.module.project.root.dir}/lib/xyz.jar</systemPath>
        </dependency>

but throws error to specify absolute path of jar.
next I tried using the de
pendency management in parent pom  by specifying
<dependency>
                <groupId>org.abc.com</groupId>
                <artifactId>xyz</artifactId>
                <version>0.1.0</version>
                <scope>system</scope>
                <systemPath>${pom.basedir}/lib/xyz.jar</systemPath>
            </dependency>

This resolves the dependency but I am not able to use the dependency in the child pom of module1
How can I solve this

A: The documentation of the directory-maven-plugin you are using explicitly says about the variables produced by the plugin:

They will be useful ONLY IN PLUGIN CONFIGURATIONS, NOT DURING POM INTERPOLATION.

This means you cannot use it like what you are doing.
As an alternative, I would consider referring to this SO answer.


text:
Q: Checking if variable is nil or empty in a single line using or operator I have absolutely no experience in Ruby, but am trying to debug an issue in FPM. Sometimes, when running FPM, I get the following stack trace:
output': undefined method `empty?' for nil:NilClass (NoMethodError)

I traced this error back to this line (rpm.rb, line 419):
if @epoch.nil? or @epoch.empty?
   @logger.warn("no value for epoch is set, defaulting to nil")
   return nil
end

This blog post says the following about the or operator:

The best way to think about the chains constructed with or is as
  series of fallbacks: try this, if that fails try this, and so on

This leads me to believe that in the above code fragment, if epoch.nil? evaluates to true, it will not attempt to check epoch.empty?, but a simple codepad shows that to be wrong (http://codepad.org/qI7rLvBX)
str = nil
puts str.nil? or str.empty?

Output:
Line 2: undefined method `empty?' for nil:NilClass (NoMethodError)
true

if I change it the operator to ||, then the short-circuiting works correctly - if epoch.nil? evaluates to true, it does not attempt to evaluate epoch.empty?.
Am I misunderstanding something about the or operator? And is the way FPM is checking for nil or empty incorrect?

A: You could skip the whole problem by noting that nil.to_s is an empty string:

NilClass#to_s → ""
Always returns the empty string.

Given that, you could say:
if @epoch.to_s.empty?

This is a useful trick for avoiding a bunch of noisy nil? tests when dealing with strings.

A: It's a matter of operator precedence. || has a higher precedence than or.
You should write it like:
str = nil
puts (str.nil? or str.empty?)
puts str.nil? || str.empty?

See more in Difference between "or" and || in Ruby?
For the issue of FPM, I have tried under Ruby 1.8.6, 1.9.3, 2.0.0, and did not get error with or expression.


text:
Q: jquery, move an inner element to the first position? Lets say you have a list of items:

Every five seconds these list items get reordered.
Using jquery whats the best way to keep #topNumber, at the top of the list during the reordering.

A: You can use .prependTo() immediately after the re-order, like this:
$("#topNumber").prependTo("#ImportantNumbers");

You can see it working here, all it's doing is taking the element and inserting it as the first child on the
, effectively moving it to the top.
Alternatively when you sort, use :not() to exclude it depending on how the sorting works, for example:
$("#ImportantNumbers li:not(#topNumber)").randomize();


text:
Q: PyQt5 on Raspbian: Background color of QWidgets is not displayed I've compiled and installed PyQt5 on a Raspberry Pi 3B+ running Raspbian Buster like described here. It took a few hours, but it worked. Afterwards I uploaded my simple PyQt example program consisting of 2 files (main.py and mainwindow.ui).
The red background color set for QProgressBar and QPushButton are displayed in different shades of red (?) on my PC running Ubuntu 18.04 LTS, but on the Raspberry Pi it is not displayed at all.
Terminal output on Raspbian Buster:
libEGL warning: DRI2: failed to authenticate
qt5ct: using qt5ct plugin
qt5ct: D-Bus global menu: no

Screenshot on Ubuntu 18.04 LTS:

Screenshot on Raspbian Buster:

Why is the red background color not displayed on Raspbian Buster?
main.py
import sys
from pathlib import Path
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtGui import QColor
from PyQt5.uic import loadUi

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        ui_file = (Path(__file__).parent / "mainwindow.ui").resolve()
        loadUi(ui_file, self)
        self.progressBar.setStyleSheet(f"background-color: {QColor('red').name()}")

def main():
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

mainwindow.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>200</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <property name="locale">
   <locale language="English" country="UnitedKingdom"/>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QGridLayout" name="gridLayout_2">
    <item row="0" column="0">
     <layout class="QGridLayout" name="gridLayout">
      <item row="0" column="0">
       <widget class="QProgressBar" name="progressBar">
        <property name="value">
         <number>0</number>
        </property>
       </widget>
      </item>
      <item row="0" column="1">
       <widget class="QPushButton" name="pushButton">
        <property name="minimumSize">
         <size>
          <width>200</width>
          <height>0</height>
         </size>
        </property>
        <property name="styleSheet">
         <string notr="true">background-color: red;</string>
        </property>
        <property name="text">
         <string>Button</string>
        </property>
       </widget>
      </item>
     </layout>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>800</width>
     <height>28</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

Terminal output on Raspbian Buster after setting export QT_DEBUG_PLUGINS=1:
QFactoryLoader::QFactoryLoader() checking directory path "/usr/lib/arm-linux-gnueabihf/qt5/plugins/platforms" ...
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/platforms/libqeglfs.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/platforms/libqeglfs.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "eglfs"
        ]
    },
    "className": "QEglFSIntegrationPlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("eglfs")
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/platforms/libqlinuxfb.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/platforms/libqlinuxfb.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "linuxfb"
        ]
    },
    "className": "QLinuxFbIntegrationPlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("linuxfb")
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/platforms/libqminimal.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/platforms/libqminimal.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "minimal"
        ]
    },
    "className": "QMinimalIntegrationPlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("minimal")
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/platforms/libqminimalegl.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/platforms/libqminimalegl.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "minimalegl"
        ]
    },
    "className": "QMinimalEglIntegrationPlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("minimalegl")
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/platforms/libqoffscreen.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/platforms/libqoffscreen.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "offscreen"
        ]
    },
    "className": "QOffscreenIntegrationPlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("offscreen")
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/platforms/libqvnc.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/platforms/libqvnc.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "vnc"
        ]
    },
    "className": "QVncIntegrationPlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("vnc")
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/platforms/libqxcb.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/platforms/libqxcb.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
    "MetaData": {
        "Keys": [
            "xcb"
        ]
    },
    "className": "QXcbIntegrationPlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("xcb")
QFactoryLoader::QFactoryLoader() checking directory path "/usr/bin/platforms" ...
loaded library "/usr/lib/arm-linux-gnueabihf/qt5/plugins/platforms/libqxcb.so"
loaded library "Xcursor"
QFactoryLoader::QFactoryLoader() checking directory path "/usr/lib/arm-linux-gnueabihf/qt5/plugins/xcbglintegrations" ...
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/xcbglintegrations/libqxcb-egl-integration.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/xcbglintegrations/libqxcb-egl-integration.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.Xcb.QXcbGlIntegrationFactoryInterface.5.5",
    "MetaData": {
        "Keys": [
            "xcb_egl"
        ]
    },
    "className": "QXcbEglIntegrationPlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("xcb_egl")
QFactoryLoader::QFactoryLoader() checking directory path "/usr/bin/xcbglintegrations" ...
loaded library "/usr/lib/arm-linux-gnueabihf/qt5/plugins/xcbglintegrations/libqxcb-egl-integration.so"
libEGL warning: DRI2: failed to authenticate
QFactoryLoader::QFactoryLoader() checking directory path "/usr/lib/arm-linux-gnueabihf/qt5/plugins/platformthemes" ...
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/platformthemes/libqgtk2.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/platformthemes/libqgtk2.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformThemeFactoryInterface.5.1",
    "MetaData": {
        "Keys": [
            "gtk2"
        ]
    },
    "className": "QGtk2ThemePlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("gtk2")
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/platformthemes/libqgtk3.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/platformthemes/libqgtk3.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformThemeFactoryInterface.5.1",
    "MetaData": {
        "Keys": [
            "gtk3"
        ]
    },
    "className": "QGtk3ThemePlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("gtk3")
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/platformthemes/libqt5ct.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/platformthemes/libqt5ct.so, metadata=
{
    "IID": "org.qt-project.Qt.QPA.QPlatformThemeFactoryInterface.5.1",
    "MetaData": {
        "Keys": [
            "qt5ct"
        ]
    },
    "className": "Qt5CTPlatformThemePlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("qt5ct")
QFactoryLoader::QFactoryLoader() checking directory path "/usr/bin/platformthemes" ...
loaded library "/usr/lib/arm-linux-gnueabihf/qt5/plugins/platformthemes/libqt5ct.so"
qt5ct: using qt5ct plugin
QFactoryLoader::QFactoryLoader() checking directory path "/usr/lib/arm-linux-gnueabihf/qt5/plugins/styles" ...
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/styles/libbb10styleplugin.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/styles/libbb10styleplugin.so, metadata=
{
    "IID": "org.qt-project.Qt.QStyleFactoryInterface",
    "MetaData": {
        "Keys": [
            "bb10bright",
            "bb10dark"
        ]
    },
    "className": "QBB10StylePlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("bb10bright", "bb10dark")
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/styles/libqcleanlooksstyle.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/styles/libqcleanlooksstyle.so, metadata=
{
    "IID": "org.qt-project.Qt.QStyleFactoryInterface",
    "MetaData": {
        "Keys": [
            "cleanlooks"
        ]
    },
    "className": "QCleanlooksStylePlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("cleanlooks")
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/styles/libqgtk2style.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/styles/libqgtk2style.so, metadata=
{
    "IID": "org.qt-project.Qt.QStyleFactoryInterface",
    "MetaData": {
        "Keys": [
            "gtk2"
        ]
    },
    "className": "QGtk2StylePlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("gtk2")
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/styles/libqmotifstyle.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/styles/libqmotifstyle.so, metadata=
{
    "IID": "org.qt-project.Qt.QStyleFactoryInterface",
    "MetaData": {
        "Keys": [
            "motif",
            "cde"
        ]
    },
    "className": "QMotifStylePlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("motif", "cde")
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/styles/libqplastiquestyle.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/styles/libqplastiquestyle.so, metadata=
{
    "IID": "org.qt-project.Qt.QStyleFactoryInterface",
    "MetaData": {
        "Keys": [
            "plastique"
        ]
    },
    "className": "QPlastiqueStylePlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("plastique")
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/styles/libqt5ct-style.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/styles/libqt5ct-style.so, metadata=
{
    "IID": "org.qt-project.Qt.QStyleFactoryInterface",
    "MetaData": {
        "Keys": [
            "qt5ct-style"
        ]
    },
    "className": "Qt5CTStylePlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("qt5ct-style")
QFactoryLoader::QFactoryLoader() checking directory path "/usr/bin/styles" ...
QFactoryLoader::QFactoryLoader() checking directory path "/usr/lib/arm-linux-gnueabihf/qt5/plugins/platforminputcontexts" ...
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/platforminputcontexts/libcomposeplatforminputcontextplugin.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/platforminputcontexts/libcomposeplatforminputcontextplugin.so, metadata=
{
    "IID": "org.qt-project.Qt.QPlatformInputContextFactoryInterface.5.1",
    "MetaData": {
        "Keys": [
            "compose",
            "xim"
        ]
    },
    "className": "QComposePlatformInputContextPlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("compose", "xim")
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/platforminputcontexts/libibusplatforminputcontextplugin.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/platforminputcontexts/libibusplatforminputcontextplugin.so, metadata=
{
    "IID": "org.qt-project.Qt.QPlatformInputContextFactoryInterface.5.1",
    "MetaData": {
        "Keys": [
            "ibus"
        ]
    },
    "className": "QIbusPlatformInputContextPlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("ibus")
QFactoryLoader::QFactoryLoader() checking directory path "/usr/bin/platforminputcontexts" ...
loaded library "/usr/lib/arm-linux-gnueabihf/qt5/plugins/platforminputcontexts/libcomposeplatforminputcontextplugin.so"
loaded library "/usr/lib/arm-linux-gnueabihf/qt5/plugins/styles/libqt5ct-style.so"
loaded library "/usr/lib/arm-linux-gnueabihf/qt5/plugins/styles/libqgtk2style.so"
Cannot load library gtk-x11-2.0: (gtk-x11-2.0: Kann die Shared-Object-Datei nicht öffnen: Datei oder Verzeichnis nicht gefunden)
qt5ct: D-Bus global menu: no
QFactoryLoader::QFactoryLoader() checking directory path "/usr/lib/arm-linux-gnueabihf/qt5/plugins/iconengines" ...
QFactoryLoader::QFactoryLoader() looking at "/usr/lib/arm-linux-gnueabihf/qt5/plugins/iconengines/libqsvgicon.so"
Found metadata in lib /usr/lib/arm-linux-gnueabihf/qt5/plugins/iconengines/libqsvgicon.so, metadata=
{
    "IID": "org.qt-project.Qt.QIconEngineFactoryInterface",
    "MetaData": {
        "Keys": [
            "svg",
            "svgz",
            "svg.gz"
        ]
    },
    "className": "QSvgIconPlugin",
    "debug": false,
    "version": 330499
}

Got keys from plugin meta data ("svg", "svgz", "svg.gz")
QFactoryLoader::QFactoryLoader() checking directory path "/usr/bin/iconengines" ...
QFactoryLoader::QFactoryLoader() checking directory path "/usr/lib/arm-linux-gnueabihf/qt5/plugins/accessible" ...
QFactoryLoader::QFactoryLoader() checking directory path "/usr/bin/accessible" ...
QFactoryLoader::QFactoryLoader() checking directory path "/usr/lib/arm-linux-gnueabihf/qt5/plugins/accessiblebridge" ...
QFactoryLoader::QFactoryLoader() checking directory path "/usr/bin/accessiblebridge" ...

A: I've been fighting similar problems today (which is how I found your post).  To get rid of the libEGL warning run raspi-config and select the "Full KMS" option from Advanced Options->GL Driver (then reboot).  That likely won't fix your styling problem though - I'm seeing styling differences between the Pi (my target system) and my Linux Mint development system.

A: I have a similar problem and running it in the following way will solve it.
sudo python3.7 name.py

I guess some privilege is needed from the IDE or the current logged in user.
Although the colors are still more opaque than in Windows and Ubuntu.


text:
Q: `cout << argv[0]` returning hex value?
Possible Duplicate:
Can not print out the argv[] values using std::cout in VC++

Code:
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    cout << argv[0] << endl;
    system("PAUSE");
    return 0;
}

As you can see, a standard Win32 console application.
The confusing part is, the value of argv[0] is output as 00035B88.
This is being (AFAIK) run with no command-line options so argv[] should not have a value yet. (or is this the problem?)
However, argv[] is declared as a pointer (_TCHAR*) and I heard that cout will print the address of pointers. Is this the case? If so, how can I print/use the value of argv?

A: _TCHAR is a wide-character type if the executable was built with the Unicode option. cout can't handle wide characters, so instead of turning it into a char * and printing out a string, it (effectively) uses the default void * printer which prints out the address of the string.
Use wcout instead.

A: Hmm. The first array entry in argv (ie. argv[0]) is, if I remember right, the name of the executable. So it might be printing the address of the first character in a c style character array. Try this:
cout << (char *)argv[0] << endl;

A: In your project settings->General. Go to "Character encoding" and select "multibyte character set". And change your _tmain() to main(). Now it will print your characters.


text:
Q: How to target and rename an HTML label if it is not a sibling or parent element? I have the following piece of HTML:

            12.

                Sponsor name (5):
                 Step 12.
                Maximum input length is 255 characters.

            <input name="shared_event_propsprop_sponsor_5.field" id="shared_event_propsprop_sponsor_5.field" value="" size="60" maxlength="255">

Now this CMS for some odd reason has multiple tr with the same alternating IDs shared_event_propsrow1 and shared_event_propsrow2 and all the label elements use the same for= and class in the same table on the same page...ugh...so what I'm trying to do is target this portion:

            Sponsor name (5):
             Step 12.
            Maximum input length is 255 characters.

and rename Sponsor Name (5) to Cash and Cheques:
but the only thing I see that I can target it with is an id that lives in the tr after it                 <input name="shared_event_propsprop_sponsor_5.field" id="shared_event_propsprop_sponsor_5.field" value="" size="60" maxlength="255">
I'm struggling to find the right words to search in Google for something that can do what I'm trying to do.
Any help is greatly appreciated!
thanks

A: As heretic monkey suggested, you can target the text itself:

$(function(){
  $('label:contains(Sponsor name (5))').text('Cash and Cheques');
});

            12.

                Sponsor name (5):
                 Step 12.
                Maximum input length is 255 characters.

            <input name="shared_event_propsprop_sponsor_5.field" id="shared_event_propsprop_sponsor_5.field" value="" size="60" maxlength="255">

A: You can try something querySelectorAll like this
let elements = document.body.querySelectorAll("table tr > td > label. wrapable");


text:
Q: alter function to count vbRed I've been trying to alter the function below to count vbRed instead of any color defined by 'criteria':
Function CountCcolor(range_data As Range, criteria As Range) As Long
    Dim datax As Range
    Dim xcolor As Long
xcolor = criteria.Interior.ColorIndex
For Each datax In range_data
    If datax.Interior.ColorIndex = xcolor Then
        CountCcolor = CountCcolor + 1
    End If
Next datax
End Function

Variations such as the one below fail:
Function CountRed(range_data As Range) As Long
    Dim datax As Range

For Each datax In range_data
    If datax.DisplayFormat.Interior.Color = vbRed Then
        CountRed= CountRed+ 1
    End If
Next datax
End Function

A: For your variation to work, remove DisplayFormat.
For example (this is your code with DisplayFormat removed):
Function CountRed(range_data As Range) As Long
    Dim datax As Range
    For Each datax In range_data
        If datax.Interior.Color = vbRed Then
            CountRed = CountRed + 1
        End If
    Next datax
End Function


text:
Q: Automatically grow document view of NSScrollView using auto layout? Is there a simple way to get an NSScrollView to adapt to its document view changing size when using auto layout?
I have tried to call both setNeedsUpdateConstraints: and setNeedsLayout: on the document view, the clip view and the scroll view, without any results.
fittingSize of the document view reports the correct size.
The problem is that the document view, which holds subviews, is not re-sized when the subviews change their size, even if they call invalidateIntrinsicContentSize. The contents of the document view are hence clipped to the original size of the document view as they grow. The document view is created in a nib and set as the scroll view's document view in an awakeFromBib method.
I was hoping that the document view frame would automatically be adjusted when its fittingSize changes, and the scrollbars updated accordingly.
NSPopover does something similar - provided that the subviews of the content controller's view have the constraints set right and various content hugging values are high enough (higher than the hidden popover window's hight constraint priority, for one).

A: The problem of course is that when adding the document view, Cocoa will automatically create some hard constraints in the view that the document view is inserted into, i.e., the clip view.
So the answer to my own question is simple, just use:
// Assume self.docView is an IBOutlet populated with
// an NSView subclass
self.docView.translatesAutoresizingMaskIntoConstraints = NO;

before you add the document view to the scroll view:
self.scrollView.documentView = self.docView;

Now, since there are no auto-generated constraints on the layout of the document view in the clip view, you will need to add them explicitly. Otherwise, the doc view's contents will just be rendered at their intrinsic size in the upper left corner of the scroll view.


text:
Q: How to get NSDate with nil value I'm a beginner in Swift and coding in general. Right now I'm trying to develop the piece of the code to set up the time limit for the action only once a day.
@IBAction func yesButtonPressed(sender: AnyObject) {
    //To retrive the control date value. First time it has nil value
    var controlDate = NSUserDefaults.standardUserDefaults().objectForKey("controlDate") as? NSDate
    //To check current date to compare with
    var currentDate = NSDate()
    // To check if time interval between controlDate and currentDate is less than 1 day
    var timeInterval = controlDate?.timeIntervalSinceNow
    var dayInSeconds = 24 * 3600
    if timeInterval < dayInSeconds {

        //show alert with message "You've done it recently. Pls wait a bit"

    } else {

        //perfome the action
        //update the value of NSUserDefaults.standardUserDefaults().objectForKey("controlDate") with current time stamp
    }
}

Instead of checking if the controlTime var has nil value to catch the App first time running I was trying to develop some shorter, universal code for both case, first time and the rest times when the controlDate var will be saved in UserDefaults.
Nevertheless it doesn't work properly (( I'd appreciate your help a lot!

A: timeInterval is an Optional, you need to unwrap it first
if let ti = timeInterval {
    if ti < dayInSeconds {
        ...
    }
}

More on Optionals

A: dayInSeconds is the wrong type to make the comparison.  Type inference is determining that it should be an Int while timeIntervalSinceNow is a Double under the covers.  And thus, you can't definitively compare an Int and a Double with accuracy.
Create dayInSeconds in this way so that it's type is inferred as a Double, rather than an Int.
var controlDate = NSUserDefaults.standardUserDefaults().objectForKey("controlDate") as? NSDate
var currentDate = NSDate()
var timeInterval = controlDate?.timeIntervalSinceNow
//*** HERES THE CHANGE***
var dayInSeconds = 24.0 * 3600
if timeInterval < dayInSeconds {
}

Since you aren't attempting to call a method on timeInterval optional unwrapping is not necessary in this case.


text:
Q: Running periodic queries on google cloud sql instance I have a google cloud postgre instance and I'd like to run periodic sql queries on it and use the monitoring system to alert the user with the results.
How can I accomplish just using the gcp platform? Without having to develop a separate app.

A: As far as I am aware of, There is no Built-in feature for recurring queries in Cloud SQL at the moment.
So you have to implement your own. You can Use Cloud Scheduler to trigger a Cloud function (via HTTP/S endpoint) that runs the query on Cloud SQL and then notify the user in the way that suits your needs (I would recommend using pub/sub).
and you might want to save the result in a GCS bucket and the user is to pull the result from there.

Also, you might want to check BigQuery. It has a built-in feature of Scheduling queries.


text:
Q: HTTP requests trace Are there any tools to trace the exact HTTP requests sent by a program?
I have an application which works as a client to a website and facilitates certain tasks (particularly it's a bot which makes automatic offers in a social lending webstite, based on some predefined criteria), and I'm interested in monitoring the actual HTTP requests which it makes.
Any tutorials on the topic?

A: Some popular protocol/network sniffers are:

*

*Wireshark (previous the famous Ethereal)

*Nirsoft SmartSniff (using WinPcap)

*Nirsoft SocketSniff (allows you to watch the WinSock activity of the selected process and watch the content of each send or receive call, in Ascii mode or as Hex Dump)

*Microsoft's Network Monitor (and a list of video-tutorials here, note video 'Advanced Filtering 2 of 2' where they specifically filter on process)

Wikipedia article 'Comparison of packet analyzers' has a nice overview of some other tools to.
Alternatively you could also look into (man-in-the-middle) proxy tools like:

*

*Fiddler

*mitmproxy
Both of the above actually record/decrypt/modify/replay HTTPS to!! You'd need to point the application you are monitoring to this proxy. If nothing else uses that proxy the log would be application/process specific and another upside to this approach is that one could also run the monitor/logger on a different machine.
Once you choose a tool, you can easily google a tutorial to go along with it.
However the core idea is usually the same: basically one sets a filter (on capture itself or display of captured data) on things like protocol, network/mac address, portno, etc. Depending on the tool, some can also filter on local application.
Hope this helps!

A: Take a look at HTTP Toolkit (disclaimer: it's my project).
Totally automatic HTTP & HTTPS interception, with zero setup, isolated to just the code you want to debug.
You can open a browser with it, and see all the traffic from that one window immediately (but no others), or run a terminal and automatically see all traffic only from processes started from that terminal. Built-in HTTPS decryption for everything, with no risky system-wide certificates and no manual setup. Let me know what you think!