text:
Q: How can I make 3 circles with a different radius "stick" together? (with example image) I have a graph that is represented by three different sized circles, based on the presence of a given element in the result set. The first circle is always set to 100%, being this is the largest the circle can be, the other two are relative % to the largest one.
The problem is that I am trying to use css to render them and I do not know the math necessary to figure out how to make them all "stick" together along their sides.
The known pieces will be the radius of each circle, and the largest one is always returned first.
Here is an example of what I'm trying to accomplish:

How can I accomplish this mathematically such that i can supply each circle with a margin-top and margin-left that will position them in this way?
I can position the largest circle at 0,0, and the second largest at half the difference between the 2 diameters, making the center points line up. The real challenge is the third smallest circle, in knowing where to position it based on the other two circles' positions.

A: Build triangle with sides radius0, radius1 and radius2 and calculate the third vertex coordinate (smallest circle center).
I've used formula (23) from here in my calculation. There is Delphi code, but I hope the principle is clear.
var
  r0, r1, r2: Integer;
  x0, x1, x2, y0, y1, y2: Integer;
  a, b, c, ca: Double;
begin
  //some intialization
  Canvas.FillRect(ClientRect);
  Randomize;
  r0 := 200;
  r1 := Round(r0 * (0.25 + 0.75 * Random));
  r2 := Round(r1 * (0.25 + 0.75 * Random));

  //circle centers' coordinates
  //biggest
  x0 := r0;
  y0 := r0;

  //second
  x1 := x0 + r0 + r1;
  y1 := y0;

  //triangle sides
  c := r0 + r1;
  b := r0 + r2;
  a := r1 + r2;

  //x-shift
  ca := (c * c + b * b - a * a) / (2.0 * c);
  x2 := x0 + Round(ca);

  //y-shift is the height of triangle
  //Pythagor's rule
  y2 := y0 + Round(Sqrt(b * b - ca * ca));

  //draw calculated circles
  Canvas.Ellipse(x0 - r0, y0 - r0, x0 + r0 + 1, y0 + r0 + 1);
  Canvas.Ellipse(x1 - r1, y1 - r1, x1 + r1 + 1, y1 + r1 + 1);
  Canvas.Ellipse(x2 - r2, y2 - r2, x2 + r2 + 1, y2 + r2 + 1);

example output:

A: Ok, lets go through each one... lets assume your 100% A circle has radius x (so B be would be Bx and c might be Cx, B = .7 and C = .3 as an example).
As another aside I would actually have a

 and then your circles would be

 instead of using margin-top/margin-left
ANYWAYS. Obviously will have top/left = 0.
From your picture it looks like the centers of A and B line up... This would mean B would have left = 2x and top = (1 - B)x
C is the hard part... I'll just put up a quick paint triangle up for reference

First lets use the Law of Cosines to find the angle at A
(B + C)² = (1 + B)² + (1 + C)² - 2(1 + B)(1 + C)cos A

cosA = (BC - B - C - 1)/(BC + B + C + 1)

Using normal Trigonometry we can also get the height...
sin A = h / (1 + C)

Using the rule
sin² A + cos² A = 1

We can combine and get
h = (1 + C) √ (1 - cos² A)

Of course to get the top we need to add 1 and minus C
top = ((1 + C) √ (1 - cos² A) + 1 - C)x

Using trig again we can get the left side...
cos A = l / (1 + C)

l = (1 + C)cos A

Of course to get left we have to add 1 and take C...
left = ((1 + C)cos A + 1 - C)x

I have created an example using border-radius to create the circles with B = .7 and C = .3 and x = 50px: http://jsfiddle.net/FelixJorkowski/xArpR/

A: Here is my python implementation of @MBo 's code
r0 = 100
r1 = 50
r2 = 25

#circles
#biggest
x0 = r0
y0 = r0

#2nd
x1 = x0 + r0 + r1
y1 = y0

#sides
c = r0 + r1
b = r0 + r2
a = r1 + r2

#x-shift
ca = (c * c + b * b - a * a) / (2.0 * c)
x2 = x0 + round(ca)

#y-shift is the height of triangle
y2 = y0 + round(math.sqrt(b * b - ca * ca))

left_a = x0 - r0
top_a = y0 - r0
width_a = r0 * 2
border_radius_a = width_a / 2

left_b = x1 - r1
top_b = y1 - r1
width_b = r1 * 2
border_radius_b = width_b / 2

left_c = x2 - r2
top_c = y2 - r2
width_c = r2 * 2
border_radius_c = width_c / 2

A: A solution using a Canvas element in case other's stumble on this.
http://jsfiddle.net/5mgLY/
var centerpoint = 50;
var radius = randomFromInterval(30, 50);                //starting circle between 30 and 50
var radius2 = radius * randomFromInterval(5, 9) / 10;   //between .5 and .9 of starting circle
var radius3 = radius2 * randomFromInterval(3, 8) / 10;  //between .3 and .8 of medium circle

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

//draw the big circle
ctx.beginPath();
ctx.arc(centerpoint,centerpoint,radius,0,2*Math.PI,false);
ctx.fillStyle = 'green';
ctx.fill();
ctx.stroke();

//draw the medium circle
ctx.beginPath();
ctx.arc(centerpoint + radius + radius2,50,radius2,0,2*Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
ctx.stroke();

//find the length of each side of the triangle that forms between the three circles
var hypotenuse = radius + radius2;
var side1 = radius + radius3;
var side2 = radius2 + radius3;

//get x and y offsets
var xOffset = ((hypotenuse*hypotenuse) + (side1*side1)  - (side2*side2)) / (2 * hypotenuse);
var yOffset = Math.sqrt(side1 * side1 - xOffset * xOffset);

//draw the small circle
ctx.beginPath();
ctx.arc(centerpoint + xOffset,centerpoint + yOffset,radius3,0,2*Math.PI);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.stroke();

function randomFromInterval(from,to)
{
    return Math.floor(Math.random()*(to-from+1)+from);
}

function toDegrees (angle) {
  return angle * (180 / Math.PI);
}


text:
Q: ASP.NET - displaying business layer errors in the presentation layer Currently in the ASP.NET application I'm developing, basic validations (ie required fields) are being done in the Presentation Layer, using Validators and a ValidationSummary.  This is working great for me specifically since the ValidationSummary will display multiple error messages (assuming multiple Validators are set to invalid).
I also have some validations being done in the business layer - due to their complexity (and data service layer reliance) I'd rather not keep them in the presentation layer.  However, I'm not sure the best way to send these back to the presentation layer for display to the user.  My initial consideration is to send back a List<string> with failed validation messages and then dynamically create a CustomValidator control (since apparently you can only bind one error message to one Validator control) for each error to show in the ValidationSummary when there are any.
I'm assuming I'm not the first one to come across this issue, so I'm wondering if anyone has any suggestions on this.
Thanks!

A: There are essentially two ways to do this: either by passing back an error code/object from your business layer, or throw out an exception. You can also combine both.
For an example, you can take a look SqlException class. When you send a SQL to SQL Server, it runs a query parser to parse your SQL first. If it sees syntax error, then it will throw out a SqlException and terminate the query. There may be multiple syntax errors in your query. So SqlExeption class has an Errors property that contains a list of errors. You can then enumerate through that list in your presentation layer to format your error message, probably with a CustomValidator.
You can also simply just return the error list without throwing an exception. For example, you can have your function to return a List in case at least one error occurred and return null in case the call was successful. Or you can pass List as an argument into your function. They are all fine, it all depends on which way you feel is more convenient. The advantage of throwing out an exception is it unwinds multiple call frames immediately, so you don't have to check return value on every level. For example, if function A calls function B , B calls function C, C sees something wrong, then if let C to return an error object (or error code), then B has to have code to check whether C returned an error and pass that error code/value back, A have to check it as well ---- you need to check it on every level. On the other hand, if you just let C to throw an exception, then the code goes straight to the exception handler. You don't have check return values on every level.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot launch AVD in emulator.Android studio 2.1.2 OUTPUT-
    Cannot launch AVD in emulator.
    Output:
    emulator: WARNING: Crash service did not start
    emulator: ERROR: Could not create C:\Users\Mahe\.android\avd\Nexus_S_API_22_2.avd/userdata-qemu.img: No such file or directory

I am a beginner in android and this error popped up when I first started the emulator.


text:
Q: Oracle Hierarchical Query Get all Childrens All Level I have a table in which I have columns DataID and ParentID , so for one parent root I can have childrens and those childrens can have more childrens and so on
Structure something like this
Root
 Child1
    A
    B
 Child2
    C
    D

Can I use a hierarchical query to gather root and all its children no matter how deep the level is

A: You seem to be asking for a very simple hierarchical query, as described in the documentation, show in its examples, and many other places.
If you want the output you showed in the question, then you could do something like:
select lpad(' ', level - 1, ' ') || dataid as hierarchy
from your_table
start with parentid is null
connect by prior dataid = parentid;

HIERARCHY
--------------------------------------------------------------------------------
Root
 Child1
  A
  B
 Child2
  C
  D

The lpad used the query level to indent the values by an appropriate number of spaces.


text:
Q: Путь для установки Download manager Как мне указать путь для директории, в которую будет установлен файл через Download Manager?

A: Покопавшись в интернете, нашёл ответ на свой вопрос
Нужный метод: request.setDestinationInExternalPublicDir(directory, filename);
Пример:
 Request request = new Request(Uri.parse(URL_ADDRESS));
        request.setAllowedNetworkTypes(3);
        request.setTitle((CharSequence)"Download");
        request.setDescription((CharSequence)"The file is downloading..");
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(1);
//File is saving to "Download"
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
FILE_NAME+FILE_EXTENSION);


text:
Q: Sending value from jQuery autocomplete back to PHP I got a bit stuck and would appreciate any help.
Intro
In short (I hope): I am creating a website (only local at the moment) which has stored city names and some important/interesting values (for example population, time, currency). I use a MySQL database to store the data. Three of these tables relevant to this case: Table 1. stores cities as values. table 2. stores the "title" of the relevant data (population, current time, currency). The third table the actual value (100 000, 12:30, Euro). I am using php to communicate between the database and the html.
Desired outcome:
A search box is used to find a city of interest. The web page prints the selected city in the top of the page and some relevant data of the city inside two divs.
Problem
How can I get the value of autocomplete back to php in order to make three different SQL queries on the same page depending on the selection?
I read that you could use a php -file as the source of the autocomplete (now on an array, values stored from the database) and somehow autocomplete could retrieve other data based on the users' selection. But will it work if I am not using any other jquery-ui component? How would it actually be written in code?
EDIT
I read shortly about:

