text:
Q: Convert a HashMap> to HashMap> I have a HashMap<Integer, List<String>> as input,  e.g :
3  :  a, b, c
6  :  b, c
9  :  a, c
12 :  b ,c

I want to convert it to HashMap<String, HashSet<Integer>> for e.g.
a : 3, 9
b : 3, 6, 12
c : 3, 6, 9, 12

How can it be done ?

A: This should help
Map<Integer, List<String>>  initMap = new HashMap<>();

initMap.put(3, new ArrayList<String>(Arrays.asList("a", "b", "c")));
initMap.put(6, new ArrayList<String>(Arrays.asList("b", "c")));
initMap.put(9, new ArrayList<String>(Arrays.asList("a", "c")));
initMap.put(12, new ArrayList<String>(Arrays.asList("b", "c")));

Map<String, Set<Integer>> finalMap = new HashMap<>();

initMap.forEach((key, values) -> {
  values.forEach(val -> {
    Object o = finalMap.containsKey(val) ?
             finalMap.get(val).add(key) :
             finalMap.put(val, new HashSet<Integer>(Arrays.asList(key)));
  });
});

A: Here's an example, along with tests:
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

import org.junit.Assert;
import org.junit.Test;

public class SoTests {
    @Test
    public void so01() {
        HashMap<Integer, List<String>> input = new HashMap<>(4);
        input.put(3, Arrays.asList("a", "b", "c"));
        input.put(6, Arrays.asList("b", "c"));
        input.put(9, Arrays.asList("a", "c"));
        input.put(12, Arrays.asList("b", "c"));

        HashMap<String, HashSet<Integer>> output = process(input);

        HashMap<String, HashSet<Integer>> expectedOutput = new HashMap<>(3);
        expectedOutput.put("a", new HashSet<>(Arrays.asList(3, 9)));
        expectedOutput.put("b", new HashSet<>(Arrays.asList(3, 6, 12)));
        expectedOutput.put("c", new HashSet<>(Arrays.asList(3, 6, 9, 12)));
        Assert.assertEquals(expectedOutput, output);
    }

    private HashMap<String, HashSet<Integer>> process(HashMap<Integer, List<String>> input) {
        return input.entrySet().stream() //
            .flatMap(entry -> entry.getValue().stream().map(s -> new IntegerAndString(entry.getKey(), s))) //
            .collect(Collectors.groupingBy(IntegerAndString::getString, HashMap::new, //
                Collectors.mapping(IntegerAndString::getInteger, Collectors.toCollection(HashSet::new))));
    }

    private static class IntegerAndString {
        private final Integer integer;
        private final String string;

        IntegerAndString(Integer integer, String string) {
            this.integer = integer;
            this.string = string;
        }

        Integer getInteger() {
            return integer;
        }

        String getString() {
            return string;
        }
    }
}

The actual logic is in the process method. The ugly IntegerAndString class is due to a lack of tuple types in Java. You can use some library like javatuples instead.

A: Just looking at Duplicate link.
This is the final solution I have
 private HashMap<String, HashSet<Integer>> process(HashMap<Integer, List<String>> input) {
     return input.entrySet().stream()
             .flatMap(entry -> entry.getValue().stream().map(s -> new SimpleEntry<>(entry.getKey(), s)))
             .collect(Collectors.groupingBy(SimpleEntry::getValue, HashMap::new,
                 Collectors.mapping(SimpleEntry::getKey, Collectors.toCollection(HashSet::new))));
     }

A: Map<Integer, List<String>> intHM = new HashMap<Integer, List<String>>();

    intHM.put(3, new ArrayList<String>(Arrays.asList("a","b","c")));

    intHM.put(6, new ArrayList<String>(Arrays.asList("b","c")));

    intHM.put(9, new ArrayList<String>(Arrays.asList("a","c")));

    intHM.put(12, new ArrayList<String>(Arrays.asList("b","c")));

    Map<String,List<Integer>> StringHM = new HashMap<String, List<Integer>>();

    Iterator<Entry<Integer,List<String>>> iterator = intHM.entrySet().iterator();

    while (iterator.hasNext()) {

        Map.Entry<Integer,List<String>> entry = (Map.Entry<Integer,List<String>>) iterator.next();

        for(String str: entry.getValue())
        {

            if (StringHM.containsKey(str))
                StringHM.get(str).add(entry.getKey());
            else
                StringHM.put(str, new ArrayList<Integer>(Arrays.asList(entry.getKey())));

        }
    }

    Iterator<Entry<String,List<Integer>>> StringIterator = StringHM.entrySet().iterator();

    while (StringIterator.hasNext()) {

        Map.Entry<String,List<Integer>> entry = (Map.Entry<String,List<Integer>>) StringIterator.next();

        System.out.print(entry.getKey()+" ");

        for(Integer i: entry.getValue())

            System.out.print(i+" ");

        System.out.println();
    }


text:
Q: Link files from html using fastapi and jinja2 Hi I'm trying to link to an json file from html code using fastapi and jinja2 but the link is not working. I guess i have to tell fastapi how to find the file or something like that.. I get an json (api) answer instad of the file..
{"detail":"Not Found"}

The python code:
from fastapi import FastAPI, Form, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

app = FastAPI()

templates = Jinja2Templates(directory='templates')

@app.get('/data', response_class=HTMLResponse)
async def data(request: Request):
    return templates.TemplateResponse('data.html', {
        'request': request
    })

And the HTML:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">

        <title>Data</title>

                Data downloader:

                Data

A: This code did it..
python:
from fastapi import FastAPI, Form, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount("/json", StaticFiles(directory="json"), name="json")

templates = Jinja2Templates(directory='templates')

@app.get('/data', response_class=HTMLResponse)
async def data(request: Request):
    return templates.TemplateResponse('data.html', {
        'request': request
    })

HTML:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">

        <title>Data</title>

                Data downloader:

                Data

So it was the import and use of StaticFiles that first code dint have

redpajama_set_name: RedPajamaStackExchange


text:
Q: .htaccess still showing .html extension I am using cpanel.
In the public_html folder I have 2 files:
home.html
test.html
home.html links to test.html with:
Test

I do not want to display the .html extension in the browser.
My htaccess file is as follows, but the .html extension is still displayed:
# BEGIN GD-SSL
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_USER_AGENT} ^(.+)$
RewriteCond %{SERVER_NAME} ^education\.mekan\-turk\.com$
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
Header add Strict-Transport-Security "max-age=300"
</IfModule>
# END GD-SSL

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)$ $1.html

A: Could you please try following, based on your shown samples. Trying to fix OP's attempts here. I am assuming that OP wants to hit URL like http://localhost:80/test which should be served by http://localhost:80/test.html here.
Fix is, when you are checking condition  RewriteCond %{REQUEST_FILENAME}.html -f then while Rewriting rule you need NOT to mention .html else it will show it in browser. Also keeping your last 2 rules at top will help here.
# BEGIN GD-SSL
<IfModule mod_rewrite.c>
Options +FollowSymLinks

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [L]
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)$ http://%{HTTP_HOST}/%{REQUEST_URI} [L]

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_USER_AGENT} ^(.+)$
RewriteCond %{SERVER_NAME} ^education\.mekan\-turk\.com$
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
Header add Strict-Transport-Security "max-age=300"
</IfModule>
# END GD-SSL

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Fair warning I haven't tested it yet should work I believe.


text:
Q: Converting List to a String in java for Oracle SQL IN clause I have the below list
ArrayList<String> list1=new ArrayList<String>();
list1.add("abc");
list1.add("bdc");
list1.add("acr");
list1.add("bde");

I wanted to use this list in a select query like below
select * from emp where emp_name in ('abc','bdc','acr','bde')

I am using spring boot rest template and tried with         ArrayList paramsList =new ArrayList() but it failed. Is there a easy way to do instead of converting into a string by iteration.

A: You can join the strings in the list to get what you want:
String values = list1.stream().map(str -> String.format("'%s'", str)).collect(Collectors.joining(","));

And build the query like:
"select * from emp where emp_name in ("+ values +")";

However, as pointed out by @Andreas this approach is susceptible to SQL Injection attacks and syntax errors (if the values in the list have SQL reserved keywords or special characters). Therefore, you should be using prepared statements instead of concatenating strings like this.


text:
Q: Why does this regular expression not match to the end of a comment line? I am using Python's regular expression to parse a file for comment lines. A comment looks like:
.. The comment is here
Not comment
Nope
.. Yup
..
.. This and the above are both comments!

However, my regular expression \.\.\s+.*?& does not match these lines. I feel as though I am doing something wrong regarding the end of the line and the ampersand.

A: *

*the [.] is not correct, it matches literal period.

*you should add ^ too, otherwise your regex matches foobar.. blah too.

*the .*?$ (I guess you had a typo & should be $)doesn't make much sense...

this should do:
^\.\.\s+.*

A: A few things:

*

*The end-of-line anchor is a dollar sign, not an ampersand. If you're reading this text line-by-line, you don't really need it. Just make your match greedy: .*.

*[.] is a character group containing a literal dot. It's not the same as ..

The correct regex would look something like this: \.{2}\s+(.*).
I would just do it without regex:
for line in file:
    if line.startswith('..'):
        comment = line[2:].strip()

A: The character for end-of-line is $, not &.
Here's a simple regular expression to match such lines:  r'\.\..*$'


text:
Q: Apple Watch invalid UIDeviceFamily I've written an Apple watch application. When I was working at local, it was perfect. But now I am trying to build it with a signed provision. My provision and info.plist's are correct, I checked twice.
I can send the standard iOS application to my device. But When I am trying to send to Apple watch application from IPhone->Apple Watch... I take this error,

Watchkit:validateWatchKitApplicationInfoDictionary, invalid
  UIDeviceFamily value... Error Domain=com.apple.watckit.errors Code=7
  "invalid info dictionary"

Does anyone knows the solution of this error?


text:
Q: Error in deployment of a flask web app with MongoDB Atlas i am new in developing web apps so i might get confused a lot of times!
The problem is this:
I was developing with Pycharm son sort of basic social network, and at first when you sign up the users were created in local folder as JSON files and then i look foward to make a deployment, and i did it without problem using PythonAnywere (PA). Lets call my .py file "server.py" where i have the whole thing.
Then i started looking for some cloud service and I ended modifying everything in order to work with Mongodb Atlas and it was a complete success. I made a lot of local test using Pycharm and everything is OK, the users are now created on cloud service.
My problem is that i would like to make a deployment test with that Mongodb service version, and i was trying to use (PA) again but this time its give me a lot of errors.
Note: i already install all the requirements in (PA) from pip freeze requirements.txt
Is there a problem with PA and MongoDB? is ther any other better option?
Should it run ok if the first version of "server.py" was ok?
I just replaced that file with new one, that was runnning perfect on localhost.
If you need more info just tell me, i am very new in this.
Thanks a lot