*

*Sending it as POST, but can it be done in the same page?

*Use sessions

*Use AJAX

What is the easiest/best to understand/use?
Any other suggestions?/help?/tips?
At this point my stack has overflown.
Summary
What is a easy to learn and correct way to handle communication from javascript/jQuery back to PHP while staying on the same page?
Code
<?php
require_once "dataPDO.php"; //All of the sql-queries
$databaseHandler = new dataPDO();
$list=$databaseHandler->allCities(); //a list of all the cities
?>
<!doctype html>

        <title>Choose a city</title>
    <meta charset="utf-8">

    <link rel="stylesheet" href="js/jquery.ui.all.css">

            Search for a city:
            <input id="cities">

            <?php
                try {
                    $databaseHandler->information(1);//(hardcoded) information belonging to the first city
                }
                catch(PDOException $e)
                {
                    echo $e->getMessage();
                }
            ?>

            <?php
                try {
                    $databaseHandler->values(1);//(hardcoded) information values belonging to the first city
                }
                catch(PDOException $e)
                    {
                    echo $e->getMessage();
                    }
            ?>

A: You certainly do not need to use JQuery or another framework, however, it sure does make it a lot easier to do these types of things.  RyanS' comment about using JQuery makes a lot of sense for this reason.  You'd just be reinventing the wheel.
Basically, the process will be to make a PHP file that takes some parameters through GET or POST and then uses those parameters to display the data.  Once you have that file in place, you can use Javascript to trigger an event to call that PHP script.  For instance, you can say when someone selects a value from a drop down menu, then pass these parameters to the PHP script and display the output from there into a div that you have on the same page as the drop down menu.


text:
Q: kafka-connect file-pulse connector standalone could not start(class not found exception on offset manager) I want to use filepulse connector to load xml files to kafka.
below are my environment:

*

*Win10 WSL, installed Ubuntu

*downloaded the confluent platform 5.5.1 (see "https://www.confluent.io/download/"), unpacked