text:
Q: Alterantive to FileToGoogleCloudStorageOperator So I found FileToGoogleCloudStorageOperator which helps in moving files from my local system to Google Cloud. But is there a similar airflow operator to move entire directory to Google Cloud.

A: Not an official one, but it'd be pretty easy to create one, you can use reuse most of the logic from https://github.com/apache/incubator-airflow/blob/master/airflow/contrib/operators/file_to_gcs.py
You can use the same GoogleCloudStorageHook it is using to upload a single file and just iterate over the directory, uploading all the files. This is what any directory upload functions for GCS would be do anyway.
Depending on the amount of files you routinely need to upload, you might be better off breaking the upload into multiple tasks.  That way, should one upload task fail you don't have to restart the upload for all files. It depends on your use case though.


text:
Q: Saving multiple pages for raster maps I need to save multiple pages of raster maps. I use "trellis.device" to save them, but it failed. See the below example for details.
library(raster)
r1 <- raster(nrow=10, ncol=10)
r1[] <- sample(c(0,1),100,replace=TRUE)

r2 <- raster(nrow=10, ncol=10)
r2[] <- sample(c(0,1),100,replace=TRUE)

sp1 <- stack(r1,r2)

library(rasterVis)

## save as pdf with two pages (It works in this way)
trellis.device(pdf, file="Test.pdf")
levelplot(sp1,col.regions=c("grey","darkgreen"))
levelplot(sp1,col.regions=c("grey","darkgreen"))
dev.off()

## save as pdf (It doesn't work when including a for loop)
trellis.device(pdf, file="Test.pdf")
for (i in 1:2){
levelplot(sp1,col.regions=c("grey","darkgreen"))}
dev.off()

A: This is listed in the R FAQ. By default R does not print values returned inside of loops the way it does when you enter a single value at the command prompt. you need to explicitly print the plot.
trellis.device(pdf, file="Test.pdf")
for (i in 1:2){
print(levelplot(sp1,col.regions=c("grey","darkgreen")))}
dev.off()


text:
Q: SQL Query to LINQ C# [Joining multiple table] I am working on this query in my sql server
select a.care_type_id, a.description,
isChecked = case when b.care_type_id is null then 'false' else 'true' end
from caretype a
left join patientinsurancetacitem b on a.care_type_id = b.care_type_id and
b.tac_id = 1

I want to translate the query into LINQ. However, I am having trouble with the and operator. I have this code so far;
from a in context.CareTypes
join b in context.PatientInsuranceTACItems on a.care_type_id equals
b.care_type_id into x
from xx in x.Where(w => w.tac_id == 1).DefaultIfEmpty()
                   select new {
                   isChecked = (b.care_type_id == null ? false : true),
                   care_type_id = a.care_type_id,
                   description = a.description}

And, also, I cannot get the b that I equated in isChecked variable. From where will I start modifying in order to get the same result as my sql query? In where I got it wrong?

A: Try this
from a in context.caretype
join b on context.patientinsurancetacitem
      on new { CA = a.care_type_id, CB =  1}  equals
         new { CA = b.care_type_id, CB =  b.tac_id}
      into tmp from b in tmp.DefaultIfEmpty()
select new
{
    care_type_id = a.care_type_id,
    description = a.description,
    checked = (b != null) // Or ((b == null) ? false : true)
}

Also check this StackOverflow answer.

A: The very simple example about joining on multiple columns is ;
from x in entity1
             join y in entity2
             on new { X1= x.field1, X2= x.field2 } equals new { X1=y.field1, X2= y.field2 }


text:
Q: Exclude page name from loop I'm currently using this loop:
if (is_single() || is_page() ) :
  if (have_posts() ) :
    while (have_posts() ) :
    the_post();

How can I exclude multiple pages within the loop?
For an example, I want to exclude pages example.com/music and example.com/contact.
EDIT:
I've done the way G.M provide, but my music and contact pages keeps loading after apply.
<?php if (is_single() || is_page() ) : if (have_posts() ) : $exclude_pages = array('music', 'contact'); while (have_posts() ) : if ( is_page() && ! empty($exclude_pages) && (
      in_array($post->post_name, (array)$exclude_pages) ||
      in_array($post->post_name, (array)$exclude_pages)
  ) ) continue; the_post(); ?>
<meta name="description" content="<?php the_content_limit(150)?>" />
// loop continues
<?php endwhile; endif;
elseif (is_home() ): ?>
// loop continues

<?php endif; ?>

<?php if( is_page( 'music' )) { ?>
<meta property="og:image" content="" />
//loop continues
<?php } ?>

So to clarify:
I'd like to exclude some meta tags that i'm generating via a loop in the header.php
Now with my loop, all pages and post get affected by the loop.
So I don't want the pages music and contact to have the same header tags from the loop in header.php.

A: An alternative way is putting the unwanted pages in an array. Useful for storing them in a option or in a serialized custom field.
$exclude_pages = array('music', 'contact');
// can be something like this: $exclude_pages = get_option('exclude_pages');

if ( have_posts() ) : while ( have_posts() ) : the_post();
  if ( is_page() && ! empty($exclude_pages) && (
      in_array($post->post_name, (array)$exclude_pages) ||
      in_array($post->post_title, (array)$exclude_pages)
  ) ) continue; // skip

  // the rest of your loop here

Edit
To also exclude some post type you can use:
$exclude_pages = array('music', 'contact');
$exclude_post_types = array('music', 'any_here');

if ( have_posts() ) : while ( have_posts() ) : the_post();
  if ( is_page() && ! empty($exclude_pages) && (
    in_array($post->post_name, (array)$exclude_pages) ||
    in_array($post->post_title, (array)$exclude_pages)
  ) ||
  ( is_single() && in_array(get_post_type(), (array)$exclude_post_types) ) ) continue;

A: is_page() will take a parameter for the page slug. That plus some logic operators should do it.
if (
  (is_single() || is_page())
  && (
    !is_page('music')
    || !is_page('contact')
  )
)

Note: it is very easy to get the logic wrong on these, and I didn't test that. It may not be quite right but I am sure it is close.


text:
Q: Dark Theme in android 9.0 changes my app layouts ugly I am just designing my layout without expecting any of the problems, but one-day android 9.0 launched and I brought the phone and installed my app in it and tried my app opening it with night mode ON and I started to see white color layout changes in dark and my minds goes block. I want to know how to disable the theme.
I tried changing themes, changing the background colors none of those works

<RelativeLayout
        android:layout_width="190dp"
        android:layout_height="200dp"
        android:layout_marginTop="-15dp"
        android:layout_below="@+id/tableTxt"
        android:background="@drawable/table_no_orders_border"
        android:theme="@style/ThemeOverlay.AppCompat.Light"
        android:layout_centerHorizontal="true">

    <android.support.v7.widget.CardView
            android:id="@+id/cv_one_login"
            android:layout_width="189dp"
            android:layout_height="199dp"
            android:layout_centerHorizontal="true"
            android:elevation="10dp"
            app:cardCornerRadius="1dp"
            app:cardElevation="10dp"
            android:layout_marginTop="0.1dp">

            <android.support.v4.widget.NestedScrollView
                    android:id="@+id/sv1"
                    android:layout_width="match_parent"
                    android:layout_height="147dp"
                    android:scrollbars="vertical"
                    android:scrollbarSize="10dp"
                    android:isScrollContainer="true">
                <TextView
                        android:id="@+id/tableItems"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:text="@string/table"
                        android:layout_marginStart="5dp"
                        android:layout_marginTop="13dp"
                        android:textColor="@color/TextcolorforBlack"/>
            </android.support.v4.widget.NestedScrollView>
            <TextView
                    android:id="@+id/totalTableBill"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:text="@string/total_bill"
                    android:textColor="@color/SettingsColor"
                    android:layout_below="@id/sv1"
                    android:textAlignment="gravity"
                    android:gravity="bottom"
                    android:layout_marginStart="5dp"/>
        </RelativeLayout>
    </android.support.v7.widget.CardView>
</RelativeLayout>

I need my layout as it is designed. even if the theme got applied also it should be the same.

A: You can change App theme to any theme in the App Manifest file like,
<application
    android:theme="@android:style/Theme.Holo"/>

<application
    android:theme="@android:style/Theme.Holo.Light"/>

<application
    android:theme="@android:style/Theme.Black"/>

<application
    android:theme="@android:style/Theme.DeviceDefault"/>

Or you can customize theme in the styles.xml file and then Apply in Manifest
<style name="AppBaseTheme" parent="android:Theme.Holo.Light"/>
<style name="AppTheme" parent="AppBaseTheme"/>

Now in Manifest file
<application
    android:theme="@style/AppBaseTheme"/>

You can also preview themes in the preview window in Android Studio.


text:
Q: Bulk insert of list of dictionary I have defined my model class like below:
class MedicalPlan(Base):
    __tablename__ = "medical_plans"

    id = Column(Integer, nullable=False , primary_key=True)
    issuer_id = Column(Integer, ForeignKey('issuers.id'), nullable=False)
    service_area_id = Column(Integer).... and so

I have created a session using below code using which I am doing most of my sql operations:
def get_session():
    engine = create_engine('postgresql+psycopg2://postgres:postgres@localhost/db')
    Session = sessionmaker(engine)
    return Session()

I have my list of dictionary which I want to insert as a bulk insert.
In documentation, I can see where I can insert using something like below:
connection.execute(table.insert(), [
        {'id':'12','name':'a','lang':'eng'},
        {'id':'13','name':'b','lang':'eng'},
        {'id':'14','name':'c','lang':'eng'},
    ]
)

My question is how can I perform such operation using my model class in the way I have provided the mapping.
Something like this does not work:
conn.execute(MedicalPlans.insert(), list_of_dict)

A: The table of the mapped class should be available as
MyTable.__table__

hence MedicalPlan.__table__.insert() should work.

There are other options in the question linked to by Ilja, but most are not as efficient - bulk_insert_mappings would come close.


text:
Q: mysql-connector-python cannot work with GBK string "赵孟頫" Look at the code in python shell:
>>> s = u'赵孟頫'.encode('gbk')
>>> s
'\xd5\xd4\xc3\xcf\xee\\'

The last byte of '赵孟頫' is \x5c, the same as backslash. And it causes a sql error.
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''?????\\')' at line 4

Here is my code:
# db is mysql.connector object
sql = '''
    INSERT INTO scraped_products(
        site_prd_id,site_id,brand)
    VALUES(
        %(site_prd_id)s,%(site_id)s,%(brand)s)
    '''
dat = {
    'site_prd_id' : 'test',
    'site_id' : 1,

    'brand' : u'赵孟頫'.encode('gbk'),
}
self.db.ping(True, 3, 1)
self.db.cursor().execute(sql, dat)

A: I have a solution which would need some extra work to get it working. The following code example is converting the data into a MySQL Hexadecimal Literal and sends it to MySQL without escaping, quoting or converting it. It's a bit a different way of executing queries, but I hope it will serve for now:
import mysql.connector

cnx = mysql.connector.connect(database='test', user='root',
                              charset='gbk', use_unicode=False)
cur = cnx.cursor()

cur.execute("DROP TABLE IF EXISTS gbktest")
table = (
    "CREATE TABLE gbktest ("
    "id INT AUTO_INCREMENT KEY, "
    "c1 VARCHAR(40)"
    ") CHARACTER SET 'gbk'"
)
cur.execute(table)

def gbk_to_hexstr(value):
    """Convert value to Hexadecimal Literal for MySQL
    """
    return "0x{0}".format(''.join(
        ["{0:x}".format(ord(c)) for c in value.encode('gbk')]))

# Convert your Unicode data using gbk_to_hexstr
data = {
    'c1' : gbk_to_hexstr(u'赵孟頫'),
}

# Use MySQLCursor.execute() _not_ passing data as second argument
cur.execute("INSERT INTO gbktest (c1) VALUES ({c1})".format(**data))
cur.execute("SELECT c1 FROM gbktest")

# Print the inserted data as Unicode
for row in cur:
    print(row[0].decode('gbk').encode('utf8'))


text:
Q: Vector proof to show the line connecting two points on a triangle is parallel to a side. If $X$ and $Y$ are points on sides $AB$ and $AC$ of a triangle $ABC$ and $\dfrac{AX}{AB}=\dfrac{AY}{AC}$, then $XY\parallel BC$.
I'm supposed to prove this using vectors, but we haven't done too much of this yet, and I'm at a loss.

A: let $t=\frac{AX}{AB}=\frac{AY}{AC}$
then $\vec{XY} = \vec{XA}+\vec{AY} = t(-\vec{AB}+\vec{AC})      $
and $\vec{BC} =  -\vec{AB}+\vec{AC} $
so the two vectors are scalar multiples of each other, hence they are parallel.

A: Hint: Assume that $$\dfrac {AX}{AB} = \dfrac{AY}{AC} = \lambda.$$
It is easy to prove that $$\vec {XY} = \vec {AY} - \vec{AX}.$$
Similarly, $$\vec{BC}  = \vec{AC} - \vec{AB}.$$
However,
$$\vec{AX} = \lambda \vec{AB} \text{ and } \vec{AY} = \lambda \vec{AC} \quad \text{(why?)}$$
Combine all the facts above and you will reach the result.


text:
Q: Very Weird Behaviour of Listview I never seen something like that before but from last few days I am experiencing very peculiar behavior of the Listview and until now I am not been able to isolate the issue.
I only paste the code which I think is necessary and later I will tell you my problem.
/* tell adapter that data is done and stop the more loading progress bar*/
public void setDataChanged(boolean type)
{
    isLoadingData = false;
    notifyDataSetChanged();
}

/* If loading is going on size of the adapter will increase to show the additional progress bar*/
@Override
public int getCount() {
    int size = friendsModels.size();
    if (isLoadingData) {
        size += 1;
    }
    Log.i("size", String.valueOf(size));//to check size

    return size;
}
/* set loading true and page number of the data items*/
public void setLoadingData(boolean isLoadingData, int page) {
    this.isLoadingData = isLoadingData;
    this.page = page;
    notifyDataSetChanged();
}

/* MAX_ITEM number of item returning from rest webservice per page*/
@Override
public int getItemViewType(int position) {
    if(isLoadingData && position%MAX_ITEM==0 && position>0)
    {
        if(position/MAX_ITEM==page+1)
        return 1;
    }
    return 0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    Log.e("getView", "getView");

    EventHolder eventHolder;
    int type = getItemViewType(position);
    LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if(convertView==null){
        eventHolder = new EventHolder();
        if(type==0)
        {
            convertView = li.inflate(R.layout.friends_list_items, parent,false);

            eventHolder.name   = (TextView)convertView.findViewById(R.id.textview_friend_name);

            convertView.setTag(eventHolder);

        }
        else if(type==1)
        {
            convertView = li.inflate(R.layout.progress_dialog, parent,false);
            eventHolder.progress = (RelativeLayout)convertView.findViewById(R.id.progress_layout);
            convertView.setTag(eventHolder);
        }
    }
    else
    {
        eventHolder = (EventHolder) convertView.getTag();
        if(type==0)
        {
            setFriends(eventHolder, position);
        }
    }

    return convertView;
}

Now onScroll method-
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
        int visibleItemCount, int totalItemCount) {
    if(firstVisibleItem + visibleItemCount >= totalItemCount && !loading && totalItemCount%6==0 && totalItemCount>0 && NetworkUtil.isNetworkAvailable(activity))
    {
        loading = true;
        friendsAdapter.setLoadingData(true,pageNo);
        ControllerRequests.getPeople(FragmentClass.this, ++pageNo, search.getText().toString());
    }
}

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}

Though everything is working fine when there are like 5 or more items but as the item size decreases let's say 1 or 2 then sometimes the getView method don't get called though log info is showing me getCount = 1 or 2  but getView just don't get called. There is no pattern, I mean sometimes 5 times getView get called it works fine then suddenly not and like that.

A: This is a strange check:
if(firstVisibleItem + visibleItemCount >= totalItemCount && !loading &&
                totalItemCount%6==0 && totalItemCount>0 &&
                                  NetworkUtil.isNetworkAvailable(activity))

I am referring to:
totalItemCount % 6 == 0

So, unless the total number of items will always be a multiple of 6, this check will prevent friendsAdapter.setLoadingData(true,pageNo); from being called. That's why the statement notifyDataSetChanged(); that resides inside setLoadingData(boolean, int) will not be executed whenever totalItemCount % 6 != 0.
Edit:
I also cannot think of a situation where this will be true:
firstVisibleItem + visibleItemCount > totalItemCount

You can go with the following to check if the user has reached the end of the list:
firstVisibleItem + visibleItemCount == totalItemCount


text:
Q: How does one overcome overlapping points without jitter or transparency in ggplot2 I am starting to use ggplot2. I have some small n (about 30 or so) granular data with lots of overlap. Neither jitter nor alpha (transparency) are suitable. Instead a stripchart with stack and offset do it best but I do not know how to do it in ggplot2. Do you know?
To see what the end result should be click on this graphic.
Here is the script I used a few years ago.
stripchart(SystData$DayTo1Syst~SystData$strain,vertical=TRUE,method="stack",pch=19,offset=.3,xlab="Strain",main="Rapidity of Systemic Disease Onset",ylab="Days post inoculation")

A: You can use position_dodge.
df <- data.frame(gp = rep(LETTERS[1:5], each =8),
                 y = sample(1:4,40,replace=TRUE))
qplot(gp,y,data=df,order=y,position=position_dodge(width=0.5))

alt text http://img100.imageshack.us/img100/8760/dodgel.png

A: # your data
df <- data.frame(gp = rep(LETTERS[1:5], each =8), y = sample(1:4,40,replace=TRUE))
# calculate offsets
df <- ddply(df, .(y, gp), transform, offset = (1:length(gp)-1)/20)
qplot(gp, y, data=df) + stat_identity(aes(as.numeric(gp)+offset)) + theme_bw()

A: You want to use geom_dotplot from ggplot2
you will probably want to use:
ggplot(insert your arguments here) + geom_dotplot(binaxis = "y", stackdir = "center")

Hope this helps. The results will look really clean which is what I think you want.


text:
Q: Sencha Touch 2 Nested list not displayed I'm trying to display NestedList with json on my hard disk, but it is not displayed. What am I doing wrong? No bugs in Chrome. (Chrome open with Applications / Google \ Chrome.app / Contents / MacOS / Google \ Chrome - allow-file-access-from-files). I get a blank screen without a single error in the console. If I comment fullscreen: true, in MyPanel.js I get clear NestedList without any data.
Servlet.json
{
    "stream":[{
            "post_id": "1",
            "post_type": "text",
            "post_thumb": "bla1"
        }]
}

MyPanel.js
Ext.define('MyApp.view.MyPanel', {
    extend: 'Ext.dataview.NestedList',
    alias : 'widget.MyPanel',

    config: {
        store : 'Storere',
        title: 'NestedList Example',
        detailCard: {
            html: 'You can see detail information here!'
        }
    }
});

Storere.js
Ext.define('MyApp.store.Storere', {
    extend: 'Ext.data.TreeStore',

    config: {
        model: 'MyApp.model.MyModel',
        defaultRootProperty : 'stream',
        proxy: {
            type: 'ajax',
            url: '.\/app\/Servlet.json',
            reader: {
                type:         'json',
                rootProperty: 'stream'
            }
        }
    }

});

MyModel.js
Ext.define('MyApp.model.MyModel', {
    extend: 'Ext.data.Model',
    config: {
        fields: [
            {name:'post_id', type: 'string' },
            {name:'post_type', type: 'string' },
            {name:'post_thumb', type: 'string' }
        ]
    }
});

TheWorld.js
Ext.define('MyApp.controller.TheWorld', {
    extend : 'Ext.app.Controller',

    config: {
        profile: Ext.os.deviceType.toLowerCase(),
        control: {
            'MyPanel': {
                activate: 'onActivate',
                leafitemtap: 'onDetailDisplay'
            }
        }

    },

    onActivate: function() {
        console.log('Main container is active');
    },

    onDetailDisplay: function(nestedList, list, index, target, record) {
        console.log('onDetailDisplay is active');
        var detailCard = nestedList.getDetailCard();
    },

    onItemTap: function(view, list, index, target, record, event) {
        console.log('Item was tapped on the Data View');
    },

    init: function() {
        console.log('Controller initialized');
    },
});

UPD:

A: You need to change NestedList config to following.
config: {
    store : 'Storere',
    //displayField:'post_type',
    title: 'NestedList Example',
    listConfig          : {
        itemTpl: '{post_type}'
    },
    detailCard: {
        html: 'You can see detail information here!'
    }
}