*downloaded zip file version 1.5.2 from github (https://github.com/streamthoughts/kafka-connect-file-pulse/releases), unzipped

*modified the "connect-standalone.properties" located under confluent path (etc/kafka/connect-standalone.properties) to include path "/home/min/streamthoughts-kafka-connect-file-pulse-1.5.2/lib"

*I did not create any topic.

I started zookeeper; kafka, and tried to start kafka-connect standalone like below:
$ zookeeper-server-start etc/kafka/zookeeper.properties
$ kafka-server-start etc/kafka/server.properties
$ connect-standalone \
etc/kafka/connect-standalone.properties \
/home/min/streamthoughts-kafka-connect-file-pulse-1.5.2/etc/quickstart-connect-file-pulse-csv.properties

but I have failures see below
[2020-09-08 15:57:45,522] INFO Loading plugin from: /home/min/streamthoughts-kafka-connect-file-pulse-1.5.2/lib/kafka-connect-file-pulse-expression-1.5.2.jar (org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader:239)
[2020-09-08 15:57:45,541] INFO Registered loader: PluginClassLoader{pluginLocation=file:/home/min/streamthoughts-kafka-connect-file-pulse-1.5.2/lib/kafka-connect-file-pulse-expression-1.5.2.jar} (org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader:262)
[2020-09-08 15:57:45,541] INFO Loading plugin from: /home/min/streamthoughts-kafka-connect-file-pulse-1.5.2/lib/kafka-connect-file-pulse-filters-1.5.2.jar (org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader:239)
[2020-09-08 15:57:45,553] INFO Registered loader: PluginClassLoader{pluginLocation=file:/home/min/streamthoughts-kafka-connect-file-pulse-1.5.2/lib/kafka-connect-file-pulse-filters-1.5.2.jar} (org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader:262)
[2020-09-08 15:57:45,554] INFO Loading plugin from: /home/min/streamthoughts-kafka-connect-file-pulse-1.5.2/lib/kafka-connect-file-pulse-plugin-1.5.2.jar (org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader:239)
[2020-09-08 15:57:45,575] ERROR Stopping due to error (org.apache.kafka.connect.cli.ConnectStandalone:130)
java.lang.NoClassDefFoundError: io/streamthoughts/kafka/connect/filepulse/offset/OffsetManager
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
    at java.lang.Class.getConstructor0(Class.java:3075)
    at java.lang.Class.newInstance(Class.java:412)
    at org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader.versionFor(DelegatingClassLoader.java:385)
    at org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader.getPluginDesc(DelegatingClassLoader.java:355)
    at org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader.scanPluginPath(DelegatingClassLoader.java:328)
    at org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader.scanUrlsAndAddPlugins(DelegatingClassLoader.java:261)
    at org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader.registerPlugin(DelegatingClassLoader.java:253)
    at org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader.initPluginLoader(DelegatingClassLoader.java:222)
    at org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader.initLoaders(DelegatingClassLoader.java:199)
    at org.apache.kafka.connect.runtime.isolation.Plugins.<init>(Plugins.java:60)
    at org.apache.kafka.connect.cli.ConnectStandalone.main(ConnectStandalone.java:79)
Caused by: java.lang.ClassNotFoundException: io.streamthoughts.kafka.connect.filepulse.offset.OffsetManager
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at org.apache.kafka.connect.runtime.isolation.PluginClassLoader.loadClass(PluginClassLoader.java:104)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    ... 13 more

question
Can you please help what could be the fix?
ps. below is what I tried for jdbc connector, just to see whether other connectors are working or not. It did not have exceptions.
connect-standalone \
etc/kafka/connect-standalone.properties \
/home/min/confluent-5.5.1/etc/kafka-connect-jdbc/sink-quickstart-sqlite.properties

pps. below is the content of file-pulse connector (I did not make changes)
connector.class=io.streamthoughts.kafka.connect.filepulse.source.FilePulseSourceConnector
topic=connect-file-pulse-quickstart-csv
tasks.max=1

filters=ParseDelimitedRow

# Delimited Row filter
filters.ParseDelimitedRow.extractColumnName=headers
filters.ParseDelimitedRow.trimColumn=true
filters.ParseDelimitedRow.type=io.streamthoughts.kafka.connect.filepulse.filter.DelimitedRowFilter
skip.headers=1
task.reader.class=io.streamthoughts.kafka.connect.filepulse.reader.RowFileInputReader

# File scanning
fs.cleanup.policy.class=io.streamthoughts.kafka.connect.filepulse.clean.LogCleanupPolicy
fs.scanner.class=io.streamthoughts.kafka.connect.filepulse.scanner.local.LocalFSDirectoryWalker
fs.scan.directory.path=/tmp/kafka-connect/examples/
fs.scan.interval.ms=10000

# Internal Reporting
internal.kafka.reporter.bootstrap.servers=localhost:9092
internal.kafka.reporter.id=connect-file-pulse-quickstart-csv
internal.kafka.reporter.topic=connect-file-pulse-status

# Track file by name and hash
offset.strategy=name+hash

ppps. below are the key info for the connect-standalone.properties file (I added the /home/min/streamthoughts-kafka-connect-file-pulse-1.5.2/lib)

# Set to a list of filesystem paths separated by commas (,) to enable class loading isolation for plugins
# (connectors, converters, transformations). The list should consist of top level directories that include
# any combination of:
# a) directories immediately containing jars with plugins and their dependencies
# b) uber-jars with plugins and their dependencies
# c) directories immediately containing the package directory structure of classes of plugins and their dependencies
# Note: symlinks will be followed to discover dependencies or plugins.
# Examples:
# plugin.path=/usr/local/share/java,/usr/local/share/kafka/plugins,/opt/connectors,

plugin.path=/usr/share/java,/home/min/streamthoughts-kafka-connect-file-pulse-1.5.2/lib
# plugin.path=/usr/share/java,/home/min/confluent-5.5.1/share/java/kafka-connect-jdbc

A: I would not call this one a perfect answer, but it is just the way I made it working.
I found the plugin.path property for the 'file-pulse' connector has to be the parent folder of the jar files.
so below worked.
$ cat etc/kafka/connect-standalone.properties

key info extracted:
plugin.path=/user/share/java,/home/min/streamthoughts-kafka-connect-file-pulse-1.5.2
# plugin.path=/usr/share/java,/home/min/confluent-5.5.1/share/java/kafka-connect-jdbc

before it was like below, and throw exception as I mentioned.
plugin.path=/user/share/java,/home/min/streamthoughts-kafka-connect-file-pulse-1.5.2/lib
# plugin.path=/usr/share/java,/home/min/confluent-5.5.1/share/java/kafka-connect-jdbc

maybe I did not understand below instructions in the connect-standalone.properties property file, or maybe the file-pulse connectors did not follow the standards/instructions stated here. certainly, the JDBC connectors the path is the path containing the JAR files.
# a) directories immediately containing jars with plugins and their dependencies
# b) uber-jars with plugins and their dependencies
# c) directories immediately containing the package directory structure of classes of plugins and their dependencies


text:
Q: Parsing HTML page into CSV - python I am trying to transfer all the data i parsed from a website into a csv file but i have run into a couple of problems:
1.Even though i have added the character encoding, it still prints out as HTML in excel rather than plain text:
e.g
<option redirectvalue="/partfinder/Asus/All In One/E Series/ET10B">ET10B</option>

2.It prints out in one column rather than rows for them all
Here is my code so far:
import string, urllib2, urlparse, csv, sys, codecs, cStringIO
from urllib import quote
from urlparse import urljoin
from bs4 import BeautifulSoup
from ast import literal_eval

class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([s.encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

changable_url = 'http://www.asusparts.eu/partfinder/Asus/All%20In%20One/E%20Series'
page = urllib2.urlopen(changable_url)
base_url = 'http://www.asusparts.eu'
soup = BeautifulSoup(page)

selects = []
redirects = []
model_info = []

#Opening csv writer
c = UnicodeWriter(open(r"asus_stock.csv", "wb"))
#Object reader
cr = UnicodeWriter(open(r"asus_stock.csv", "rb"))

print "FETCHING OPTIONS"
select = soup.find(id='myselectListModel')
selects.append(select)

for item in selects:
    print item.get_text()

options = select.findAll('option')

for option in options:
    if(option.has_attr('redirectvalue')):
       redirects.append(option['redirectvalue'])

for r in redirects:
    rpage = urllib2.urlopen(urljoin(base_url, quote(r)))
    s = BeautifulSoup(rpage)
    #print s

    #Fetching the main title for each specific model and printing it out
    print "FETCHING MAIN TITLE"
    maintitle = s.find(id='puffBreadCrumbs')
    model_info.append(maintitle)
    print maintitle.get_text()

    datas = s.find(id='accordion')

    a = datas.findAll('a')

    content = datas.findAll('span')

    print "FETCHING CATEGORY"
    for data in a:

        if(data.has_attr('onclick')):
            arguments = literal_eval('(' + data['onclick'].replace(', this', '').split('(', 1)[1])
            #model_info.append(arguments)
            print arguments #arguments[1] + " " + arguments[3] + " " + arguments[4]

    # Retrieves Part number and Price
    print "FETCHING DATA"
    for complete in content:

        if(complete.has_attr('class')):
            #model_info.append(complete['class'])

            print complete.get_text()

    print "FETCHING IMAGES"
    img = s.find('td')

    images = img.findAll('img')
    model_info.append(images)
    print images

c.writerows(selects)

How can i make it so it prints out as

1-Text rather than HTML
2-Rows rather than one column

[EDIT]
This is how i would like the CSV file to be displayed and example of values to be returned
"Brand Name"  "CategoryID"  "ModelID"    "Family"            "Name"                  "Part Number"  "Price"  "Image src"
    Asus    |   AC Adapter  |  ET1602  |  E Series | Power Cord 3P L:80CM,UK(B) |    14G110008350   |14.77  |  image src

[NEW EDIT]
These are the outputs for the printed values:
print "FETCHING OPTIONS"
select = soup.find(id='myselectListModel')
selects.append(select)

for item in selects:
    print item.get_text()

yields:
ET10B ET1602 ET1602C etc..

Fetching Main Title:
print "FETCHING MAIN TITLE"
maintitle = s.find(id='puffBreadCrumbs')
model_info.append(maintitle)
print maintitle.get_text()

yields:

Asus - All In One - E Series - ET10B

Fetching Category
datas = s.find(id='accordion')

a = datas.findAll('a')

content = datas.findAll('span')

print "FETCHING CATEGORY"
for data in a:

    if(data.has_attr('onclick')):
        arguments = literal_eval('(' + data['onclick'].replace(', this', '').split('(', 1)[1])
        #model_info.append(arguments)
        print arguments

yields:
FETCHING CATEGORY
('Asus', 'AC Adapter', 'ET10B', '6941', 'E Series')
('Asus', '04G265003580')
('Asus', '14G110008340')
('Asus', 'Bracket', 'ET10B', '7138', 'E Series')
('Asus', 'Cable', 'ET10B', '6983', 'E Series')
('Asus', 'Camera', 'ET10B', '6985', 'E Series')
('Asus', 'Cooling', 'ET10B', '6999', 'E Series')
('Asus', 'Cover', 'ET10B', '6984', 'E Series')
etc..

Fetching the Name:
print "FETCHING NAME"
name = s.find('b').get_text()
print name

yields:

POWER ADAPTER 65W19V 3PIN

Fetching Part Number and Price
print "FETCHING PART NUMBER AND PRICE (inc. VAT)"
for complete in content:

   if(complete.has_attr('class')):
        #model_info.append(complete['class'])
        print complete.get_text()

yields:
FETCHING PART NUMBER AND PRICE (inc. VAT)
Part number: 04G265003580

Remote stock
38.09:- EUR

Fetching the images
print "FETCHING IMAGES"
img = s.find('td')

images = img.findAll('img')
model_info.append(images)
print images

yields:
FETCHING IMAGES
[<img alt="" src="/images/Articles/thumbs/04G265003580_thumb.jpg"/>]

A: You need to process the selects list further; rather than write the whole list to the CSV file, write just the option tags to the CSV file:
for select in selects:
    c.writerow([opt.string for opt in select.find_all('option')])


text:
Q: Sync vs Async Queue in iOS I have some idea about JS and was going through iOS
I was reading this blog and am confused about async and sync in Swift (although I have a feeling that it's same in IOS and Javascript) but anyway
import UIKit

func smile () {
    print('1')
}

func love() {
    print('2')
}

//Serial Queue

let queue = DispatchQueue(label: 'SerialQueue')

queue.async {
    for _ in 1...5 {
     smile()
  }
}

 queue.async {
    for _ in 1...5 {
     love()
   }
 }

This would log something like this
1
1
1
1
1
2
2
2
2
2

Thinking about the example, If it was a sync instead of async then the output would've been the same? so what's the use of using async above?
Also, In JS we need to await. In swift we don't have to do anything?  Can someone explain it to me by giving example of async and await in swift?

A: Since you're using the same queue for both works, the second async block won't start executing until the first block ends. It doesn't matter if it's asynchronous or serial.
You'll see the true difference between .async and .sync if you add a print statement between both queues. Like this:
queue.async {
    for _ in 1...100 {
          self.smile()
    }
}
print("Finished printing smiles")
queue.async {
    for _ in 1...100 {
          self.love()
    }
}

The previous code will probably print "Finished printing smiles" even before it has started printing smiles! That's because async work returns instantly and keeps executing code.

And let's see what happens if you change the queues with synchronous queues:
queue.sync {
    for _ in 1...100 {
          self.smile()
    }
}
print("Finished printing smiles")
queue.sync {
    for _ in 1...100 {
          self.love()
    }
}

Yup. Now the sync queue waits before the closure completes before carrying on. So, you'll get 100 smiles, and then the "Finished printing smiles".

If you want to achieve concurrency, that's it, two blocks of code executing simultaneously (but not at exactly the same time, because that would be parallelism), you'll have to use two different queues, or specify the .concurrent parameter in the queue configuration:
override func viewDidLoad() {

    let queue = DispatchQueue(label: "SerialQueue")
    let queue2 = DispatchQueue(label: "AnotherQueue")

    queue.async {
        for _ in 1...100 {
              self.smile()
        }
    }
    print("Finished printing smiles")
    queue2.async {
        for _ in 1...100 {
              self.love()
        }
    }
}

As you'll see, the order here is chaotic and will vary between executions. That's because both queues are running at the same time.
Another equivalent to this code would be:
let queue = DispatchQueue(label: "ConcurrentQueue", attributes: .concurrent)

queue.async {
    for _ in 1...100 {
          self.smile()
    }
}
print("Finished printing smiles")
queue.async {
    for _ in 1...100 {
          self.love()
    }
}

A: @loufranco and @Roberto has answered in detailed way.
You can also achieve this on a single OperationQueue adding different BlockOperation on it.
As if you will see in this scenario:
let queue = OperationQueue()

let operation1 = BlockOperation {
    for _ in 1...5 {
     smile()
  }
}
print("Done")
let operation2 = BlockOperation {
    for _ in 1...5 {
     love()
   }
 }

queue.addOperation (operation1)
queue.addOperation (operation2)

The output is :

And if you will add operation2 dependency on operation1:
operation2.addDependency(operation1)
queue.addOperation (operation1)
queue.addOperation (operation1)

The Output is :

A: When you use sync, it executes in the queue's thread, but sync doesn't return until it is done. async returns immediately.
Because you have a serial queue, the prints are the same, but the calling function can return before the queue has done the printing. If it were sync, the calling function would be waiting for the prints to finish.
There is no async/await concept in Swift yet. That is not what is happening here (or in the sync case)
If you want to see the difference, put sleeps in the blocks and prints outside the queue calls.


text:
Q: autofit column width to contents in word automation Using Microsoft Interop for word, after adding a table to the document, how can the column width be set for all columns so that it fits the largest item there? For example, if the column header is only two letters, and each cell underneath is only one digit, the column should only be about a centimeter wide.

A: If you only have one table in your document, you would use something like this (where oDoc is your active document.)
oDoc.Tables(0).AllowAutoFit = True;
oDoc.Tables(0).AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitContent);

If you have more than one table, you'd want to choose the index of the one you wish to update or loop through them.

A: In the Word object model AutoFit is what the feature is called that allows (or doesn't allow) table columns to resize to fit the content, the width of the window/page or prevents them from resizing automatically.
To force the table columns to resize to fit their content:
tbl.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitContent);

To change the width of a single column to fit to the content:
tbl.Columns[index].AutoFit();

This can also be done for all columns:
tlb.Columns.AutoFit();


text:
Q: Link in answer editor appears correctly in preview, but not in the answer Note: I know about the other bug marked duplicate, but this one is different.
I was about to edit an answer to fix url syntax, but noticed that it was correct. Preview thinks it is correct, but there's no ref in the answer. The answer I was going to edit is
https://stackoverflow.com/a/4262450/1045994

A: That's because this answer was posted before I made this change, and so its HTML was still created under the old rules, where a URL directly following an opening parenthesis would not be auto-linked. I have made a non-edit to the answer (just added a newline) to force re-rendering the answer with the new rules, and now the URLs are links.


text:
Q: GHC doesn't pick the only available instance I'm trying to write a CSS DSL in Haskell, and keep the syntax as close to CSS as possible. One difficulty is that certain terms can appear both as a property and value. For example flex: you can have "display: flex" and "flex: 1" in CSS.
I've let myself inspire by the Lucid API, which overrides functions based on the function arguments to generate either attributes or DOM nodes (which sometimes also share names, eg <style> and <div style="...">).
Anyway, I've ran into a problem that GHC fails to typecheck the code (Ambiguous type variable), in a place where it is supposed to pick one of the two available typeclass instances. There is only one instance which fits (and indeed, in the type error GHC prints "These potential instance exist:" and then it lists just one). I'm confused that given the choice of a single instance, GHC refuses to use it. Of course, if I add explicit type annotations then the code compiles. Full example below (only dependency is mtl, for Writer).
{-# LANGUAGE FlexibleInstances #-}
module Style where

import Control.Monad.Writer.Lazy

type StyleM = Writer [(String, String)]
newtype Style = Style { runStyle :: StyleM () }

class Term a where
    term :: String -> a

instance Term String where
    term = id

instance Term (String -> StyleM ()) where
    term property value = tell [(property, value)]

display :: String -> StyleM ()
display = term "display"

flex :: Term a => a
flex = term "flex"

someStyle :: Style
someStyle = Style $ do
    flex "1"     -- [1] :: StyleM ()
    display flex -- [2]

And the error:
Style.hs:29:5: error:
    • Ambiguous type variable 'a0' arising from a use of 'flex'
      prevents the constraint '(Term
                                  ([Char]
                                   -> WriterT
                                        [(String, String)]
                                        Data.Functor.Identity.Identity
                                        a0))' from being solved.
        (maybe you haven't applied a function to enough arguments?)
      Probable fix: use a type annotation to specify what 'a0' should be.
      These potential instance exist:
        one instance involving out-of-scope types
          instance Term (String -> StyleM ()) -- Defined at Style.hs:17:10
    • In a stmt of a 'do' block: flex "1"
      In the second argument of '($)', namely
        'do { flex "1";
              display flex }'
      In the expression:
        Style
        $ do { flex "1";
               display flex }
Failed, modules loaded: none.

I've found two ways how to make this code compile, none of which I'm happy with.

*

*Add explicit annotation where the flex function is used ([1]).

*Move the line where flex is used to the end of the do block (eg. comment out [2]).

One difference between my API and Lucid is that the Lucid terms always take one argument, and Lucid uses fundeps, which presumably gives the GHC typechecker more information to work with (to choose the correct typeclass instance). But in my case the terms don't always have an argument (when they appear as the value).

A:
There is only one instance which fits (and indeed, in the type error GHC prints "These potential instance exist:" and then it lists just one). I'm confused that given the choice of a single instance, GHC refuses to use it.

Type classes are open; any module could define new instances. So GHC never assumes that it knows about all instances, when checking a use of a type class. (With the possible exception of the bad extensions like OverlappingInstances.) Logically, then, the only possible answers to a question "is there an instance for C T" are "yes" and "I don't know". To answer "no" risks incoherence with another part of your program that does define an instance C T.
So, you should not imagine the compiler iterating over every declared instance and seeing whether it fits at the particular use site of interest, because what would it do with all the "I don't know"s? Instead, the process works like this: infer the most general type that could be used at the particular use site and query the instance store for the needed instance. The query can return a more general instance than the one needed, but it can never return a more specific instance, since it would have to choose which more specific instance to return; then your program is ambiguous.
One way to think about the difference is that iterating over all declared instances for C would take linear time in the number of instances, while querying the instance store for a specific instance only has to examine a constant number of potential instances. For example, if I want to type check
Left True == Left False
I need an instance for Eq (Either Bool t), which can only be satisfied by one of
instance Eq (Either Bool t)
instance Eq (Either a t)    -- *
instance Eq (f Bool t)
instance Eq (f a t)
instance Eq (g t)
instance Eq b

(The instance marked * is the one that actually exists, and in standard Haskell (without FlexibleInstances) it's the only one of these instances that is legal to declare; the traditional restriction to instances of the form C (T var1 ... varN) makes this step easy since there will always be exactly one potential instance.)
If instances are stored in something like a hash table then this query can be done in constant time regardless of the number of declared instances of Eq (which is probably a pretty large number).
In this step, only instance heads (the stuff to the right of the =>) are examined. Along with a "yes" answer, the instance store can return new constraints on type variables that come from the context of the instance (the stuff to the left of the =>). These constraints then need to be solved in the same manner. (This is why instances are considered to overlap if they have overlapping heads, even if their contexts look mutually exclusive, and why instance Foo a => Bar a is almost never a good idea.)
In your case, since a value of any type can be discarded in do notation, we need an instance for Term (String -> StyleM a). The instance Term (String -> StyleM ()) is more specific, so it's useless in this case. You could either write
do
  () <- flex "1"
  ...

to make the needed instance more specific, or make the provided instance more general by using the type equality trick as explained in danidiaz's answer.

A: The problem is that the Term instance for String -> StyleM () only exists when StyleM is parameterized with (). But in a do-block like
someStyle :: Style
someStyle = Style $ do
    flex "1"
    return ()

there is not enough information to know which is the type parameter in flex "1", because the return value is thrown away.
A common solution to this problem is the "constraint trick". It requires type equality constraints, so you have to enable {-# LANGUAGE TypeFamilies #-}
 or {-# LANGUAGE GADTs #-} and tweak the instance like this:
{-# LANGUAGE TypeFamilies #-}

instance (a ~ ()) => Term (String -> StyleM a) where
    term property value = tell [(property, value)]

This tells the compiler: "You don't need to know the precise type a to get the instance, there is one for all types! However, once the instance is determined, you'll always find that the type was () after all!"
This trick is the typeclass version of Henry Ford's "You can have any color you like, as long as it's black." The compiler can find an instance despite the ambiguity, and finding the instance gives him enough information to resolve the ambiguity.
It works because Haskell's instance resolution never backtracks, so once an instance "matches", the compiler has to commit to any equalities it discovers in the preconditions of the instance declaration, or throw a type error.


text:
Q: When to use Permutations and Combinations So I am very confused about when to use combinations and permutations in questions that ask me to find the amount of ways something can be ordered.
For example, I was trying to answer a question that asked to find get $5$ kinds of cards (aces, twos, threes, etc) in a $5$ card hand. I thought that this would be a permutation $P(13,5)C(4,1)^5$, since I had read that the ways to get a full house ($2$ of one type and $3$ of another) was $P(13,2)C(4,3)C(4,2)$, and thought it would work the same way for this problem, but it ended up being a combination of $C(13,5)C(4,1)^5$.
Why is this the case? And how can I identify when to use combination or permutation?
Thanks,
Kyle

A: If the order of the objects or the cards matters you need to use permutation.
If the order of the objects doesn't matter, you need to use combination.
In your example, any of the five cards can be picked randomly, where the order does not matter, so you use combination.
Hope this helps.

A: The other two answers correctly mentioned the difference between order mattering and not mattering for permutations and combinations respectively. I however, wanted to shed some light on the implied problems of the OP which were:

*

*How to find the total number of $5$-of-a-kinds in a poker hand

*How to find the total number of full houses in a poker hand

For the first, as was previous mentioned, the order of the hand of five distinctly valued cards does not change the hand we have i.e. a hand of $A,2,3,4,5$ all fo hearts is identical to $5,4,3,2,A$ all of hearts. As such, to choose $5$ distinctly valued cards need employ $C(13,5)$. Now however, we have to realize that each card can come in four different suit, and thus for each of the five cards we chose with $C(13,5)$ we have $4$ options to choose from. This leads immediately to the thought of $C(4,1)$ for five cards yiedling the given answer of $C(13,5)*(C(4,1))^5$.
Now for the second. I actually quite dislike the answer given in the OP, that of $P(13,2)C(4,2)C(4,3)$ as I am of the impression that it is hiding the real permutation in the $P(13,2)$ term. We know that a full house consists of $2$ values of card, $2$ of the one and $3$ of a second. So exaclty like in the $5$-of-a-kind example we can choose $2$ of the $13$ possible values in a standard deck of $52$ cards to determine the number of ways in which choosing these two values is possible (NOTE that some may disagree that clearly there are $13$ options for the first value in a full house and $12$ for the other and thus $P(13,2)$ is correct. And I agree that it gives the correct value I just argue that it is arrived at via misleading reasoning based on the order mattering definitions differentiating $P$ and $C$). I would argue that the order of these two chosen values is not relevant and therefore calls for a $C$ to be calculated. The note above's arguement would have you say that not only are you choosing two of the $13$ values for your full house but you are simultaneously choosing which will be your group of $3$ and which your group of $2$, and though this is technically correct I believe it skips a step and is the reason the OP was confused. $C(13,2)$ is the clearer way because, like the $5$-of-a-kind example we are merely choosing cards. We care not that we chose $(A,K)$ versus $(K,A)$ After this choice, we can ask now how many ways can I pick my grouping of $3$ and my grouping of $2$? Well one would have $2$ options, i.e. the $2$ values just chosen in $C(13,2)$, to choose the grouping of $3$ and $1$ option for the grouping of $2$. Because the choice of these two determines which value will require $3$ cards and which $2$ in our full house we are effectively distinguishing between a full house of $(A,A,K,K,K)$ and $(A,A,A,K,K)$ with this permutation of $P(2,1)$. Then finally we can zoom in individually on our pair and $3$-of-a-kind and choose our suits $3$ of them for our $3$-of-a-kind choice and $2$ for our pair yielding $C(4,3)*C(4,2)$. This culminates in a solution of $C(13,2)P(2,1)C(4,3)C(4,2)$ which of course is the same value as the OP's just arrived at in a, in my opinion, clearer way as it stays a bit truer to the definitions that are the answer to the over-arching question of what distinguishes a $P$ from a $C$. Hope this clears it up!

A: Just to throw another 2 scenarios that might make sense when to use combination or permutation:

*

*You are the Coach of a 12 basketball players, you need to choose 5 to play the game, does it matter in what order you select them? No! so that combination.

*You're running a 100 meters sprint with another 4 guys on the lane. Does it matter who get first, second etc? Yes! so that permutation


text:
Q: A good place for unit test folder: in source code folder, out of it, or ...? Developing a software project in python, what is the best practice for the location of tests folder in a project's structure from production perspective? Is it really matter to place them inside the src folder or outside of it. Does this decision affect the production of the software in any way when everything is made automated?
-- my_project
  |---- src
  |---- tests
  |---- ...

or
-- my_project
  +---- src
      |---- tests
  +---- ...

A: I would like to mention one further option to the ones that you have shown, namely to put the unit-tests into a project of their own (one unit-test project for each of the production test projects / components).  What distinguishes these three different options is the degree to which the production code and the test code are separated.
When comparing the different approaches, I see the following criteria:

*

*Maintaining a clear barrier between production code and test code: Production builds should not contain test code.  For some kinds of software this is not just a recommendation, but a strict requirement (for example in safety critical software) - even if the test code within the production code would be dead code or unreachable.  But, a clear barrier can also be advantageous when designing tests: separation helps to first focus on tests on the public API.  And, sometimes you want to deliver production code to the customer but not the unit-test code or vice-versa (depending on the contract).  This is, obviously, the simpler to achieve the more production code and test code are separated.

*Mutual traceability between production code and related test code: Traceability is easy to achieve when production code and test code are versioned together.  Typical commits to the repository could then contain production code changes and related changes to the tests.  Putting production code and tests into different projects would be a disadvantage here - unless you can somehow ensure that both related projects are consistently versioned, such that it is always clear which versions belong together.  If you would have to ensure this manually, it is likely to fail.
Taking these criteria into account, I would personally say that for many development situations your first solution is the best compromise - given that the language and tool environment allows to fulfill the criteria in an acceptable way.  But, in the end you will have to judge according to your respective development context.
One additional note maybe on integration tests, even if this goes beyond what you have asked: Integration tests do not just belong to one component in one specific version, but to a configuration of two or more components in their specific versions.  Therefore is it for integration tests more plausible to put them into projects of their own.  But, again, there are exceptions here...

A: For bigger projects, What I would recommend is having the test at the module level, when dividing your project in modules. If your project is small and has only one module then the test would be outside the src folder.
By module I don't specifically mean "hard" module, in can be "soft" (for a lack of better term). A soft module would be a folder within your project where things are grouped together in a cohesive fashion, where other folders are free to import whatever is inside, but oral / written rules tells you what should be imported, usually one or two public API classes, whereas an "hard" module would hide what's inside, only furnishing the API for other modules.
The reasoning is that:

*

*law of cohesion: You want your test close enough to your source, but not really pollute the implementation details

*opinionated: usually you don't test internals, only the public api.

an example of such soft dividing would be:
  src
    cars
      test
        car_test
      storage
        car_storage.extension
      engine
        engine.extension
      car.extension
    motor
     test
        motor.test
     motor.extension

an example of such hard dividing would be:

  cars
    test
      car_test
    src
      engine
        engine.extension
      car.extension
    package_manager_file

  motor
   test
     motor.test
   src
     motor.extension
   package_manager_file


text:
Q: Hashing a key by folding then dividing by a prime number? I want to hash the following key  "LOWELL" using a simple hash function that used 3 steps  :
Step 1: transform the key into a number.
LOWELL = | L | O | W | E | L | L | | | | | | |
ASCII code: 76 79 87 69 76 76 32 32 32 32 32 32

my question here why it added more 6 empty positions with fixed ASCII code 32

Step 2: fold and add (chop off pieces of the number and add
them together)
7679|8769|7676|3232|3232|3232|
7679+8769+7676+3232+3232+3232 = 33,820

Step 3: take the mod by a prime number
33,820 mod 19937 = 13,883

Another question here for why dividing by prime numbers i found this
  answer : Dividing by a number is good when there are sequences of
  consecutive numbers. If there are many dierent sequences of
  consecutive numbers, dividing by a number that has many small factors
  may result in lots of collisions. A prime number is a better choice. but i didn't get it

Step 4: divide by the size of the address space (preferably a prime number). 13,883 mod 101 = 46

finally why it divided the address space ?!

You can find detailed steps here  (Slide 350)
Many Thanks in advance for helping

A: Since your address space contains only 101 slots, you cannot put your record in a position whose address exceeds this limit.
So you take the reminder of division of the output from the hash function (13,883 in your case) by the address space, to make sure that the location of the record falls in the allowed address space.
So h(s) % address_space will always give allowed position within your address space.
Regarding your first question, why do we use a prime number in hashing, this thread will help you:
Why use a prime number in hashCode?


text:
Q: Can you change Ruby core classes (eg String) in a Ruby on Rails deployed on Heroku? I ran into a problem with adding a method to String that allows you to do something like: "9".is_a_number? and get true or false. I tested it working on development but when I pushed to production it didn't work.
Anybody have experience changing Ruby core classes on Heroku?
Both times I placed the new code inside the /helper directory on my Rails app.
Edit:
This is from my memory so I don't have 100% confidence that this is what I had:
app/helpers/sudoku_helper.rb
class String
   def is_a_number?
      self.to_f.to_s == self.to_s || self.to_i.to_s == self.to_s
   end
end

I didn't add anything else, as it worked on development. Perhaps I need to do something to tell Rails to run it on production?

A: Put your code in the lib folder and require it in a initializer or directly put your code in the initializer.
This way, you can be sure it is loaded and when is it loaded.


text:
Q: Unable to Create a new account from Scaffolding I'm trying to create authorization and authentication from scratch using the new Identity scaffolding in the new .Net Core 2.1 but keep getting this error.
SqlException: Invalid object name 'AspNetUsers'.
RegisterModel fails to execute on this line:
var result = await _userManager.CreateAsync(user, Input.Password);

IDENTITYHOSTINGSTARTUP.CS
[assembly: HostingStartup(typeof(Authorize.Areas.Identity.IdentityHostingStartup))]
namespace Authorize.Areas.Identity
{
    public class IdentityHostingStartup : IHostingStartup
    {
        public void Configure(IWebHostBuilder builder)
        {
            builder.ConfigureServices((context, services) => {
                services.AddDbContext<AuthorizeContext>(options =>
                    options.UseSqlServer(
                        context.Configuration.GetConnectionString("AuthorizeContextConnection")));

                services.AddDefaultIdentity<AuthorizeUser>()
                    .AddEntityFrameworkStores<AuthorizeContext>()
                    .AddDefaultTokenProviders();
            });
        }
    }
}

A: This error usual suggests that you do not have the AspNetUsers table in your database. Have you ran the migrations provided in the scaffold? This can be done through either a powershell or console terminal. Navigate to the web project and execute Update-Database if using powershell or dotnet ef database update for  console.
https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/


text:
Q: A question on the SYZ mirror symmetry A toy SYZ mirror symmetry is described as follows. Let $X$ be a $n$-dimensional compact manifold. The contangent bundle $T^*X$ has a natural symplectic structure locally given by the $2$-form $\sum_idq_i \wedge dx_i$. Here $(x_i)$ is a local coordinate of $X$ and $(x_i,q_i)$ is a local coordinate of $T^*X$ corresponding to the $1$-form $\sum_i q_i dx_i$.
On the other hand, the tangent bundle $TX$ has a complex structure locally given by $(x_i+iy_i)$. Here $(x_i)$ is a local coordinate of $X$ and $(x_i,y_i)$ is a local coordinate of $TX$ corresponding to the vector field $\sum_i y_i \partial/\partial x_i$.
Some people want to compactify the two spaces by modding out the fibers by a lattice and its dual. Then the local holomorphic coordinate becomes $z_i=\exp2\pi \sqrt{-1}(x_i+iy_i)$. This is a toy SYZ mirror symmetry I am aware of.
My question is, why the complex structure on $TX$ is natural? Alsoare there any more good examples that shows the SYZ mirror symmetry?


text:
Q: How to split String with "\" as a delimiter? and also how to replace "\" into ":"? Hi I would like to know what should I put in order to split the string into parts using "\" as a delimiter?
The String returned by the server will be as shown below
String test ="\\ipAddress\FolderA\InnerFolderA\abc.mp4"; << this one give me error ,thus i have to put in another "\",
String test ="\\ipAddress\\FolderA\\InnerFolderA\\abc.mp4";

String parts[] = test.split("\\");
        String part0 = parts[0];
        String part1 = parts[1];
        String part2 = parts[2];

and when I run it, it gives me error:

Exception in thread "main" java.util.regex.PatternSyntaxException:
  Unexpected internal error near index 1.

Also when I tried replacing the String using this line of code to replace the "\" as in
String output = test.replaceAll("\\", ":");

it also give me error .

A: Maybe you should use "\\" as the argument,not "\". Very glad to help you!
public static void main(String[] args) {
    String test ="\\ipAddress\\FolderA\\InnerFolderA\\abc.mp4";

    String parts[] = test.split("\\\\");
            String part0 = parts[0];
            String part1 = parts[1];
            String part2 = parts[2];
            System.out.println(part1);
}

A:  public static void main(String[] args) {

        String test = "\\ipAddress\\FolderA\\InnerFolderA\\abc.mp4";
        String output = test.replaceAll("\\\\", ":");
        System.out.println(output);

        String parts[] = test.split("\\\\");
        String part0 = parts[0];
        String part1 = parts[1];
        String part2 = parts[2];
        System.out.println(part0);
        System.out.println(part1);
        System.out.println(part2);

    }

output
:ipAddress:FolderA:InnerFolderA:abc.mp4

ipAddress
FolderA


text:
Q: How to pack multiple parameter into one I use the Prawn to generate pdf. To make a table, I do:
table test_rows(test), :column_widths => [100, 200, 360] , &table_style

Is there any way that can let me put a proc into table_style? I don't want to repeat column_widths and table_style in my code.
def table_style
  return Proc.new{
    row(0).font_style = :bold
    columns(1..3).align = :center
    self.row_colors = ["DDDDDD", "FFFFFF"]
    self.header = true
  }
end

A: This method appears to take three arguments: data, options and a block. See https://github.com/prawnpdf/prawn/blob/master/lib/prawn/table.rb
If you are trying to store those arguments as temporary variables to re-use in other calls to table, you can use something like:
options = { :column_widths => [100, 200, 360] }
table_style = Proc.new { ... }

table(data1, options, &table_style)
table(data2, options, &table_style)


text:
Q: Place LinearLayout at bottom of another LinearLayout I am trying to place LinearLayout containing gridview at the bottom. Please suggest what can be done.
Below is my XML code :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/parentRelativeView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/darkgreen"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txtEquation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/darkorange"
        android:gravity="center"
        android:text="2+2=?"
        android:textColor="@color/white"
        android:textSize="40dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/txtOutput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/darkpurple"
        android:gravity="center"
        android:textColor="@color/white"
        android:textSize="28dp"
        android:textStyle="bold" />

    <com.github.lzyzsd.circleprogress.DonutProgress
        android:id="@+id/donut_progress"
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:layout_below="@+id/txtOutput"
        android:layout_gravity="center"
        android:gravity="center"
        android:textColor="@color/white"
        custom:donut_finished_color="#30b8f2"
        custom:donut_progress="01"
        custom:donut_text_size="50dp" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_weight="0"
        android:background="@color/white"
        android:baselineAligned="false">

        <GridView
            android:id="@+id/numberGridView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="0.4dp"
            android:background="@color/white"
            android:horizontalSpacing="0.4dp"
            android:numColumns="@integer/grid_rows"
            android:stretchMode="columnWidth"
            android:verticalSpacing="0.4dp" />
    </LinearLayout>
</LinearLayout>

A: There is no way you can align some items to top and others to bottom in LinearLayout. We have RelativeLayout for purposes like this. With RelativeLayout you can align anything to anything so I recommend you to use it.


text:
Q: jQuery's fadeToggle() selects more elements than desired

  $(document).ready(function(event) {
    $(".reply-btn").click(function() {
      $(".section-row-reply").closest(".section-row-reply").fadeToggle();
    });
  });

I have a for-loop that generates the following:

*

*comments

*replies

*reply form.

I want the jquery function,fadeToggle() to reveal the reply form for each comment when the reply button is clicked

{{ comments.count }} Comment{{ comments|pluralize }}

    {% for comment in comments %}
    {% if comment %}

{{ comment.user }}

          {{ comment.timestamp }}

{{ comment.content }}

          <button type="button" name="button" class="reply-btn btn btn-outline-dark btn-sm" id="reply-button">Reply</button>

        {# reply per comment #}

        {# all replies to comments will be shown below the comment #}

        {% if comment.replies %}
        {% for reply in comment.replies.all %}

{{ reply.user }}

              {{ reply.timestamp }}

{{ reply.content }}

        {% endfor %} {# endfor comment.replies #}
        {% endif %} {# endif comment.replies #}

        {# after replies have been shown, we can have the reply-comment-form #}
        {% if user.is_authenticated %}

          <form class="post-reply" method="post">
            {% csrf_token %}
            <input type="hidden" name="comment_id" value="{{ comment.id }}">

                  <textarea class="input" name="content" placeholder="Reply here..."></textarea>

                <button class="primary-button" value="submit" type="submit">Reply</button>

              {{ comment_form.errors }}

          </form>

        {% endif %} {# endif user.is_authenticated #}
        {# comments are display in the manner above in the div section #}

    {% endif %} {# endif comment #}
    {% endfor %} {# endfor comment in comments #}

This is a django powered site hence the {% %}, {# #} and {{ }} at the html layer. The function works but not exactly. When any reply button is clicked (to display the reply form), other reply forms for other comments are displayed.
**The idea is to make the reply button for each comment display only the reply form for that comment. Any help will be greatly appreciated. I suspect my selection of elements at the jquery layer. **
all css are that of bootstrap 3.3.7


text:
Q: Mapping an array in asp.net Web API I'm trying to map up a controller function to my web api.
config.Routes.MapHttpRoute(
              name: "RPCRoutingApiCaseStudy",
              routeTemplate: "api/{controller}/{action}/{ServiceID}",
              defaults: new { ServiceID = RouteParameter.Optional }
              );

The issue is, in my controller, ServiceID is supposed to be an array. How can I set up my mapping to accept an array, and what would it look like? Sorry if that's an obvious question, but I'm very unfamiliar with this stuff and I'm trying to learn.
I understand how to do it with a regular parameter, where like for int I'd type url/api/controller/method/5
I just don't know what to do for an array.

A: In order to pass complex types into Web API you need to make that helper class that contains an IENumerable type then pass that object into the Web API via JSON encapsulation.
The following example accepts a POST method and takes a CustomListType object that contains a List. You can then do what you like with the object.
public class ValuesController : ApiController
{

    [System.Web.Http.AcceptVerbs("POST")]
    public bool POST(CustomListType myList)
    {
        //Do stuff here

        return true;
    }

    public class CustomListType
    {
        public List<int> myArray { get; set; }
    }

}

Using Advanced Rest Client for Chrome; You can test the post by sending the object:
{myArray:[0,1,2]}

Note that because CustomListType has a member called "myArray" we also have "myArray" in our JSON object.
If you put a debug line in there you should be able to see the objects and the values of "myArray"


text:
Q: How to add a checkbox element to attachments editor with example The code below adds a custom input field to the attachments editor. How can I convert the text input to a checkbox and get/set the value of the checkbox on load and save?
Note: "input" => "checkbox" does not work :(
function image_attachment_fields_to_edit($form_fields, $post) {
        $form_fields["imageLinksTo"] = array(
            "label" => __("Image Links To"),
            "input" => "text",
            "value" => get_post_meta($post->ID, "_imageLinksTo", true)
        );
        return $form_fields;
    }

function image_attachment_fields_to_save($post, $attachment) {
        if( isset($attachment['imageLinksTo']) ){
            update_post_meta($post['ID'], '_imageLinksTo', $attachment['imageLinksTo']);
        }
        return $post;
    }

add_filter("attachment_fields_to_edit", "image_attachment_fields_to_edit", null, 2);
add_filter("attachment_fields_to_save", "image_attachment_fields_to_save", null, 2);

A: Below is a complete block for adding an IsLogo checkbox , including the saving :
function attachment_fields_to_edit_islogoimage( $form_fields, $post ) {
    $islogo = (bool) get_post_meta($post->ID, '_islogo', true);
    $checked = ($islogo) ? 'checked' : '';

    $form_fields['islogo'] = array(
        'label' => 'Logo Image ?',
        'input' => 'html',
        'html' => "<input type='checkbox' {$checked} name='attachments[{$post->ID}][islogo]' id='attachments[{$post->ID}][islogo]' />",
        'value' => $islogo,
        'helps' => 'Should this image appear as a proposal Logo ?'
    );
    return $form_fields;

}
add_filter( 'attachment_fields_to_edit', 'attachment_fields_to_edit_islogoimage', null, 2 );

function attachment_fields_to_save_islogoimage($post, $attachment) {
    $islogo = ($attachment['islogo'] == 'on') ? '1' : '0';
    update_post_meta($post['ID'], '_islogo', $islogo);
    return $post;
}
add_filter( 'attachment_fields_to_save', 'attachment_fields_to_save_islogoimage', null, 2 );

my 2 cents.

A: Set the 'input' to 'html' and write out the html for the input:
function filter_attachment_fields_to_edit( $form_fields, $post ) {
    $foo = (bool) get_post_meta($post->ID, 'foo', true);

    $form_fields['foo'] = array(
    'label' => 'Is Foo',
    'input' => 'html',
    'html' => '<label for="attachments-'.$post->ID.'-foo"> '.
        '<input type="checkbox" id="attachments-'.$post->ID.'-foo" name="attachments['.$post->ID.'][foo]" value="1"'.($foo ? ' checked="checked"' : '').' /> Yes</label>  ',
    'value' => $foo,
    'helps' => 'Check for yes'
    );
    return $form_fields;
}

Saving works just as you did above, but you're checking against a checkbox value instead, so you'll need to update to true if isset() and update to false if not.


text:
Q: JavaScript MIME type is application/octet-stream nodejs I'm writing a combiner module for node js.
I'm using express to get the files like the following:
app.get('/combine/js/?files=scripts/file1.js;scripts/file2.js', function(req, res){
    res.contentType('text/javascript');
    res.end(content); //the combined files content
});

Now, when the page is loaded I'm getting the following error in chrome:
'Resource interpreted as Script but transferred with MIME type application/octet-stream'
What am I doing wrong?
UPDATE: this is the full app.get combiner function that response the content...
    app.get('/combiner/:type/?', function(req, res){
        var type = req.params.type;
        var files = [];
        files = req.query.files.split(';');
        var content = combiner.combine(type, files);
        switch(type){
                case 'js': res.contentType('text/javascript'); break;
            case 'css': res.contentType('text/css'); break;
        }
        content = content.replace('<:=appid=:>', vars.appid);
        res.end(content);
    });

A: From what I can see, it looks like the Express docs might be wrong here. They clearly say that  giving the mime type will work, but that isn't happening for you, or me in my tests.
You should either set the content-type automatically:
res.header('Content-Type', 'application/javascript');

or pass the file extension to res.contentType().
res.contentType('js');


text:
Q: iOS navigation view background image UIViewContentModeScaleAspectFill not working Using the code below, I've added a background image to a UINavigationController (the view, NOT the nav bar) and I'm trying to scale the image to fill the view, because I don't know the user's device and orientation. (Note: I do NOT want to create device- or orientation-specific sizes / resolution because my background images could change so this would take too much time).
- (void)viewDidLoad
{
    [super viewDidLoad];

    NSLog(@"%@", NSStringFromCGRect(self.navigationController.view.frame));

    // Set background image
    NSString *filename = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"assets/images/wallpaper.jpg"];
    self.background = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:filename]];
    self.background.contentMode = UIViewContentModeScaleAspectFill;
    self.background.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.background.center = CGPointMake(CGRectGetMidX(self.navigationController.view.frame), CGRectGetMidY(self.navigationController.view.frame));
    [self.navigationController.view insertSubview:self.background atIndex:0];
}

The UIViewContentModeScaleAspectFill and UIViewAutoresizingFlexibleHeight/Width is SUPPOSED to make the image scale to fill the screen regardless of screen size and orientation. However, I need help with an issue on the simulator: iOS behaves differently depending on whether the simulator is started in portrait / landscape mode.
The image below shows what happens when the app is started in portrait mode and then rotated to landscape. In portrait, the image is NOT scaled to fill the view (there are black bars above/below the image). In landscape, the image is correctly scaled to fill the view.

The image below shows what happens when the app is started in landscape and then rotated to portrait. In landscape, the image is NOT scaled to fill the view (there are black bars to the sides of the image). In portrait, the image is correctly scaled to fill the view.

Why is iOS handling these two scenario's differently, why is the image NOT scaling correctly to fill the view and how do I get UIViewContentModeScaleAspectFill to work correctly?

A: Reposting my comment as an answer so you can mark this question as solved.
You're not setting the UIImageView's initial frame. Try something like
- (void)viewDidLoad
{
    [super viewDidLoad];

    ...

    self.background.frame = self.navigationController.view.bounds;
    [self.navigationController.view insertSubview:self.background atIndex:0];
}


text:
Q: For the .com TLD, is there any known change tracking for WhoIs information? A client exposed information regarding what will become a controversial website in the domain WhoIs after she purchased it from auction.
Is there any whois cache that will detect, save, and share the old whois information for that domain, after it has changed?
(It's a website to provide birth control in countries where it is banned, and she may receive death threats for the information shared on it.  Obviously something she wishes to avoid.)

A: http://www.domaintools.com/research/whois-history/
They supposedly keep track of that data.  I've never used their service, but you can see from sample reports what the data would look like.  Or you can have your client purchase their domain's WHOIS history and see if the data she's wishing to hide is in there or not.

A: http://who.is/ has a history of records in the tab called History after you do a lookup.

A: The domaintools WHOIS history is the one everyone uses. It's not perfect, they do snapshots. I agree with the suggestion that she pay for a history of the domain in question to see what they have. It's about $50, and that's what most people womdering about its history are likely to try.
There's a history tab at who.is, but precious little history behind it.  I tried some domains that have been live for a decade and it had something.
Note that since the domaintools history requires money, people are unlikely to stumble across anything by accident.


text:
Q: GeoDjango error: Only numeric values of degree units are allowed on geographic DWithin queries I'm trying to get N points within 5000 meters of a certain point. My database is Postgres(PostGIS). I have a model like this:
class Theatre(models.Model):
    geom = models.PointField(srid=4326, blank=True, null=True, default=None)
    objects = models.GeoManager()

Then I ran a couple lines in Django shell:
Theatre.objects.filter(geom__dwithin=(GEOSGeometry('POINT(30.111199 -97.309990)'), D(m=5000)))

and I get the error:
ValueError: Only numeric values of degree units are allowed on geographic DWithin queries.

I found the documentation in here and it discusses calculating the geometry distance. What am I doing wrong?

A: I don't know GeoDjango, but, from a PostGIS PoV, there seems to be at least two potential problems:

*

*If the arguments for POINT() should be longitude & latitude, they should probably be reversed: (-97.3, 30.1).

*geom_dwithin expects the distance to be in the same units as the geometry's SRS, which in your example (srid=4326) is degrees, not meters.
Study the GeoDjango or PostGIS documentation, or at least the various other questions on this site that involve ST_Dwithin(). Try Googling
site:gis.stackexchange.com st_dwithin

A: As highlighted here and by the error message, you need to convert D(m=5000) to degree units. The following function can help you with that.
import math

def distance_to_decimal_degrees(distance, latitude):
    """
    Source of formulae information:
        1. https://en.wikipedia.org/wiki/Decimal_degrees
        2. http://www.movable-type.co.uk/scripts/latlong.html
    :param distance: an instance of `from django.contrib.gis.measure.Distance`
    :param latitude: y - coordinate of a point/location
    """
    lat_radians = latitude * (math.pi / 180)
    # 1 longitudinal degree at the equator equal 111,319.5m equiv to 111.32km
    return distance.m / (111_319.5 * math.cos(lat_radians))

After which you can then call your query as follows:
Theatre.objects.filter(geom__dwithin=(GEOSGeometry('POINT(30.111199 -97.309990)'), distance_to_decimal_degrees(D(m=5000), -97.309990)))


text:
Q: Rails reverses day and month when saving DateTimePicker form field I am trying to use Tempus Dominus Bootstrap 4 in a form on a Ruby on Rails 5.2 app so the user can select a date. Here is the code:
app/views/events/_form.html.erb

  <%= f.label :starts_at, 'Start Date and Time', class: 'control-label' %>

    <%= f.text_field(:starts_at, class: "form-control datetimepicker-input", data: {target:"#datetimepicker1"}) %>

app/assets/javascripts/events.js
$(function () {
  $('#datetimepicker1').datetimepicker();
});

app/controllers/events_controller.rb
  def create
    @event = Event.new(event_params)
    @event.user = current_user
    if @event.save
      redirect_to @event, notice: 'Event was successfully created.'
    else
      render :new
    end
  end

I want to submit the format with month first. When I pick a date June 9, 2018 and submit the form, it saves it to the database with the month and day reversed: Sept 6, 2018. When I look at the params after the form is submitted, the format is 06/09/2018 6:00 PM with month first, but Ruby/Rails converts it to a datetime object assuming day first.
How do I tell Ruby that the month is first when converting it to a date object? Can I do something in the controller before saving it?

A: You can tell Ruby how to read time string:
DateTime.strptime('06/09/2018', '%m/%d/%Y')

More details you can see in this answer.
Edited:
Also, you can set the default date format as there:
Add this to config/initializers/date_time.rb
Date::DATE_FORMATS[:default] = "%m/%d/%Y"

A: I found out you can change the date format to one Ruby correctly understands and that is easily readable by users. Change the JavaScript to:
$(document).on('turbolinks:load', function() {
  $('#datetimepicker1').datetimepicker(
    'format', 'MMMM D, YYYY h:mm A'
  );
});

This will display the date to the user as June 9, 2018 6:30 PM. Date format comes from Moment.js http://momentjs.com/docs/#/displaying/format/ but is added to the format option of Tempus Dominus.
As a side note, to get tempus dominus boostrap 4 working in Rails, you have to also load moment.js. Either call the cdn or add the momentjs-rails gem. If the latter then in your application.js file you need to require it, something like this:
# app/assets/javascripts/application.js
...
//= require moment
//= require tempusdominus-bootstrap-4.js


text:
Q: ckeditor with placeholder plguin enhancement double click issue I need a placeholder/variable that takes name, defaultValue, tooltip/description. I created a plugin and it is working fine in the editor/create mode. When placeholder is created, it is adding the following tags to source
<var class="cke_placeholder" name="varName" title="varToolTip">[[varDefaultValue]]</var>

Image that depicts create & edit mode differences

When I save the html content with placehoder in db and trying to load it back to ckeditor, I am not able to get the + symbol and hence not able to launch the editor.
Here is my ckeditor/plugins/var/plguin.js
    'use strict';

( function() {
    CKEDITOR.plugins.add( 'var', {
        requires: 'widget,dialog',
        icons: 'var', // %REMOVE_LINE_CORE%
        hidpi: true, // %REMOVE_LINE_CORE%

        onLoad: function() {
            CKEDITOR.dialog.add( 'var', this.path + 'dialogs/var.js' );
        },
        init: function( editor ) {
            this.registerWidget( editor );
            editor.ui.addButton && editor.ui.addButton( 'Var', {
                label: 'Create Variable',
                command: 'var',
                toolbar: 'insert',
                icon: 'var'
            } );
        },
        registerWidget: function(editor){
            var that = this;

            // Put ur init code here.
            editor.widgets.add( 'var', {
                // Widget code.
                dialog: 'var',
                pathName: 'var',
                // We need to have wrapping element, otherwise there are issues in
                // add dialog.
                template: '<var class="cke_placeholder">[[]]</var>',

                downcast: function() {
                    return new CKEDITOR.htmlParser.text( '<var class="cke_placeholder" name="'+this.data.name+'" title="'+this.data.description+'">[[' + this.data.defaultValue + ']]</var>' );
                },

                init: function() {
                    this.setData( 'defaultValue', this.element.getText().slice( 2, -2 ) );
                    this.setData( 'name', this.element.getAttribute("name") );
                    this.setData( 'description', this.element.getAttribute("title") );
                },

                data: function() {
                    this.element.setText( '[[' + this.data.defaultValue + ']]' );
                    this.element.setAttribute('name', this.data.name );
                    this.element.setAttribute('title', this.data.description );
                }
            } );
        },
        afterInit: function( editor ) {
            this.registerWidget( editor );

            /*var placeholderReplaceRegex = /\[\[([^\[\]])+\]\]/g;

            editor.dataProcessor.dataFilter.addRules( {
                text: function( text, node ) {
                    var dtd = node.parent && CKEDITOR.dtd[ node.parent.name ];

                    // Skip the case when placeholder is in elements like <title> or <textarea>
                    // but upcast placeholder in custom elements (no DTD).
                    if ( dtd && !dtd.span )
                        return;

                    return text.replace( placeholderReplaceRegex, function( match ) {
                        // Creating widget code.
                        var widgetWrapper = null,
                            innerElement = new CKEDITOR.htmlParser.element( 'span', {
                                'class': 'cke_placeholder'
                            } );

                        // Adds placeholder identifier as innertext.
                        innerElement.add( new CKEDITOR.htmlParser.text( match ) );
                        widgetWrapper = editor.widgets.wrapElement( innerElement, 'placeholder' );

                        // Return outerhtml of widget wrapper so it will be placed
                        // as replacement.
                        return widgetWrapper.getOuterHtml();
                    } );
                }
            } );*/
        }
    } );

} )();

Here is my ckeditor/plugins/var/dialogs/var.js
'use strict';

CKEDITOR.dialog.add( 'var', function( editor ) {
    //var lang = editor.lang.var,
        //generalLabel = editor.lang.common.generalTab,

        var generalLabel = 'General',
        validRegex = /^[^\[\]<>]+$/,
        emptyOrInvalid = ' can not be empty. It can not contain any of following characters: [, ], <, >',
        invalid = ' can not contain any of following characters: [, ], <, >';

    return {
        title: 'Variable properties',
        minWidth: 300,
        minHeight: 80,
        contents: [
            {
                id: 'info',
                label: generalLabel,
                title: generalLabel,
                elements: [
                    // Dialog window UI elements.
                    {
                        id: 'name',
                        type: 'text',
                        style: 'width: 100%;',
                        label: 'Name',
                        'default': '',
                        required: true,
                        validate: CKEDITOR.dialog.validate.regex( validRegex, 'name'+emptyOrInvalid ),
                        setup: function( widget ) {
                            this.setValue( widget.data.name );
                        },
                        commit: function( widget ) {
                            widget.setData( 'name', this.getValue() );
                        }
                    },
                    {
                        id: 'defaultValue',
                        type: 'text',
                        style: 'width: 100%;',
                        label: 'Default Value',
                        'default': '',
                        required: true,
                        validate: CKEDITOR.dialog.validate.regex( validRegex, 'Default Value'+emptyOrInvalid ),
                        setup: function( widget ) {
                            this.setValue( widget.data.defaultValue );
                        },
                        commit: function( widget ) {
                            widget.setData( 'defaultValue', this.getValue() );
                        }
                    },
                    {
                        id: 'description',
                        type: 'text',
                        style: 'width: 100%;',
                        label: 'Description',
                        'default': '',
                        required: true,
                        validate: CKEDITOR.dialog.validate.regex( validRegex, 'Description'+invalid ),
                        setup: function( widget ) {
                            this.setValue( widget.data.description );
                        },
                        commit: function( widget ) {
                            widget.setData( 'description', this.getValue() );
                        }
                    }
                ]
            }
        ]
    };
} );


text:
Q: cakephp avoid multiple callbacks Suppose I have a User model who hasMany Items (and Item belongsTo User, of course)
each time an Item is modified anyewhere in my applicationI want an email to be sent to his user (or to their users)
So in my Item model I wrote something like
public function beforeSave($options = array())
{
    // if data is modified find User and send him email
}

But making so when I edit more than one Item at the same time in my action (i.e. in a foreach loop) then several emails are sent, but I want just one email, or one email for every User involved in the update.
How can I achieve this?
Maybe using cakephp Event system?

A: You can set an extra variable:
public $isMultiple = false;
public function beforeSave($options = array())
{
    if(!$this->isMultiple) {
        $this->isMultiple = true;
        // if data is modified find User and send him email
    }
}

A: Firstly, don't send email from inside a data model. Email activities are very volatile and you should keep your data model code as stable as possible. Instead, use a component and call a method on the component when you need emails sent.
It sounds like you want to report on completed transactions, and not individual record edits. One way to handle this is to set a datetime stamp in the User model of when the last email was sent. You can then use that datetime stamp to find Item records that have been modified, and notify of those changes.
In your controller you would simply modify the items as needed.
public function action()
{
    foreach($record in $records)
    {
        ......
        $this->Item->save(....);
    }

    $this->MyEmailComponent->notify($user_id);
}

Then in your email component you would query the Item model for which items have changed since the last email was sent.
public function notify($user_id)
{
    $this->User->id = $user_id;
    $last_email = $this->User->field('emailed');

    $updated_items = $this->Item->find('all',array(
        'conditions'=>array('Item.updated >'=>$last_email)
    ));

    // send email about those items

    $this->User->saveField('emailed',date('Y-m-d h:i:s'));
}


text:
Q: How to use data from one field in another field in Solr? In data-config.xml:
<entity name="index" query="select distinct index from (SELECT distinct index FROM street WHERE (substr(code::text, 1, 8)::character varying(8)) = substr('${kladr.code}', 1, 11)
                                    union all
                                    SELECT distinct index FROM kladr WHERE (substr(code::text, 1, 8)::character varying(8)) = substr('${kladr.code}', 1, 8)
                                    union all
                                    SELECT distinct index from street_zip where (substr(code::text, 1, 8)::character varying(8)) = substr('${kladr.code}', 1, 11)
                                    union all
                                    SELECT distinct index from street_building where (substr(parent_code::text, 1, 8)::character varying(8)) = substr('${kladr.code}', 1, 8)) as t
                                    "
           transformer="LogTransformer" logTemplate="street: ${index.index}" logLevel="debug">
        </entity>

I need separate entity "index_count" with number of records in entity "index" (it is multivalued field). If I make another SQL query it slows down data import, can I use entity to extract data from it? For example:
<entity name="index_count" query="SELECT count(*) from index">
    </entity>

Or something like this?

A: Probably not the only way, but you could add an Update+Request+Processor, that counts the number and populates the index_count field.
It will be fast, but it is more complex to implement, you need to write java code. And if you are using Solrcloud you need to deploy the code to all the nodes etc


text: Q: How to detect if Prevent cross site tracking is enabled in Safari browser using JavaScript Can someone tell me how can I detect if the prevent third party protection is enabled in Safari browser using JavaScript.


text:
Q: Trouble with sqlite3 set_authorizer method I'm trying to use the Connection.set_authorizer method to only allow certain DB operations with a connection object.  (The documentation is here)
I'm using this code to test:
import sqlite3 as sqlite

def select_authorizer(sqltype, arg1, arg2, dbname):
    print("Test")
    return sqlite.SQLITE_OK  #should allow all operations

conn = sqlite.connect(":memory:")
conn.execute("CREATE TABLE A (name integer PRIMARY KEY AUTOINCREMENT)")
conn.set_authorizer(select_authorizer)
conn.execute("SELECT * FROM A").fetchall() #should still work

This gives me a sqlite3.DatabaseError: not authorized, without ever printing out "Test".  I'm guessing I may have set up my authorizer wrong, and it's just failing to even call it.  (Though the error message sure doesn't communicate that)  But according to the documentation, this setup looks right.
EDIT: Changed sqlite.SQLITE_OKAY to sqlite.SQLITE_OK, but since the method doesn't seem to be called at all, not surprisingly that didn't help.

A: The authorizer callback takes 5 arguments, but yours only accepts four:

The first argument to the callback signifies what kind of operation is to be authorized. The second and third argument will be arguments or None depending on the first argument. The 4th argument is the name of the database ("main", "temp", etc.) if applicable. The 5th argument is the name of the inner-most trigger or view that is responsible for the access attempt or None if this access attempt is directly from input SQL code.

Thus, the signature should be:
def select_authorizer(sqltype, arg1, arg2, dbname, source):

Generally, when testing a callback like that, testing is made easy by using a *args wildcard parameter:
def select_authorizer(*args):
     print(args)
     return sqlite.SQLITE_OK

The above callback prints out:
(21, None, None, None, None)
(20, 'A', 'name', 'main', None)

when I run your test SELECT.
See the C reference for SQLite set_authorizer and the action codes reference for the various constants used.

A: Martijn Pieter's answer is correct; I somehow missed that 5th argument when I read that paragraph.
Something I've also found reading through the documentation more closely that would have really helped me figure this out on my own is the line: sqlite.enable_callback_tracebacks(True)
This line will cause sqlite to print a traceback for errors that occur within callback functions.


text:
Q: PHP while with sleep loop not updating database until end of loop I have a while loop with a sleep function that I wan´t to run -> update database -> sleep -> run again for a number of 10 times. With the below script the script loops 10 times, but it only updates the database when all 10 loops have finished.
I added an echo at the end just to verify, and the echo does not appear on the page until the and when every loop is echoed out at once.
I have also tried placing ob_flush() and flush() after the echo with no luck.
Script
$loops = 10;
while ($loops > 0)
{
  while($row = mysql_fetch_array($result))
  {
    // Get current User status
    $username = $row['username'];
    $user_status = $row['user_status'];
    $user_updated = date('Y-m-d H:i:s');

    // Update database
    $update_sql = "UPDATE  `database`.`user` SET  `user_status` =  '$user_status',
                                                  `user_updated` =  '$agent_updated'
                                            WHERE
                                                  `user`.`username` =  '$username'";
    $update=mysql_query($update_sql);
    echo "Loop #".$loops."<br>";
  }
flush();
$loops--;
Sleep(5);
}

I've also tried the same with a FOR loop.
Any suggestions would be appreciated. I've gone through the search and haven´t found users with similar issues but I couldn't find the answer.

A: You can get those echoes to show one by one, but on a controlled environment (according to php documentation, flush may still buffer the output on several Win32 systems), you can read further in the php flush manual page.
To be more specific, make sure APaches mod_gzip is disabled, also, some php.ini settings like output_buffering and zlib.output_compression should be set to false.
output_buffering = false
zlib.output_compression = false

Even with all of this, you may also need to send a "big" amount of data (like 2048 chars) in order to make some browser to actually display new data.
echo "One"
echo str_repeat(" ", 2048);
Sleep(3)
echo "Two"
echo str_repeat(" ", 2048);
// Ans so on

In the comments of the aforementioned  manual page, you can see more examples.

A: It seems, according to the code provided, that all updates are done in the first loop, then mysql_fetch_array($result) returns only falses and the inner loop is not proceeded again in the other main loops, unless you fill $result again (between while cycle headers).

A: As pointed out by N.B. that PHP only returns results all at once after the script runs, I have ended with the following solution:
A bash.sh script that runs the PHP page every 5 seconds:
#!/bin/bash

set -e
count=1
while [ $count -le 12 ] :
do
  # run this scripts for one minute (12 times every 5 seconds = 60 seconds)
  /usr/bin/php -q thescript.php
  (($count++))
sleep 5
done

Then a cronjob that runs the page every minute. The above works and solves my issue.


text:
Q: Sharepoint Online: Creating new pages in wiki When trying to create a new page in the wiki, I use the double square brackets in the designer, e.g.

[[Repositories, UOW and Onion]]

After saving, the link has a dotted line but it is not clickable (it's not a link!):

This only happens sometimes and I can't figure out why.

A: You can use wiki links to link pages together by simply using the page name surrounded by double square brackets. You create wiki links the same way whether you are linking to existing wiki pages or pages that do not exist yet.
For example, to quickly add a link from a wiki page back to the home page for your wiki, type [[Home]].
Here are some examples of links:

*

*[[Dogs]] : A link to a page named Dogs in the same folder.

*[[Animals/Dogs]] : A link to a page named Dogs in a subfolder called Animals.

*[[List:Announcements/Welcome]] : A link to the item called Welcome in the Announcements list on this site.

*To display double opening or closing brackets without making a link, type a backslash before the two brackets. For example, [[ or ]].
For more details click here.


text:
Q: How to get a Backbone Model attribute after fetch? I know that a fetch is asynchronous and it needs to use "success" in fetch.
But what if I want to use the data out of the success?
I wanna to get the user ID and to use it in a model "Note".
 authedUser.fetch({
            success: function(){;
                window.uid = authedUser.get("id");
            }

But if I try to do this console.log(uid); not in success I get undefined.

A: When your new models/collections are registered the "change" event is triggered.
So you can use
 MyModel.on("change", function() {

    MyModel.get('wtv');

});

A: You should be able to access updated model from success callback.
Like this:
authedUser.fetch({
        success: function(model){;
            window.uid = model.get("id");
        }


text:
Q: C# SharpZipLib Can't read stream when trying to uncompress zip in Unity3D I'm using ICSharpCode.SharpZipLib to try and unzip a file from the web, all I need to do is get the uncompressed byte array. However I get the error "InvalidOperationException: Unable to read from this stream". I am working in c# in Unity3D with the target as webplayer. It apparently is readable, so I'm not sure of the problem. Here's my code and any help would be very much appreciated.
using (MemoryStream s = new MemoryStream(bytes))
{
    using (BinaryReader br = new BinaryReader(s))
    {

        using (ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(s))
        {
            byte[] bytesUncompressed = new byte[32768];
            while (true)
            {
                Debug.Log("can read: " + zip.CanRead);
                int read = zip.Read(bytesUncompressed, 0, bytesUncompressed.Length);
                if (read <= 0)
                    break;
                zip.Write(bytesUncompressed, 0, read);
            }
        }
    }
}

A: It is unclear to me how you are populating your stream s, but all you may need is to roll back your stream's position prior to reading it:
s.Seek(0, System.IO.SeekOrigin.Begin);

A: The example pattern is fairly painful, let me give you a "better(tm)" pattern to use.
byte[] GetBytesFromCompressedStream(MemoryStream src)
{
    byte[] uncompressedBytes = null;

    using (MemoryStream dst = new MemoryStream())
    using (ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(src))
    {
        byte[] buffer = new byte[16 * 1024];
        int read = -1;

        while((read = zip.Read(buffer, 0, buffer.Length)) > 0)
        {
            dst.Write(buffer, 0, read);
        }

        uncompressedBytes = dst.ToArray();
    }

    return uncompressedBytes;
}