There is this displayField config of NestedList where you can specify which field to be used to set title and item text . By default it is set to text but you can specify it to be one of your model field. If you are overriding getItemTextTpl or getTitleTextTpl, this config will be ignored.
Plus there's listConfig config option available where you can mention itemTpl config. As json is having multiple fields with image and text nodes I assume you want to show that too.
So you can have listConfig something like following :
    listConfig: {
        itemTpl: '
{post_type}
'
    },

Reasons of list was not getting displayed might be-

*

*Store is not loaded with proper data. ( To make sure inspect Network tab in chrome to see if Servlet.json present.

*displayField and/or listConfig not mentioned.


text:
Q: Set break points in Tornado app How could I set a break point in my tornado app?
I tried pdb, but Tornado app seams to be ignoring my pdb.set_trace() command in my app.

A: If you are running your app using foreman you would set you environment variable in .env file in root project folder.
Setting the below env variable in my .env file did the tick form me.
PYTHONUNBUFFERED=true
Now I can set code breakpoints in my app, and also print output to server logs while running the app using foreman.

A: Where did you put pdb.set_trace()...? This works for me:
#!/usr/bin/python
# -*- coding: utf-8 -*-

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import pdb

from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        greeting = self.get_argument('greeting', 'Hello')
        reself.write(greeting + ', friendly user!')

if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[(r"/", IndexHandler)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    pdb.set_trace()
    tornado.ioloop.IOLoop.instance().start()

Session:
$ python test.py
> /home/mariusz/Dokumenty/Projekty/Testy/test.py(24)<module>()
-> tornado.ioloop.IOLoop.instance().start()
(Pdb) break 16
Breakpoint 1 at /home/mariusz/Dokumenty/Projekty/Testy/test.py:16
(Pdb) continue
> /home/mariusz/Dokumenty/Projekty/Testy/test.py(16)get()
-> self.write(greeting + ', friendly user!')
(Pdb) step
--Call--
> /usr/local/lib/python2.7/dist-packages/tornado/web.py(497)write()
-> def write(self, chunk):
(Pdb) step
> /usr/local/lib/python2.7/dist-packages/tornado/web.py(512)write()
-> if self._finished:
(Pdb) step
> /usr/local/lib/python2.7/dist-packages/tornado/web.py(516)write()
-> if isinstance(chunk, dict):
(Pdb)

After putting continue in above code debugger stopped, because I had to poll http://localhost:8000/ in browser to have RequestHandler function actually called.


text:
Q: TypeScript - Return type based on input type I have a union type that can be narrowed based on a kind property. I would like to create a function whose input is one of those kinds ("Foo" or "Bar"), and whose output is a function that accepts the matching type as input (FooType or BarType).
I tried implementing such a function (getHandler) as follows:
type FooType = { kind: "Foo", fooMsg: string }
type BarType = { kind: "Bar", barMsg: string }

function getHandler(kind: "Foo" | "Bar") {
  switch (kind) {
    case "Foo":
      return { handle: (foo: FooType) => console.log(foo.fooMsg) };
    case "Bar":
      return { handle: (bar: BarType) => console.log(bar.barMsg) };
  }
}

const fooBar: FooType | BarType = getFooOrBar(); // return type is 'FooType | BarType'
getHandler(fooBar.kind).handle(fooBar);

But this throws an error on the call to handle(fooBar):

TS2345: Argument of type 'FooType | BarType' is not assignable to parameter of type 'never'.

I understand the error, but I'd like to know if there's a way to communicate to TypeScript that this will not fail (without resorting to using any or //@ts-ignore).
Specifically, because getHandler was called using fooBar's kind, I know that the handle function will be able to operate on fooBar. Is there a way express that fact in TypeScript?

A: I got rid of the {handle: ...} function wrapper, but it should work in any case. The important bit is in the signature of getHandler.
In particular, in the usage of mapped types to build the Handlers<...> generic type:
type Handlers<TypesWithKind extends { kind: string }> = {
    [T in TypesWithKind as T["kind"]]: (obj: T) => void;
}

I could not figure out a way to avoid a (albeit safe) cast in the return statements in the getHandler method, but I think it should be ok.
Link to TS Playground
type FooType = { kind: "Foo", fooMsg: string }
type BarType = { kind: "Bar", barMsg: string }

type FooBarType = FooType | BarType;

// see: https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#key-remapping-via-as
type Handlers<TypesWithKind extends { kind: string }> = {
    [T in TypesWithKind as T["kind"]]: (obj: T) => void;
}

type FooBarHandlers = Handlers<FooType | BarType>;

function getHandler<T extends (FooType | BarType)['kind']>(kind: T): FooBarHandlers[typeof kind] {
    switch (kind) {
        case "Foo":
            // here TS is confused about the type of kind. It is still recognized as 'Foo' | 'Bar' instead of simply Foo.
            // I bail out with a cast, which is kind of bummer, but I suppose we are more interested in the calling part
            return ((foo: FooType) => { console.log(foo.fooMsg); }) as FooBarHandlers[typeof kind];
        case "Bar":
            return ((bar: BarType) => {console.log(bar.barMsg); }) as FooBarHandlers[typeof kind];
        default:
            throw new Error('UnexpectedValue!');
    }
}

const aFoo: FooType | BarType = {
    kind: "Foo", fooMsg: 'Message'
};
const fooHandler = getHandler(aFoo.kind)
fooHandler(aFoo);

const aBar: BarType = {
    kind: "Bar", barMsg: 'Message'
};
const barHandler = getHandler(aBar.kind);
barHandler(aBar);

// you could also simply use an object:
const handlers: FooBarHandlers = {
    Foo: (foo: FooType) => { console.log(foo.fooMsg); },
    Bar: (bar: BarType) => {console.log(bar.barMsg); }
};
handlers[aFoo.kind](aFoo);


text:
Q: How to disable gcc warning "floating constant exceeds range" and "floating constant truncated to zero"? These obnoxious warnings are on-by-default in current gcc, and I can't find which option is needed to disable them. They're generating warning-spam and preventing compiling with -Werror in code where the behavior gcc warns about is intentional (and comes from general-purpose macros that could not easily avoid generating such constants).

A: After digging through the GCC source code, I found that the warnings you've described are part of the -Woverflow option. So just turn off that warning.
By the way, this comment is in the code for the warning:

Both C and C++ require a diagnostic for a floating constant
  outside the range of representable values of its type...
  We also give a warning if the value underflows.

A: In GCC 4.8, each warning comes with a clear indicator of which flag enables it:
floating constant exceeds range of 'double' [-Woverflow]

Good job, GCC devs.


text:
Q: Deleting element and changing element property in an Array of objects So there is an array of object called employees that has employee's credentials.
I am supposed to delete the object if the employee's name is Theo, and if the employee's name is Lorie I should change the department's property to 'HR'
I've tried using a for loop to go through the objects in the array and change their properties. but it would not return the iterated array.
maybe I need to use the .reduce() method
Here is the code I've tried

A: It should be working!
Your array of objects.
var employees = [
 {
  "firstName": 'Von',
  "lastName": 'budibent',
  "email": "email@mail.com",
  "departement": "Sales"
 },
 {
  "firstName": 'Theo',
  "lastName": 'Trill',
  "email": "email@mail.com",
  "departement": "Services"
 },
 {
  "firstName": 'Lorie',
  "lastName": 'Trill',
  "email": "email@mail.com",
  "departement": "Research and Development"
 }
];

Then you need to filter by firstName and then mapping the data.
var adjustedEmployees = employees
 .filter(employee => employee.firstName !== 'Theo')
 .map((employee) => {
   if (employee.firstName === 'Lorie') employee.departement = 'HR';
   return employee;
 });

A: //I needed to use a function with no parameters, I figured out how to do it.
Solved question

A: //Remove employe with firstname 'Theo'
var result = employees.filter(employee => employee.firstName !== 'Theo');
//Change department of Lorie to 'HR'
result.forEach(el => {
  el.departement = el.firstName === 'Lorie' ? 'HR' : el.departement
})


text:
Q: Transposing column into rows and create new column? I have the following table
Col_1 Col_2 Col_3     Date
 0.1   0.2   0.3   2013-08-13
 0.4   0.5   0.6   2013-08-12

I want the following:
   Date          New Column        Value
2013-08-13        Col_1             0.1
2013-08-13        Col_2             0.2
2013-08-13        Col_3             0.3
2013-08-12        Col_1             0.4
2013-08-12        Col_2             0.5
2013-08-12        Col_3             0.6

So, I am not only transposing the table but also adding a new column which tells me column name from which the values are coming. I tried doing a UNION..but it did not work :(
Thanks!

A: You could it like this:
INSERT INTO NEW_TABLE_NAME (Date, `New Column`, Value)

SELECT    DATE, 'Col_1', Col_1

FROM      OLD_TABLE_NAME

UNION ALL

INSERT INTO NEW_TABLE_NAME (Date, `New Column`, Value)

SELECT    DATE, 'Col_2', Col_2

FROM      OLD_TABLE_NAME

UNION ALL

INSERT INTO NEW_TABLE_NAME (Date, `New Column`, Value)

SELECT    DATE, 'Col_3', Col_3

FROM      OLD_TABLE_NAME;


text:
Q: File added to assets folder after ng serve are not served by Angular I have a file upload control in my Angular project which uploads files to assets/images folder. On the success of file upload, I would like to preview the uploaded file with URL http://localhost:4001/assets/images/filename.jpg. But the URL gives 404 Not Found error even the file exists in assets/images folder.
It seems Angular's assets folder is meant to serve only static files which can be copied on the build. What are all the possibilities to get the dynamic files to display immediately after upload?
I tried to upload files outside the assets folder, but it is not able to serve the file with a relative path.
I would expect the files to be served from Angular App's URL instead of using any CDN services.
Any help/suggestion to use dynamic assets will be highly appreciated.

A: You should use a backend service to handle file uploads, and avoid uploading files to Assets directory.
Essentially you should be posting the image to backend over an API call so the backend (whatever the programming language is) can do the saving part for you (and probably return the image path as the result of same API call).


text:
Q: remote monitoring of linux logs I would like to monitor syslog logs on few dozens of linux servers. In ideal world I'd prefer pull method where central monitoring server collects once per day logs from all machines via ssh, applies common and per-server rules and reports about any unexpected log entries.
Do you have any suggestions?
I would prefer not to use centralized syslog server.
I've looked at ossec, again I would prefer to use ssh for all the communication and would prefer to avoid installing any additional tools on monitored servers

A: Use Splunk. It has several ways to collect and index logs. You can set a cron job to pull the server logs into monitored directories, i.e. /var/log/splunk-logs/{server1, server2, etc}. This is a bit more work then just using syslog, but should be doable.

A: I'm not sure of any turn-key application/solution for this but you could easily use rsyslog on your central monitoring server with the imfile module, which can monitor (and alert via ommail module and conditionals) on arbitrary log files that could be pulled in from your Linux servers via rsync and cron.
I'm using rsyslog as a central syslog server and using ommail to send me alerts on various events from my edge firewall, Squid proxy, core switch, etc.  Works well.

A: If you're wanting some kind of script you could use this http://paste.broner.org/126 (could easily be more dynamic with catching user input, or more elegantly getops). If you don't allow for root to ssh to your hosts from the 'source' machine you could run a script based on the filtering locally on each host, and setup a cron job to watch the logs. Put the dumped new entries to a specific location and have the 'source' machine check that directory via cron, pickup the files, and remove them once copied.
This is a huge work around for not using syslog-ng, or some other syslog server. Is there a reason why you choose to not use one?
Edit: you could also use uuencode, and mail, to mail the files to an address as well if that would be more preferred.

A: Logwatch and Swatch are commonly available tools, and are even installed by default on some Linux distributions. You could install this on each server. This keep a running tail on the logs so that any critical events (eg stuff dying, hack attempts, ssh failures, etc) could be alerted to you immediately via email or some other delivery mechanism.
If you need to avoid installing tools on each monitored system, you could write up some rsync scripts to grab the /var/log directories and sync to a local directory on the central server. Then tell swatch/logwatch to parse those.


text:
Q: Tkinter contents of both widgets visible when overlapping So, I am trying to make a video game in Tkinter (no, I don't want to use PyGame), but I have ran into a bit of a problem.
I have realized that sometimes you may want to have two widgets overlap (e.g. sprite on top of background) but have the contents of both widgets to be visible. For example, I might have a sprite with transparent sections.
How do I set the "background" option of a widget so that there is no visible background?
Note: "you can't do this" answers are acceptable.

A: This is not really posible in Tkinter. But you can set the transparency of the whole window with root.attributes('-alpha', 0.5)
For windows, you can do root.attributes("-transparentcolor", "red"), but again it will be applied to the whole window, not just the single widget.


text:
Q: Older anime featuring girls in powered suits with limited battery life 'illegally' fighting mutated people I can't remember too many specifics, but I think that they all had simplified suits of different colours and were mentored by a lady who was an ex-member, but had a white suit I think? They had occasional run-ins with authorities, likely were fighting these mutated people illegally. I remember at one point a guy was sort of brought in as like an intern/helper to them, with one distinct scene where he accidentally walks into their changing room and says something along the lines of 'I swear I didn't see anything, definitely didn't see your red underwear'.

A: Sounds like Bubblegum Crisis.

*

*The Knight Saber's hardsuits were primarily monochromatic - Priss in blue, Sylvie in white, Nene in pink, Lina in green.

*They had interactions with the police (it's the same world as another series, called AD Police). Nene was a police officer as her "dayjob", and there were important secondary characters on the force.

*The badguys were not mutants, but rather rogue machines called Boomers. The powerful ones did have a material-manipulation power that looked pretty freaky - swelling, bulging, tentacles, extra parts, stuff like that.

*Sylvie, the leader, owned a lingerie shop. They used the shops delivery van as a transporter for the hardsuits and their transforming motorcycles.

*The intern/helper was Mackie, Sylvie's younger brother. He walked in on them suiting up at least once.

Note that there are two versions of Bubblegum Crisis, an OVA from the late 80s, and Bubblegum Crisis Tokyo 2040 a reboot released in the late 90s.
I'd have to rewatch them both, but if I recall correctly the hardsuits were explicitly battery powered in BGC2040 and it was a plot point. I don't recall any particular emphasis on the power source in the original BGC, but its been a long time.
Furthermore, Sylvie's role was much more active in BGC than BGC2040, where she was more like a mentor and/or puppetmaster.
Of the two, it's more likely you're recalling the rebooted series rather than the original.


text:
Q: Simple HTTP POST with an anonymous type as body I can't really find a working example, maybe it is because its simply not possible?
I'd like to take a C# anonymous type object like the following:
var postBody = new
{
   friend = new
   {
      name = "dave",
      last ="franz"
   },
   id = "12345",
   login = "mylogin"
};

and post it to my web service in a simple http POST with the following post body:
{
   "friend" :
   {
      "name" : "dave",
      "last" : "franz"
   },
   "id" : "12345",
   "login" : "mylogin"
};

A: Pretty easy using Json.net. You can get it using the nuget package manager in VS.
var postBody = new
{
   friend = new
   {
      name = "dave",
      last ="franz"
   },
   id = "12345",
   login = "mylogin"
};
var postString = Newtonsoft.Json.JsonConvert.SerializeObject(postBody);
using(var wc = new WebClient())
{
    wc.Headers.Add("Content-Type", "application/json");
    var responseString = wc.UploadString(serviceAddress, "POST", postString);
}

A: If you have HttpClient client:
var request = new HttpRequestMessage(HttpMethod.Post, "<URL>") {
  Content = JsonContent.Create(new {
    Prop = "Value"
  })
};
var response = await client.SendAsync(request);


text:
Q: MongoDB - A detailed change request for webhost While preparing to deploy a MongoDB powered site to a clients web server, their IT department has asked for the following:
(The Linux distribution is CentOS 6)

What I need from yourself is a detailed list of all the changes the
  MongoDB will make to the server.
Install Locations, Config Changes etc.

Can anyone point me to where I would find the information they requested?

A: You should be able to find this information inside the rpm which is built using the following files in the Mongo repository:
https://github.com/mongodb/mongo/tree/master/rpm

A: *

*Install Location : Just use yum for your installation .. all the location is automatically managed mostly (/etc/mongo.conf and /var/lib/mongo for files)
yum install mongo-10gen mongo-10gen-server

Or better still just search for the stable mongoDB db available and install
    yum search mongo

*

*Firewall :  If the database server and application ar ot on the same server .. you need to update firewall to accept connection form mongoDB port
-A INPUT -m state --state NEW -m tcp -p tcp --dport 27017 -j ACCEPT

*To make MongoDb available on boot
chkconfig --levels 235 mongod on

*Am sure your mongoDB config ... please note that replication and replSet is a diffrent ball game
nano -w /etc/mongod.conf

You do not need much for the installation ...its pretty straight forward
Thanks
:)


text:
Q: Google API Client for JS, Gapi.Client vs Gapi.Auth2 Working with the gapi google api client for javascript. We have our current operations working atop gapi.client which we can hold the tokens for the user and simply supply them to gapi.client prior to running operations.
The issue is that for additional functions with other API's, we need to use a process with the gapi.auth2 object that grants the additional permissions. We have the tokens, and the user's consent, but calling gapi.auth2.init seems to force another signin.
Example: gapi.client.setToken({access_token: access});
How can I set the tokens we already have in gapi.auth2 so that I can perform the grant?


text:
Q: How inaccurate is sys.dm_db_partition_stats? I am looking at ways to count rows in several tables on several databases.  In this particular case I am looking for unused and abandoned items.
Several sources source1, source2 recommend using sys.dm_db_partition_stats everything agrees that the count is not perfectly accurate.  MSDN describes row_count as

approximate number of rows in the partition.

I understand if the value is always changing, it might be off by a bit. There are some good arguments on why this small discrepancy really doesn't matter.  But if the value is near zero or none, will it be accurate?
If I use sys.dm_db_partition_stats and I am getting no rows found, do I need to run a second query using COUNT (or something else) to make sure the table is really empty or is the inaccuracy limited to minor fluctuations over minor periods of time?
Clarify
I don't own the data, so I am ethically prohibited from looking at it. If sys.dm_db_partition_stats tells me a table is empty I can't just go open it and see if it really is empty. I need to know if I can depend on the results returned from it.  As pointed out in answers, more information than just this will be required, before deleting.  The table may be used as a temp table, maybe it gets rows written to it and removed, and just always happens to be empty when I look at it.

A: If you're looking for unused or abandoned tables, the number of rows won't be enough. You'd better look into index usage stats:
select database_id, object_id, index_id,
    last_user_seek, last_user_scan, last_user_lookup, last_user_update
from sys.dm_db_index_usage_stats

If you are interested in several methods for tracking table usage, I wrote about it some months ago.

A: I think source1 has the answer.  He (Aaron) states that even when you get an "accurate" count, you could be blocking users trying to write to the table.  As soon as you put your eyes on the result, it could be immediately inaccurate as writers were trying to put data in your table while you blocked them for the accurate count.
So, I believe using partition_stats works fine for what you want.  I wouldn't be afraid to test it though and it might be an interesting test at that.  You could create a db of 1000 empty tables.  Then a routine that constantly inserts and deletes data in random tables.  Then run your partition query and run your count query and compare.
I think what might work best is to use partitions and accumulate your data in a table and over periods of days or weeks, any table with consistently zero results is unused or abandoned.


text:
Q: process a list of post values I am working on a grading program with jsf and hibernate. I have a list of students and a list of criteria for calculations. The criteria list is variable and can be modified by a teacher... I was wondering how I can manage to do the set all grades for all students in a request. Let's say there is Student A and B with criterias X and Y. It should show a table
+---------------------------------------------------+
| Student   | Criteria X        | Criteria Y        |
+-----------+-------------------+-------------------+
| A         | [input for grade] | [input for grade] |
+-----------+-------------------+-------------------+
| B         | [input for grade] | [input for grade] |
+---------------------------------------------------+

I can do that, so far, but the input for grade has not a target in the controller bean since it can't be only student A and B, but could have more/les, same with criteria. I'd love an idea to manage it.
In PHP, I'd work with the Post global variable and fetch this array to get student/criteria from input name and save that grade with the corresponding student/criteria.
JSF - 2.0
[Update 1]

            Nombres y apellidos
                <ui:repeat value="#{cursoController.grupo.criterios.toArray()}" var="criterio">
                    #{criterio.criterioNombre}
                </ui:repeat>

        <ui:repeat value="#{cursoController.grupo.matriculas.toArray()}" var="matricula">
            <h:form rendered="#{matricula.rol.perfil.idPerfil == 69}">

                        <h:inputHidden value="#{matricula.rol.idRol}"/>
                            #{matricula.rol.usuario.persona.personaNombre}

                    <ui:repeat value="#{cursoController.grupo.criterios.toArray()}" var="criterio">

                            <h:inputText style="width: 70px;"/>

                        </ui:repeat>

            </h:form>
        </ui:repeat>


text:
Q: Looking for a story where an intelligent robot tries to avenge the human race This was a short story probably written well before 2010. I have an idea that it might be fairly well-known, but haven't managed to find it.
It started in the not-too-distant future.  There was a permanent research base on the moon run by human staff with one experimental self-aware robot.  I think the robot was called Sam.
The base crew was recalled to Earth at the outbreak of war, which surprised Sam as "he" had been told that war had been eradicated.  The war eventually wiped out the human race and he came to believe that it had been done by hostile aliens, partly because of a well-written sci-fi book he mistook for fact.  He used an automated factory on Earth to build an army of robots and led them on a mission to seek and destroy the aliens.
After centuries of travelling space and wiping out any moderately advanced civilisation they found, some robot researchers discovered that there had been no alien attack and the human race had destroyed itself.  Sam concluded that his own race needed an overriding purpose to keep it from meeting the same fate, so he instructed the researchers to destroy the evidence and continued the impossible revenge quest.

A: To Avenge Man by Lester Del Rey. I read it in The Ninth Galaxy Reader but it has been widely anthologised so you could have read it in lots of different collections.
The story is exactly as you describe. At the end Sam is told:

"There is no Enemy now," the scientist said from behind him. "There can be no doubt. Man was his own destroyer. He killed himself. In a sense, his race was the one we are sworn to kill."

but Sam responds by burning the evidence and the story ends:

Man had failed, like all other races grown from killing strains of animal life. But in dying, he had passed on part of his soul to another race that had been designed without his mighty passions. Somehow he had passed on the driving anger of his spirit to his true children, the robots.
And they had carried on.
The robots had been a created race, a race designed only to serve, able to live in perfect peace and without ambition. They had owned no heritage. But through an accident of fiction and a few dying words, men had left them a rich heritage.
Anger had carried them throughout the stars, and hatred had bridged the spaces between the galaxies.
'You're mistaken, Robert,' Sam said. 'Vengeance is our heritage. Burn the evidence.'
Most of the material was tinder dry, and it caught fire at the first spark. For a few seconds, it was a seething pillar of flame. Then there was only a dark scar on the wood to show the true death of man.


text:
Q: How do you find a minimum of a function with these tools? Let's say I can define a group $G$ acting on a set of combinatorial objects $X$ and I have a function $f: X \to \Bbb{N}$ that I want to find a minimum of in $X$.
Is there a polynomial time algorithm using thes above tools to find a minimum of $X$ starting with an input that is a maximum of $X$?  I mean the running time is $O(P(n))$ where $P$ is some polynomial and $n = f(x_0)$ is a maximum?
If the answer is no or idk, is there if we add more requirements to $G$ and $f$?


text:
Q: How to add extension to doxygen I am new to using doxygen (love it) and I need to be able to document javascript. I looked under the extensions tab on the doxygen homepage and it told of an extension to document javascript; however, I don't know how to add/enable extensions. How do you add extensions and then make sure they are used? Thanks in advance!

A: the extensions for javascript are filters, they parse javascript source code and create a C++ like (not real C++) file which then can be parsed by doxygen!
You can try them out by downloading und running them (they are scripts) and look if they work properly (not yet working for my files..).
If you find one, all you have to do is change the settings in the Doxyfile (configuration file) under FILTER_PATTERNS.
have a look a this:
http://coherent-labs.com/blog/documenting-javascript-with-doxygen/
and this:
https://github.com/schteppe/ammo.js-demos/tree/master/doc


text:
Q: how to use a variable to define a directory flask python3 I have this sample code below, when I try to go to / I get a 404 error, I am trying to use variables as app routes but with no luck
from flask import Flask

app = Flask(__name__)

index_dir = "/"

app.route(index_dir)
def index():
    return "hello_world"

if __name__ == '__main__':
    app.run(host="0.0.0.0")

Any idea on how to make python3 variables to directories

A: You have skipped the decorator symbol (@) before app.route(index_dir). It should be like this to work:
from flask import Flask

app = Flask(__name__)

index_dir = "/"

@app.route(index_dir)
def index():
    return "hello_world"

if __name__ == '__main__':
    app.run(host="0.0.0.0")


text:
Q: Can you selectively sync only some instance of a setting (if that setting is an array)? Question
I'm using GitLens, which has fantastic remote integration. However, I'm not sure if I should have certain remotes sync between machines. For instance:
"gitlens.remotes" : [
    {
       "domain": "bitbucket.corporate-domain.com",
       "name": "Corporate BitBucket",
       "type": "Bitbucket Server",
    },
    {
       "domain": "github.com/personal",
       "name": "Personal GitHub",
       "type": "GitHub",
    }
]

Now, I know that one can put "gitlens.remotes" into "settingsSync.ignoredSettings" and that will keep it from syncing. Fair enough. But, what if I don't mind the second remote syncing between machines, and I only want to prevent the first remote from syncing? Can't put "gitlens.remotes[0]" into "settingsSync.ignoredSettings", that doesn't work.
Alternatives
Workspace Settings
I'm not sure this is what I want because I have multiple projects on both machines, and I'd like to have the settings sync between those projects. Having to put the same remotes settings into each workspace seems like overkill to me. I have thought about creating a settings.local.json file and saving it on my work machine, though, and from whence I could copy the settings. (I know VSCode used to support a file, but no longer does.)
Profile Switcher
I have this extension and have been tinkering with it, but I don't see how it would work here as it would still sync the setting between machines, it would just have it in another JSON object.

Note that it isn't a huge deal or urgent problem, I'm just curious if this functionality exists. And if it doesn't, and there are other ways to do this, I am all ears.


text:
Q: What is the media-key command in 14.04 for sound and brightness? I am using a laptop and with vanilla Ubuntu 14.04 I was able to control my monitor brightness with super+F5/F6.
Now I want to switch to i3wm and I need to manually bind those keys. What is the command to control the brightness/sound etc?

A: For sound, the basic keys are:

*

*XF86AudioNext

*XF86AudioPause

*XF86AudioPlay

*XF86AudioPrev

*XF86AudioLowerVolume

*XF86AudioRaiseVolume

*XF86AudioStop

You can link them to you favorite music player, for example, setting XF86AudioNext to execute gmusicbrowser -cmd NextSong. The specific code will depend on the options allowed by your particular music player (which you can check in a terminal writing "my_music_player" --help or alike).
See this link for a list of all available XF86 commands.


text:
Q: Calling MouseLeave chartJs Angular I have the code below:
Angular component html
<canvas myChart>
   [dataset] = "dataVariable"
   [labels] = "labelVariable"
   (chartHover) = "chartHover($event)"
</canvas>

Component.ts
public chartHover(e: any){
   //Perform operations
}

I'm actually calling a custom pop-up whenever I hover over an element. The problem is I haven't found a way to trigger the mouseleave event to make the component disappear.
I've tried this:
(chartMouseLeave) = "funct()"

What's the correct way to do this?

A: You can bind the event to mouseout event of the canvas.
<canvas myChart>
   [dataset] = "dataVariable"
   [labels] = "labelVariable"
   (chartHover) = "chartHover($event)"
   (mouseout) = "mouseOut($event)"
</canvas>

Component
public mouseOut(event: any){
   // set pop up open flag to false
}


text:
Q: Setup Maven Repository on private server to share the android library for Android Studio I have a Gitlab server for Version Control System. I have developed an android library and want to share the android library in a gradle way i.e. compile "com.mycompanyname.libraryname:version.
I need a guidance on how to set up the repository on my server and how to share the library for gradle building.
I am trying to achieve a gradle mechanism using below given setup:
buildscript {
  repositories {
    jcenter()
    maven { url 'https://any_url_/public' }
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:1.0.+'
    classpath 'io.anything:gradle:1.+'
  }
}

apply plugin: 'com.android.application'

repositories {
    jcenter()
    maven { url 'https://any_url/public' }
}

A: Local artifact repository would be probably JFrog Artifactory, Apache Archiva or Sonatype Nexus. Here's a co-edited comparison matrix. All three have OSS versions which should do the job for Gradle builds.
Both JFrog and Sonatype have free instances of Artifactory and Nexus correspondingly for OSS projects, so you don't even need to maintain your own server if you don't want to.
Regarding publishing to a local Maven repository and releasing to JFrog Bintray (jcenter) and to Maven Central, there are a lot of good guides (here's one, for example).
If you will end up using Artifactory, then you can publish to Bintray JCenter and Maven Central directly from it (that's what Spring Framework, Groovy, Grails and many others are doing), here's the REST API that you'll call (or you can use the UI).

I am with JFrog, the company behind Bintray and [artifactory], see my profile for details and links.


text:
Q: Display all table data through procedures in SQL ORACLE I have a employees table and i have to print all employees data through a procedure I tried this:
DECLARE
e_ename Emp.Empname%Type;
e_job Emp.Job%Type;
e_mgr Emp.Mgr%Type;
e_hiredate Emp.Hiredate%Type;
e_sal Emp.Sal%Type;
e_comm Emp.Comm%Type;

PROCEDURE empregados(n IN Emp.Empname%Type, j IN
Emp.Job%Type, m IN Emp.Mgr%Type, h IN Emp.Hiredate%Type, s IN Emp.Sal%Type, cm IN Emp.Comm%Type)
IS

BEGIN

    Dbms_Output.Put_Line('Name: ' || n ||' Job: '||j||'MGR: '||m||' Hiredate: '||h||' Salary: '||s||' Comissao: '||cm);

END;
BEGIN
SELECT ENAME into e_ename, job into e_job, mgr into e_mgr, hiredate into e_hiredate, sal into e_sal, comm into e_comm FROM EMP;
empregados(e_ename,e_job,e_mgr,e_hiredate,e_sal,e_comm);
END;
/

Im having some trouble with this error
Error report -
ORA-06550: line 19, column 32:
PL/SQL: ORA-00923: FROM keyword not found where expected
ORA-06550: line 19, column 1:
PL/SQL: SQL Statement ignored
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

Would like to know what is wrong in the query?

A: You only need to specify into once. Your statement should look like
select col1, col2, col3
  into var1, var2, var3
  from emp
 where emp_id = 123;

To print out all employee info, you can loop through the employees using a cursor
DECLARE
    PROCEDURE empregados (n    IN Emp.Empname%TYPE,
                          j    IN Emp.Job%TYPE,
                          m    IN Emp.Mgr%TYPE,
                          h    IN Emp.Hiredate%TYPE,
                          s    IN Emp.Sal%TYPE,
                          cm   IN Emp.Comm%TYPE)
    IS
    BEGIN
        DBMS_OUTPUT.Put_Line (
               'Name: '
            || n
            || ' Job: '
            || j
            || 'MGR: '
            || m
            || ' Hiredate: '
            || h
            || ' Salary: '
            || s
            || ' Comissao: '
            || cm);
    END;
BEGIN
    FOR i IN (SELECT ENAME, job, mgr, hiredate, sal, comm FROM EMP)
    LOOP
        empregados (i.ename,
                    i.job,
                    i.mgr,
                    i.hiredate,
                    i.sal,
                    i.comm);
    END LOOP;
END;
/


text:
Q: replacing a character at a certain pos in the str using php exp. string to replace;
 150941_3D-glass-green-effect-hd-wallpapers_jpg

I need to replace the character _jpg with .jpg but the extension can change so I need _ to be replaced with a point.  I have tried strpos and then substr_replace but this removes everything after and include the _.

A: Tested with 2 extensions and also accounts for jpeg
$str1 = '150941_3D-glass-green-effect-hd-wallpapers_jpg';
$str2 = '150941_3D-glass-green-effect-hd-wallpapers_png';

$str1 = preg_replace('/_([a-z]{3,4})$/', '.$1', $str1);
$str2 = preg_replace('/_([a-z]{3,4})$/', '.$1', $str2);

echo $str1; //150941_3D-glass-green-effect-hd-wallpapers.jpg
echo $str2; //150941_3D-glass-green-effect-hd-wallpapers.png

A: Use the str_replace command.
$string = '150941_3D-glass-green-effect-hd-wallpapers_jpg';
$new = '.jpg' // or wathever you want.
$new_string = str_replace('_jpg', $new, $string);

A: You could do this:
$filename = "150941_3D-glass-green-effect-hd-wallpapers_jpg";
$position = strrpos($filename, "_");
if($position !== false) {
    $filename = substr_replace($filename, ".", $position, 1);
}

A: <?php
$o = "150941_3D-glass-green-effect-hd-wallpapers_jpg";
$o = preg_replace("/_([^_]+)$/", ".\\1", $o);
echo $o;

A: Check below code
$imgExt = array('_jpg','_jpeg','_png','_bmp','_gif');
$replaceExt = array('.jpg','.jpeg','.png','.bmp','.gif');
$string = '150941_3D-glass-green-effect-hd-wallpapers_jpg';
$replacedText = str_replace($imgExt,$replaceExt,$string);


text:
Q: C# - How can I convert the string value to decimal places? Basically, ive created a form that I can select different shapes that when a value on the track bar is selected, works out both the area and boundary length of either a circle, triangle or square.
The values are currently coming through with a lot of decimal places and I want to set up radio buttons to choose whether 2, 3 or 4 decimal places.
private void sliderBar(object sender, EventArgs e)
{

        textBox3.Text = trackBar1.Value.ToString();

        if(circleButton.Checked == true)
        {
            textBox2.Text = (circle.getArea(trackBar1.Value)).ToString();
            textBox1.Text = (circle.getBoundLength(trackBar1.Value)).ToString();
        }
        else if(squareButton.Checked == true)
        {
            textBox2.Text = (square.getArea(trackBar1.Value)).ToString();
            textBox1.Text = (square.getBoundLength(trackBar1.Value)).ToString();
        }
        else
        {
            textBox2.Text = (triangle.getArea(trackBar1.Value)).ToString();
            textBox1.Text = (triangle.getBoundLength(trackBar1.Value)).ToString();
        }

        if (decimalPlaces2Button.Checked == true)
        {
            TextBox2.Text = decimal.Round(textBox2, 2, MidpointRounding.AwayFromZero).ToDouble();

        }
}

A: Here's a working solution which does not Round your number.
static double TakeDecimals(double value, int decimalCount)
    {
        var truncation = Math.Pow(10, decimalCount);
        return Math.Truncate(value * truncation) / truncation;
    }

Called like
var input=24.343545;
TakeDecimals(input, 2);//24.34
TakeDecimals(input, 3);//24.343
TakeDecimals(input, 4);//24.3435

UPDATE
In your case, having a string, you can do Convert.ToDouble(yourString) before calling the method.

A: You can use Math.Round(double, int32)
Math.Round(value, 2);

A: First convert string to decimal using "Convert.ToDecimal". Then use "Math.Round" to round the decimal number(2, 3 or 4 decimal places).
decimal area;
textBox3.Text = trackBar1.Value.ToString();

    if(circleButton.Checked == true)
    {
    area = circle.getArea(trackBar1.Value)
        textBox2.Text = area.ToString();
        textBox1.Text = (circle.getBoundLength(trackBar1.Value)).ToString();
    }
    else if(squareButton.Checked == true)
    {
    area = square.getArea(trackBar1.Value)
        textBox2.Text = area.ToString();
        textBox1.Text = (square.getBoundLength(trackBar1.Value)).ToString();
    }
    else
    {
    area = triangle.getArea(trackBar1.Value)
        textBox2.Text = area.ToString();
        textBox1.Text = (triangle.getBoundLength(trackBar1.Value)).ToString();
    }

    if (decimalPlaces2Button.Checked == true)
    {
    decimal number1 = Convert.ToDecimal(area);
        decimal numWithTwoDecimalPlace = Math.Round(number1, 2);
            TextBox2.Text = numWithTwoDecimalPlace.ToString();
    }
else if (decimalPlaces3Button.Checked == true)
    {
    decimal number1 = Convert.ToDecimal(area);
        decimal numWithTwoDecimalPlace = Math.Round(number1, 3);
            TextBox2.Text = numWithTwoDecimalPlace.ToString();
    }

A: you can use this:
    decimal convertedValue;
    decimal.TryParse(textBox2.Text,out convertedValue);
   textBox2.Text = Math.Round(convertedValue, 2).ToString();


text:
Q: Incorrect field type mapping SubSonic 2.2, SQLite 3 I have a boolean (BOOL) type field in the SQLite table.
In the SubSonic generated DAL it is represented as string (instead of bool).
It is weird.
How it can be managed? Please, help.
alt text http://dl.dropbox.com/u/3882061/sqlite.GIF

A: I maybe wrong on this, I have only used Subsonic 2.2 with SQL2008 but I would recommend looking at the source for Subsonic, namely SQLLiteDataProvider.cs and reviewing the DbType function.
It seems to recognise the type Boolean but not Bool and the default when it does not recognise your type is to resort to String.
Hare is the code in question from that function
 switch(sqliteType.ToLowerInvariant())
            {
                case "text":
                case "char":
                case "nchar":
                case "varchar":
                case "nvarchar":
                    return DbType.String;
                case "boolean":
                case "bit":
                    return DbType.Boolean;
                case "bigint":
                case "int":
                case "integer":
                    return DbType.Int64;
                case "real":
                case "numeric":
                case "double":
                case "single":
                case "float":
                    return DbType.Single;
                case "smallint":
                    return DbType.Int16;
                case "date":
                case "time":
                case "datetime":
                case "smalldatetime":
                case "timestamp":
                    return DbType.DateTime;
                case "binary":
                case "blob":
                case "image":
                    return DbType.Binary;
                case "guid":
                    return DbType.Guid;
                default:
                    return DbType.String;
            }

I would recommend changing it, seeing if it works and then recommeding the change to the subsonic chaps.

A: I checked in a newer version of the provider in Dec. with several bug fixes, but from what I can tell it's not included in the source download -- Rob doesn't work with sqlite therefore it's not a priority for him to merge and test. I recommend looking my version since it solved several bugs for me. I have an even newer version that passes virtually all of the unit tests, modified for sqlite, but wonder if it's worthwhile uploading it. It was difficult to get the tests to pass due to database locking errors and the sql server bias in the core code -- sqlite has file level locking. The unit tests are not at all complete coverage.
Link to my SQLiteProvider.cs on github
My version has a slightly different GetDbType method, and I see for some brain dead reason I didn't include bool or boolean as a type to convert so I will add that.


text:
Q: Is there a way to include a brew instillation in a python build? I'm trying to build a speech recognition application that works in a browser. Currently using pyodide with a web worker. I have my own package, built alongside pyaudio, that I use for the web worker.
Is there a way that I can include a brew instillation, specifically portaudio, inside of my python package so that when I build the package, portaudio is included in the wheel file? I need portaudio included for this to work in the browser.
Thank you!

A: I'm understanding two different questions here, so I'll try to answer them both.

Can I have a python build fetch a Homebrew project during buildtime

To my knowledge, the answer is no. The Python distribution system is separate from Homebrew, and they can't interact in this fashion.
Even if they could, this wouldn't necessarily be desirable:

*

*What happens if the user isn't on macOS (or Linux)? Then the build would fail.

*The prefix that Homebrew will install the package in isn't very deterministic. The user might be using a custom prefix, or they might be on Apple Silicon (which has a different default prefix to Intel).

*

*Your python package might run into some difficulty locating the package.

*What about if they don't have Homebrew installed? They might have another package manager like MacPorts or Fink, or maybe none at all.

Can I bundle portaudio into the build distribution?

Maybe? Even if you could, I almost certainly wouldn't recommend it.

*

*Bundling dependencies increases the size of the distribution unnecessarily.

*It would take a reasonable amount of effort to setup, assuming you can do it.

All these reasons are why for the majority of projects that have a similar setup, you will find that they recommend installing certain packages with their system package manager first, before building the Python source code.
This allows them to choose whatever package manager they have installed, and it should also be a quick and painless process.
Therefore, just change your installation instructions to the following:
# On macOS
brew install portaudio
pip install ...


text:
Q: Identify horror film/TV show where protagonists ostensibly hunting a Gill-Man are transformed into same I am trying to track down the name of a film or TV show I saw as a child during the 70s, probably during a "Creature Feature" type TV rebroadcast. I believe the work was actually from the 50s or 60s (black and white, as I recall).
As I recall, there was some kind of crew of protagonists on a river-boat hunting for a Gill-Man/Creature From The Black Lagoon type of monster.
I also have a vague recollection that some of the protagonists/boat's crew vanish as the monster surreptitiously attacks across the film.
I have the impression that a (probably "the," and probably did a lot of screaming) sympathetic female character on the boat is kidnapped and the climax of the film reveals that the disappeared people have been/are being transformed in something like a surgical theater into piscene amphibious humanoids just like the primary antagonist.
Update 1-20-2020: The feature was not any of:

*

*The Creature From The Black Lagoon, Revenge of the Creature, or The Creature Walks Among Us

*The Dr. Who episode "The Underwater Menace"

*Zaat (aka The Blood Waters of Dr. Z)

*Island of the Fishmen

*The Voyage to the Bottom of the Sea episode "The Deadly Amphibians"

*Terror Beneath the Sea

A: The Doctor Who story "The Underwater Menace" (1967)?
The Doctor, with Polly, Ben and Jamie in tow, lands the TARDIS on a volcanic island where they are captured and taken into a cave complex. It soon becomes clear that this tiny island is all that remains of the ancient Atlantean civilisation.
Mad scientist Professor Zaroff has convinced the Atlanteans that he can raise the city from the sea, but in reality he plans to drain the ocean into the Earth's core and thereby destroy the planet.
Polly is taken off to be converted into an aquatic Fish Person, while the others meet two shipwrecked sailors who help them convince the Fish People to rebel. Eventually, the Doctor manages to foil Zaroff's plan
Fun Fact: The story spans four episodes, but only two of the four survive today. The other two remain missing.

Also there's Isle of the Fishmen, with a very similar plot (minus the Doctor) but it's from 1979 and apparently not B&W.

A: Perhaps Zaat (also known as The Blood Waters of Dr. Z) 1971?
Still not B&W, but plot points match....
From the wikipedia summary:

The film begins with Nazi mad scientist Dr. Kurt Leopold in his lab,
  where he has lived alone for about 20 years. His formula (the titular
  Zaat) can turn a man into a walking catfish. He injects himself with
  the serum and emerges from a tank as a giant fish-like creature.
Leopold decides to kill the colleagues that laughed at his work. He
  begins with a character named Maxson. In a lake where Maxson is
  fishing, Leopold swims under Maxson's boat, overturns it, and proceeds
  to kill Maxson and Maxson's son. Maxson's wife escapes, although she
  is in shock from the attack.
After killing Maxson, Leopold discovers a girl who is camping out
  alone on the shore of the lake. Leopold rlater eturns to the lake
  where the girl is still camping and waits for an opportunity to abduct
  her. Lopold catches her underwater. He swims with her to his lab, even
  as she struggles in vain to escape.  Leopold injects Zaat into her
  neck. As she is immersed into a tank of Zaat, the girl wakes up and
  struggles against the ropes holding her. The equipment malfunctions
  for reasons unknown, and her corpse, partially transformed, is pulled
  from the tank.
Leopold attempts to kidnap another mate. His choice is Martha Walsh,
  the lovely female member of the INPIT scientific team sent to
  investigate the weird happenings in the town (caused by Dr. Leopold).
  Leopold grabs her after her male counterparts leave her alone. Leopold
  takes her to his lab, but two of her companions (having unraveled the
  plot) are waiting there. Leopold kills them (including the sheriff)
  violently. He injects her with Zaat, readies her to be dunked into the
  tank, and makes his getaway, with canisters of Zaat. Martha's
  transformation does not go as planned and she gets saved from getting
  dunked in the tank by one of her dying male companions as Leopold
  flees toward the ocean. Despite being saved from the transformation,
  she appears to be in a trance and immediately follows Leopold into the
  sea. The movie ends ambiguously, with Leopold seen shot but not
  killed.

A: "Terror Beneath the Sea"(1966)?
It has one leading female and she does do a lot of screaming. It takes place on a submarine, not a river boat, but it involves men being turned surgically into 'gill men'. Here is the full movie from Youtube . The surgical scenes start at about 30 minutes, and soon after you can see what you referred to as a 'surgical theater'.

P.S.
It's in color, though, not B & W, but maybe you watched on a B & W Tv?


text:
Q: What does it mean to attach to process in Visual Studio 2010? I have seen this option under the debug menu, but I don't completely understand what it means. Could somebody explain it to me? Thank you in advance.

A: I don't know what the official documentation says, but this is how I use it.
If you are working in a project that runs continuously, say a web site deployed in IIS or a windows service and you have the solution with the code of the running program open in VS, you can attach to the process and debug it as if you had launched it hitting F5, set breakpoints, etc. It also allows to attach to a process running in a remote machine if it is properly configured, which turns out to be useful if you are debugging a process in a staging server or something like that.
You just need to make sure that the code you are editing is the one used to compile the binary.

A: You can attach the debugger to a running process and start debugging it where its at.  Mostly useful only if you have the debugging information for the executable.
I tend to use it if my program hits an exception and I'm not already debugging it.  I can attach and then view the variables and call stack.

A: When you Attach to a Process, you're causing the debugger to attach to the process and allow you to set breakpoints within code that you have not started from a debugger.  This is very useful in the situation of trying to debug things that have an automatic spawning process (such as .NET code that runs under IIS).

A: Instead of pressing F5 to start an instance of your app (or pressing the green "go" button), you can attach the debugger to an already running program.  While you /can/ attach to an instance of Notepad, since Notepad is not a .net application and you don't have the .pdb debugging symbols for notepad, it won't do much good.
To attach to an already running instance of your program (or an internet explorer instance that is running your code)...

*

*compile non-optimized

*compile "Full" debugging symbols (the
default for the DEBUG configuration)

*make sure the .pdb file is in
the same directory as the .dll or .exe (or you can find them manually)

*make sure the code is in the same path as when it was compiled (or
you have to find it manually)

A: That means to attach a debugger (i.e visual studio's integrated debugger) to the process so you can pause it and inspect variables at runtime.  This happens when you hit F5 automatically, or can be done manually using the debug menu.


text:
Q: ExtJS - Data from Store don't load I have a problem with loading data from store. Please tell me what I do wrong. I am using ExtJS 4.1.
Request sends properly, i haven't troubles like file not found or something like that. It also works if I had few stores, and any of this stores loading one 'data type' to his model, for example urls1. But if I have one store and one big model, data don't display.
I have a JSON like this:
{
"root": {
    "tName": "name",
    "urls1": [{
            "url": "http:// ..... :09'"
        }, {
            "url": "http:// ..... :10'"
        }],
    "perS": "",
    "perD": "",
    "urls2": [{
            "url": "http:// ..... :0009'"
        }, {
            "url": "http:// ..... :0010'"
        }],
    "val2": "",
    "list2": [{
            "level": "lvl1"
        }, {
            "level": "lvl2"
        }],
    "types": [{
            "type": "type2"
        }, {
            "type": "type4"
        }],
    "accs": [{
            "login": "login",
            "pass": "p1",
            "port": "8858",
            "conType": "type3",
        }, {
            "login": "login3",
            "pass": "p13",
            "port": "88583",
            "conType": "type2",
        }]
}
}

My Model:
Ext.define('ACT.model.myModel', {
extend: 'Ext.data.Model',
fields: [
    {name: 'tname'},
    {name: 'urls1'},
    {name: 'psec'},
    {name: 'pday'},

    {name: 'urls2'},
    {name: 'list2'},
    {name: 'types'},

    {name: 'accs'},

]

});
My Store:
Ext.define('ACT.store.dataStore', {
extend: 'Ext.data.Store',
storeId:'mStore',
model: 'ACT.model.myModel',
autoLoad: true,

proxy: {
    type: 'ajax',
    url: 'resources/data/configuration/MyConfig.json',
    reader: {
    type: 'json',
    root: 'root',
    successProperty: 'success'
    }
}

});
and my initComponent function in view:
initComponent: function() {

    var me = this;

    this.columns = [
    {
        xtype: 'checkcolumn',
        text: ' ',
        width: 100,
        sortable: false,
        hideable: false,
        allowBlank: false
    },
    {
        text: 'URL',
        width: '85%',
        dataIndex: 'urls1',
        sortable: true,
        hideable: false
    }]
this.callParent(arguments);

}
});

A: The above should load urls1 into the store correctly, however, the data type is array. So the data is in the store but it is only not displayed in the grid as dataIndex points to that array.
You can create another model for urls and associate it with the master model.


text:
Q: How to return to the previous window with defined values JAVA-FX I dont know what is happening, Im trying to go back to the previous windows with some values already defined, but it doesnt work, I created an static ObservableList, so each time I add a new objective it will be added it, this part works, heres the code:
public void AddList(ActionEvent e) throws IOException {

    FXMLLoader loader = new FXMLLoader();
    loader.setLocation(getClass().getResource("Form.fxml"));
    Parent root = loader.load();
    Formcontroller = loader.getController();
    Scene scene = new Scene(root);
    Stage Newstage = (Stage)((Node)e.getSource()).getScene().getWindow();
    Newstage.setScene(scene);
    Newstage.show();

}

it will send me to the window where the form is, heres the code to add a new objective:
public void addObjective(ActionEvent e) throws IOException {

    if (this.saving.getText().equalsIgnoreCase("")) {

        Objectives object = new Objectives (this.objective.getText(), Double.parseDouble(this.price.getText()), 0);
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("Objectives.fxml"));
        Parent root = loader.load();
        Objectivescontroller = loader.getController();
        controller.AgregarObjetivo(object);
        Scene scene = new Scene(root);
        Stage Pstage = (Stage) button.getScene().getWindow();
        Pstage.setScene(scene);
        Pstage.show();

    }else {

        if (Double.parseDouble(this.saving.getText()) != 0 || Double.parseDouble(this.saving.getText()) == 0) {

            Objectives object = new Objectives (this.objective.getText(), Double.parseDouble(this.price.getText()), Double.parseDouble(this.saving.getText()));
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(getClass().getResource("Objectives.fxml"));
            Parent root = loader.load();
            Objectivescontroller = loader.getController();
            controller.addObjetive(object);
            Scene scene = new Scene(root);
            Stage Pstage = (Stage) button.getScene().getWindow();
            Pstage.setScene(scene);
            Pstage.show();

        }
    }
}

here is the code to add the objective to the list:
 public void addObjective (Objectives objective) {

    objectives.add(objective);
    listview.getItems().addAll(objectives);

}

each new objectives that I add it will stay in the list, the problem now its that Im trying to make a button in the form window, where I can click on it and go back without adding a new objective, but it shows me the list empty, i dont know why it doesnt show me the list that is already with objectives, heres the code:
public void goback (ActionEvent e) throws IOException {

    FXMLLoader loader = new FXMLLoader();
    loader.setLocation(getClass().getResource("Objectives.fxml"));
    Parent root = loader.load();
    Scene scene = new Scene(root);
    Stage Pstage = (Stage) button.getScene().getWindow();
    Pstage.setScene(scene);

}

its the same code that I used to add new objective, the only difference its that Im not calling the controller, sorry if my code is ugly or noob, but Im new in java - javafx and im just starting, thanks!