text:
Q: How to assert two list values with contains, but not a exact equal comparison in java I am brand new to Java and i need some help. I have two lists.
List Expected = [Name , SSN, DOB];
List Actual = [Name , SSN];

I need to assert whether the List Actual values are available in List Expected, in other words, if both of the values in List Actual if it available in List Expected, my test should Pass. I googled and i tried to use this below assert statement. But my test is failing with the reason it is trying to validate the "DOB" from the List Expected.
Assert.assertThat("The Test Result Is.... : ", Expected, containsInAnyOrder(Actual.toArray()));

can anyone help me?

A: assertTrue(expected.containsAll(actual));

I strongly advise to stop using raw types (i.e. use List<String> and not List), and to respect the Java naming conventions (variables start with a lowercase letter).


text:
Q: csh environment variable execute I'm building a command line up in a tcsh shell variable, something like
set cmd  = "/usr/local/bin/rsync "
set parm = "--verbose --acls --times --links "
set src  = "/spindle/to\ be\ backed-up "
set dest = "/mnt/backup21 "

set final = "$cmd $parm $src $dest"

$final

and I'd like the last line to execute the command.  I can get this to execute, but always with the error
rsync: link_stat "/spindle/to\" failed: No such file or directory (2)

It doesn't seem to properly see the space in the path.  I tried multiple \ in that line, still didn't work.  Suggestions?

A: First off, I'd seriously consider finding a different way to do this. csh is widely considered to be a poor shell for programming; see the classic article Csh Programming Considered Harmful. I've been using csh and tcsh for more decades than I care to admit, and I still have to resort to trial and error to answer questions like this.
But for your immediate question, eval seems to work. Replace the line
$final

by
eval $final

redpajama_set_name: RedPajamaStackExchange


text:
Q: Install GeoIP on Windows? Does anybody know how to install GeoIP's C library on Windows in a few simple steps. Even a few complicated steps will do. I researched and tried to compile it from the setup file but failed several times. Sometimes, I get errors saying that GeoIP.h could not be located. Other times I get that bugtrack_url is not a valid option for compilation.
I have tried using pip install GeoIP and I have also tried just using setup.py.
Has anyone had any luck setting this up on Windows?

A: The 'GeoIP.h could not be located' error indicates that you need to install libgeoip-dev first. Though I have no idea how to install it on windows easiy.
I suggest you to use the pygeoip package, based on the following  reasons:

*

*pygeoip is a pure python package

*pygeoip supports Python 3

*pygeoip has wheel support

*pygeoip has better documentation

*pygeoip has 50x more downloads on pypi.

*pygeoip is compatible with GeoIP's API


text:
Q: Not-equal to character in R What is the command for printin the string that are not equal to a specific character? From the data below I would like to print the number of rows where the t5-column does not start with d-. (In this example that is all the rows)
I tried
dim(df[df$t5 !="d-",])
df:
             name freq            mir start end mism  add   t5  t3       s5       s3    DB ambiguity
6     seq_10002_x17   17 hsa-miR-10a-5p    23  44  5GT    0  d-T   0 TATATACC TGTGTAAG miRNA         1
19    seq_100091_x3    3 hsa-miR-142-3p    54  74    0 u-CA d-TG   0 AGGGTGTA TGGATGAG miRNA         1
20    seq_100092_x1    1 hsa-miR-142-3p    54  74    0 u-CT d-TG   0 AGGGTGTA TGGATGAG miRNA         1
23    seq_100108_x5    5 hsa-miR-10a-5p    23  44  4NC    0  d-T   0 TATATACC TGTGTAAG miRNA         1
26 seq_100113_x1219 1219    hsa-miR-577    15  36    0    0  u-G   0 AGAGTAGA CCTGATGA miRNA         1
28    seq_100121_x1    1 hsa-miR-192-5p    25  45  1CT u-CT  d-C d-A GGCTCTGA AGCCAGTG miRNA         1

A: df1 <- df[!grepl("^d-",df[,8]),]
nrow(df1)
print(df1)

A: There is one row in your data that has a t5 entry that does not start with "d-". To find this row, you could try:
df[!grepl("^(d-)",df$t5),]
#               name freq         mir start end mism add  t5 t3       s5       s3    DB ambiguity
#26 seq_100113_x1219 1219 hsa-miR-577    15  36    0   0 u-G  0 AGAGTAGA CCTGATGA miRNA         1

If you only want to know the row number, you can get it with rownames()
> rownames(df[!grepl("^(d-)",df$t5),])
#[1] "26"

or with which(),
> which(!grepl("^(d-)",df$t5))
#[1] 5

depending on whether you want the row number counting from the top of your data frame or the row number according to the value on the left.


text:
Q: How can I change the value of a $_GET variable without using a link? The website I am working with is a property sales site where the user can freely advertise their property. Properties can be for sale or for rental: http://ev-villa.com
The search panel I designed has 2 tabs: For Sale and To Rent. To get a clearer understanding of the following problem I would advise you to load the site from the above URL. As the site is multi-lingual you may have to change the language to English by clicking on the flag icon in the top right of the page.
So the tabs in the search panel (left side of the page) can be clicked by the user and this tab will now change colour to show that it has been selected. This is handled by a variable in the URL called saleType. So if the value of this variable is equal to "torent" then the "To Rent" tab will change colour (The css on the page changes when the variable's value changes). Apart from changing colour this variable also affects the search results gained when the user clicks the search button.
The issue here is that the variable change is done by a link which requires reloading/redirecting. So if these tabs are clicked a few times, the result is that the user will have to click the browser's back button quite a few times to leave the website or to get to other parts of the website.
I am basically looking for an alternative solution to changing the value of this variable in php without using a link so that the value is set without redirecting the browser to a new page. I am trying to avoid the use of JavaScript and other languages, to ensure maximum cross-browser and cross platform compatibility, making sure this website works for browsers that don't support JavaScript or don;t have JavaScript enabled at the time of use.

A: I wasn't happy with my previous answer, so I gave it a little bit more thought.
Here's a workaround, completely without JavaScript and without requesting the server:

*

*Instead of 1 form for both types of search (rent/sale), create two identical forms but with different action attributes.
<!-- Rental -->
<form action="search.php?saleType=torent" method="get">
...
<!-- Sale -->
<form action="search.ph?saleType=forsale" method="get">
...

*Use CSS to position the forms on top of one another, and to hide one of the forms.

*Use the Checkbox Hack to detect a click event on the form "For Sale" and "To Rent" links (you'll need to make them a <label>), and to hide/show the respective form.


text:
Q: Bootstrap Grid Alignment Issues So I'm following a tutorial for RoR but I can't seem to get the alignment right.If I copy and paste the code for the tutorial, it will look like
this
Here is the code:

<%= form_for(@user) do |f| %>

  <%= f.label :name %>
  <%= f.text_field :name %>

  <%= f.label :email %>
  <%= f.email_field :email %>

  <%= f.label :password %>
  <%= f.password_field :password %>

  <%= f.label :password_confirmation, "Confirmation" %>
  <%= f.password_field :password_confirmation %>

  <%= f.submit "Create my account", class: "btn btn-primary" %>
<% end %>

But if I put col-md-1, then it sort of works, looking like this
Is it possible to still use col-md-6 but have it properly aligned like the second photo? I don't know what else to change other than the numbers.

A: I am not able to test this right now but you may be able to change your first line of your form to:
 <%= form_for @user, :html => {:class => "form-horizontal"} do |f| %>

This should add the html and css need to make the form horizontal:
 <form class="form-horizontal">

Some what like this example: https://jsfiddle.net/obp9x1yr/7/
This might be a good post to read for more information: Rails Bootstrap how to format form_for (width grid collapses)


text:
Q: Connecting to mysql with Zend Framework 2 I'm trying to connect to mysql database with zend framework but it's unable to connect.
i followed up zend documentation and some other tutorial on how to connect to mysql but it's give's me an error on this line "$sm = $this->getServiceLocator();"
Error Message :
Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for Post\Model\PostTable

global.php
return array(
'db' => array(
    'driver' => 'Pdo',
    'dsn' => 'mysql:dbname=zend;host=localhost',
    'driver_options' => array(
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
    ),
),
'service_manager' => array(
    'factories' => array(
        'Zend\Db\Adapter\Adapter'
        => 'Zend\Db\Adapter\AdapterServiceFactory',
    ),
),);

local.php
 return array(
'db' => array(
    'username' => 'root',
    'password' => '',
),

);
PostController.php
public function getPostTable() {
    if (!$this->postTable) {
        $sm = $this->getServiceLocator();
        $this->postTable = $sm->get('Post\Model\PostTable');
    }
    return $this->postTable;
}

//module/Post/src/Post/Model/PostTable.php
<?php
namespace Post\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\AbstractTableGateway;

class PostTable extends AbstractTableGateway
{
  protected $table ='tbl_post';

   public function __construct(Adapter $adapter)
{
    $this->adapter = $adapter;
    $this->resultSetPrototype = new ResultSet();
    $this->resultSetPrototype->setArrayObjectPrototype(new Post());
    $this->initialize();
}

public function fetchAll()
{
    $resultSet = $this->select();
    return $resultSet;
}
}

A: I, personally, think that it is obvious that 'Post\Model\PostTable' is not defined either at all, or where it should be.
Where is 'Post\Model\PostTable' defined in your codebase? How does that compare to ZF2's rules?

A: In your Module.php you should have 'Post\Model\PostTable' injecting the table
good luck :)


text:
Q: Swift - How to build iOS user interface dynamically from XML code? I have the following sample xml code which my app receives. My job is to create certain UI elements such as textfields and labels based on this xml code.
<?xml version="1.0" encoding="UTF-8"?><Form>
    <Group description="Alap" name="GEN">
            <Field name="CUSNUM" type="F" length="0" lines="1" constraint="" mcHandler="" readOnly="false" hidden="false" mandatory="true" label="Üzletkód" width="2"/>
            <Field name="CUSTOMERNAME" type="F"  length="0" readOnly ="false" label="Üzlet neve" width="2"/>
            <Field name="COMPANYNAME" type="F" length="0" readOnly ="false" label="Cég neve" width="2"/>
            <Field name="ZIPCODE" type="F" length="0" readOnly ="false" label="Irányítószám" width="2"/>
            <Field name="CITY" type="F" length="0" readOnly ="false" label="Település" width="2"/>
            <Field name="ADDRESS" type="F" length="0" readOnly ="false" label="Cím" width="2"/>
    </Group>
</Form>

A: First, you need to parse the XML using XMLParser.
You then walk through the resulting data structure and manually create the UILabels and possibly UIViews per Group.
Finally you add each UI element above to the current UIView.
If you're adding a UIView per Group, you of course need to make that the current UIView. And when you reach the end of the Fiels in a group, you need to pop back to the previous UIView (i.e., the superview of the current UIView).
The XML does not define where exactly you need to place the Fields and Groups. This is something that should be defined by the requirements/wishes of the party asking you to make this. I suggest you define top/bottom/left/right margins, plus a horizontal and vertical margin between labels and group views.
You could use iOS auto-layout, but this will add code. To decide, have a look how complex these UIs can become in realistic scenarios and how much size flexibility you need. Don't write 'generic' stuff that's not necessary; you'd rather focus on keeping code simple & understandable.

A: Specifically about XML parsing, if you don't mind using an external library, you could take a look at XMLMapper.
The model classes to map your XML will be:
class Form: XMLMappable {
    var nodeName: String!

    var group: Group?

    required init(map: XMLMap) {

    }

    func mapping(map: XMLMap) {
        group <- map["Group"]
    }
}

class Group: XMLMappable {
    var nodeName: String!

    var fields: [Field]?
    var description: String?
    var name: String?

    required init(map: XMLMap) {

    }

    func mapping(map: XMLMap) {
        fields <- map["Field"]
        description <- map.attributes["description"]
        name <- map.attributes["name"]
    }
}

class Field: XMLMappable {
    var nodeName: String!

    var name: String?
    var type: String?
    var length: Int?
    var lines: Int?
    var constraint: String?
    var mcHandler: String?
    var readOnly: Bool?
    var hidden: Bool?
    var mandatory: Bool?
    var label: String?
    var width: Int?

    required init(map: XMLMap) {

    }

    func mapping(map: XMLMap) {
        name <- map.attributes["name"]
        type <- map.attributes["type"]
        length <- map.attributes["length"]
        lines <- map.attributes["lines"]
        constraint <- map.attributes["constraint"]
        mcHandler <- map.attributes["mcHandler"]
        readOnly <- map.attributes["readOnly"]
        hidden <- map.attributes["hidden"]
        mandatory <- map.attributes["mandatory"]
        label <- map.attributes["label"]
        width <- map.attributes["width"]
    }
}

And you can map your XML string by using XMLMapper like:
let form = XMLMapper<Form>().map(XMLString: xmlString)


text:
Q: Seach for all Active Directory Users starting with "CA" with variable I'm currently programing an administration tool and I could need some help.
I want that every user, starting with "ca" gets imported to the listbox.
The Import into the listbox works perfectly fine.
The users I own e.g. are "cambridge", "california" and "call".
$searchuser = "ca"

if(@(Get-ADObject -Filter { sAMAccountname -eq $searchuser }).Count -ge 1){
                Get-ADObject -Filter { sAMAccountname -eq $($searchuser) } | foreach{[void]$lstUsers.Items.Add($_.name)}

            } else {

                [System.Windows.Forms.MessageBox]::Show("No user found.","Error",[System.Windows.Forms.MessageBoxButtons]::OK,[System.Windows.Forms.MessageBoxIcon]::Warning)

            }

If I put a single username into the variable it works without any problems but with multiple it doesn't want to work...
Can someone help me out a little?

A: tl;dr
# Note the '*' to make the search term a wildcard expression.
$searchuser = 'ca*'

# ...

# Note the use of Get-AdUser and the use of the -like operator.
Get-ADUser -Filter 'sAMAccountname -like $searchuser'

See AdminOfThings' helpful answer for more detailed information on the need for using wildcard patterns combined with the -like operator instead of -eq, and using an LDAP filter as an alternative.
The rest of this answer focuses on the -Filter syntax:

To solve the fundamental problem, replace

-Filter { sAMAccountname -eq $($searchuser) }

with
-Filter 'sAMAccountname -eq $searchuser'
or, using an expandable string ("...")[1] (as suggested by Mathias R. Jessen):
-Filter "sAMAccountname -eq `"$searchuser`""
While seductively convenient, the use of script blocks ({ ... }) as -Filter arguments is conceptually problematic and can lead to misconceptions - such, as in your case, the incorrect expectation that $(...), the subexpression operator can be used.
In short: While -Filter expressions resemble PowerShell expressions, they're strings interpreted by the AD provider, and there are important differences between what those strings support compared to regular PowerShell expressions - see this answer for background information, including how to deal with property-access expressions such as $searchuser.Name.
The additional problems with your code are discussed in AdminOfThings's answer.

[1] That is, variable references are expanded before the resulting string is passed to the AD cmdlet. Note that for the embedded quoting " (escaped as `") is preferable to ', because the search terms themselves may contain ', such as a last name of O'Neal.
Using expandable strings is convenient if you need to use expressions (such as property access, e.g., $searchuser.Name) as part of the filter, but this approach has limitations, notably the inability to embed dates. The generally robust solution is to assign the expression to an auxiliary variable (e.g., $name = $searchuser.Name) and reference that inside a single-quoted string; e.g., 'sAMAccountname -eq $name'

A: The -eq operator is for exact matches rather than partial/substring matches. -like operator is supported in the -Filter parameter and can be used for partial matching. You will need to add your own wildcarding (via *) for the partial match to work.
If you only need to search users, I would opt for Get-ADUser instead.
$searchuser = 'ca*'
Get-ADUser -Filter 'samaccountname -like $searchuser'

Sometimes, -LDAPFilter is more efficient for the machine running the query and can be used in this scenario:
$searchuser = 'ca*'
Get-ADUser -LDAPFilter "(samaccountname=$searchuser)"

Your if statement logic may be impacting your code completion times depending on how long it takes the command to return results. This is because you are running the same query twice. You could opt for storing the command results into a variable first provided it won't cause memory constraints on your system.
$searchuser = 'ca*'
$users = Get-ADUser -Filter 'samaccountname -like $searchuser'
if ($users) {
    # add users to your list
}

The -Filter value is treated as a string. There's no good reason to ever use a script block ({} notation) for the filter value. It can be tricky at times using complex values. PowerShell parses the initial command and does its variable substitutions. Then the Get-AD* command runs and another layer of parsing happens. This creates some confusion for handling quoting for the filter value. See below for examples:
# When using simple variables, you can simply use single quotes
Get-ADUser -Filter 'samaccountname -like $searchuser'

# When using variable property references or strings, use outer double quotes and single inner quotes
# If the string contains apostrophe, it will need to be escaped
# This syntax also works for simple variables
Get-ADUser -Filter "samaccountname -like '$($searchuser.SamAccountName)'"
Get-ADUser -Filter "samaccountname -like 'ca*'"

See mklement0's answer for in-depth detail on how -Filter works in the AD cmdlets.

A: Get-ADObject -LDAPFilter:"(anr=CA)" -Properties:allowedChildClassesEffective,allowedChildClasses,lastKnownParent,sAMAccountType,systemFlags,userAccountControl,displayName,description,whenChanged,location,managedBy,memberOf,primaryGroupID,objectSid,msDS-User-Account-Control-Computed,sAMAccountName,lastLogonTimestamp,lastLogoff,mail,accountExpires,msDS-PhoneticCompanyName,msDS-PhoneticDepartment,msDS-PhoneticDisplayName,msDS-PhoneticFirstName,msDS-PhoneticLastName,pwdLastSet,operatingSystem,operatingSystemServicePack,operatingSystemVersion,telephoneNumber,physicalDeliveryOfficeName,department,company,manager,dNSHostName,groupType,c,l,employeeID,givenName,sn,title,st,postalCode,managedBy,userPrincipalName,isDeleted,msDS-PasswordSettingsPrecedence -ResultPageSize:"100" -ResultSetSize:"20201" -SearchScope:"Subtree"

Super extra, I know:)
Not really the answer but, wanted to show how much can be included when querying.


text:
Q: How to draw icons or similar in Canvas? Is there any way to draw some icons or something in Canvas inside points or circles? For example a company´s logo? Could be with bitmap or similar?

A: Use the different methods from Canvas "draw()" and you just have to take care of your bounds. Use for example:
mCanvas.drawBitmap(Bitmap bitmap, float left, float top, Paint paint);
mCanvas.drawCircle(float cx, float cy, float radius, Paint paint);

Check it here: http://developer.android.com/reference/android/graphics/Canvas.html


text:
Q: How to use androidx.work to replace AsyncTask? Recently I am trying to use androidx.work.* stuff to perform background tasks. It works fine with the MVVM pattern. However, I met several issues when using the Worker(via OneTimeWorkRequest.Builder) to replace the AsyncTask.
First, how to pass out generic object result back from the Worker? It seems only primitive types are supported. What if I want to decode the image file in the worker thread and pass the decoded drawable or bitmap back to the main thread observer? I have a workaround is to put the object in some global data store but it does not seem to be a good practice.
Another problem is that when I try to observe on the live data obtained via WorkManager.getWorkInfosByTagLiveData(TAG_NAME), it will also return the former en-queued worker info to me. So I have to call WorkManager.pruneWork() to avoid this issue. And this does not seem to be a good practice either.
Thanks for your advice.

A: Regarding returning the result: Simply put, the same way you do it with AsyncTask. You're not supposed to pass objects around in between task. Use a "callback" or interface like explained in this answer:
How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?


text:
Q: TabControl Context Menu In a Windows Forms app I set the ContextMenuStrip property on a TabControl.

*

*How can I tell the user clicked a tab other then the one that is currently selected?

*How can I restrict the context menu from showing only when the top Tab portion with the label is clicked, and not elsewhere in the tab?

A: A bit late, but I've found a solution for the first part of your question. You can figure out which tab was right-clicked on by sending a left mouse click to the application. This selects the tab, so now you can use the TabControl.SelectedTab property to get the tab that the user right-clicked on.
    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    private static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);

    private const int MOUSEEVENTF_LEFTDOWN = 0x02;
    private const int MOUSEEVENTF_LEFTUP = 0x04;
    private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
    private const int MOUSEEVENTF_RIGHTUP = 0x10;

    private static void SendLeftMouseClick()
    {
        int x = Cursor.Position.X;
        int y = Cursor.Position.Y;
        mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, x, y, 0, 0);
    }

    public Form1()
    {
        InitializeComponent();

        tabControl1.MouseDown += new MouseEventHandler(tabControl1_MouseDown);
        tabControl1.MouseUp += new MouseEventHandler(tabControl1_MouseUp);
    }

    void tabControl1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            // Send a left mouse click to select the tab that the user clicked on.
            SendLeftMouseClick();
        }
    }

    void tabControl1_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            // To show a context menu for only the tab button but not the content of the tab,
            // we must show it in the tab control's mouse up event.
            contextMenuStrip1.Show((Control)sender, e.Location);
        }
    }

A: Don't bother setting the contextMenuStrip property on the TabControl. Rather do it this way. Hook up to the tabControl's MouseClick event, and then manually show the context menu. This will only fire if the tab itself on top is clicked on, not the actual page. If you click on the page, then the tabControl doesn't receive the click event, the TabPage does. Some code:
public Form1()
{
    InitializeComponent();
    this.tabControl1.MouseClick += new MouseEventHandler(tabControl1_MouseClick);
}

private void tabControl1_MouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        this.contextMenuStrip1.Show(this.tabControl1, e.Location);
    }

}

A: Opening event of context menu can be used to solve both problems
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
    Point p = this.tabControl1.PointToClient(Cursor.Position);
    for (int i = 0; i < this.tabControl1.TabCount; i++)
    {
        Rectangle r = this.tabControl1.GetTabRect(i);
        if (r.Contains(p))
        {
            this.tabControl1.SelectedIndex = i; // i is the index of tab under cursor
            return;
        }
    }
    e.Cancel = true;
}

A: I was looking for a solution for the exact same problem.
After testing both @nisar and @BFree answers I came to this (I also had the TabControl` inside a Panel somewhere in the Form):

*

*Create tabcontrol1

*Subscribe to the MouseClick event

*Create contextMenuTabs, ContextMenuStrip

private void tabControl1_MouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        Point ee = new Point(e.Location.X - panel1.Left, e.Location.Y - panel1.Top);
        for (int i = 0; i < this.tabControl1.TabCount; i++)
        {
            Rectangle r = this.tabControl1.GetTabRect(i);
            if (r.Contains(ee))
            {
                if (this.tabControl1.SelectedIndex == i)
                    this.contextMenuTabs.Show(this.tabControl1, e.Location);
                else
                    {
                      //if a non seelcted page was clicked we detected it here!!
                    }

                break;
            }
        }
    }
}


text:
Q: DB2 query to fetch first value in a group I have a db2 query which has to fetch the first value present for a column(Col6). I have tried using minimum for the column, but it fetches the first value in ascending order.
The table is as follows:
Col1    Col2    Col3    Col4    Col5    Col6
10      -1      N/A     1       41      Pack Inv
10      -1      N/A     1       10      Fl Sales
10      -1      N/A     1       10      St Ss Bu
10      -1      N/A     1       41      Pack Inv

The expected output for Col7 is as follows:
Col1    Col2    Col3    Col4    Col5    Col6        Col7
10      -1      N/A     1       41      Pack Inv    Pack Inv
10      -1      N/A     1       10      Fl Sales    Pack Inv
10      -1      N/A     1       10      St Ss Bu    Pack Inv
10      -1      N/A     1       41      Pack Inv    Pack Inv

By using MIN(Col6) OVER (PARTITION BY Col1) AS "Col7",the output generated is:
Col1    Col2    Col3    Col4    Col5    Col6        Col7
10      -1      N/A     1       41      Pack Inv    Fl Sales
10      -1      N/A     1       10      Fl Sales    Fl Sales
10      -1      N/A     1       10      St Ss Bu    Fl Sales
10      -1      N/A     1       41      Pack Inv    Fl Sales

May I know how the expected output can be achieved in db2.
Thank you

A: While it is not clear how the "first" column is defined in your data, this general problem is solved by ranking columns with row_number() and then selecting the first one:
with ranked as (
  select col1,
         col6,
         row_number() over (partition by col1 order by [cols that define "first"]) rank
)
select col1, col6 from ranked where rank=1

You can then join this result back to the original table if you want to add the selected value to every row...or use merge to insert it as a new column if that is what you are after.


text:
Q: How can I develop a LAMP web application using Docker, Puppet and Vagrant? In the dark ages, my usual setup for development of LAMP web applications was to test locally on my machine. PHP (in my case), the database and the web server were all installed natively.
The server was set up with standard installs of Apache and MySQL, and I had multiple virtual hosts for different parts of the web application. When I was happy with the results I had on my local machine, I'd logged into the server and did git pull in the staging environment.
Assuming everything was working as well on the server as it was on my machine, I'd do the same thing for production.
New beginnings…
So now I'm starting a brand new web application from scratch, and I want to do it "the proper way". I've read up about Docker, Vagrant and Puppet (and Chef, although I personally prefer Puppet's system of dependencies rather than Chef's iterative process). Despite all the research I've done, there still seem to be several questions I can't seem to find answers for:
Should there be separate Docker containers for the web server (such as Apache), the database server (such as MySQL) and each part of the web application?
When I talk about parts of the web application, I mean things like mysite.com, controlpanel.mysite.com, etc. These "parts" will share the same database.
Since Docker seems to provide ready-made containers for things like the web and database servers, it seems like those things at least should be in separate containers. Should the different parts of my web application be in separate containers, too?
Docker containers seem to be designed to be replaceable rather than me having to update the software inside them. What about the data they write that I don't want to lose?
The database server will manage files related to the content of my database (that I'll want to be backing up). The web server will be creating logs, and my web applications will be managing various files and caches, etc. All these files need to be written outside of the application's containers (because I might replace them when updating?), so where do they go? Straight into the host machine's file system? Or into a separate "Docker Volume"?
If they go into Docker volumes, should I use a separate volume for the database, web server, application, etc.? Can I still easily access the contents using SFTP from my local machine like I do now? I don't want to lose any convenience here!
Is it a good idea to use Puppet to create and manage the Docker containers, both for the development server and production server?
It seems Puppet has support for managing Docker containers directly, so this seems like a reasonably good way of easily setting up a server or the production environment (using Vagrant) from scratch.
Hopefully I've asked some relevant questions; it would be great to get some proper "best practices" for development and production of LAMP-like web applications. it's just there doesn't seem to be much that I've found!

A:
Should there be separate Docker containers for the web server (such as Apache), the database server (such as MySQL) and each part of the web application?

There is no correct answer to that question. If you will be using Docker in production, then try to run your Docker containers in your development environment as they will be in production. Else just use the Docker containers the easiest way you can.
Docker Hub provides ready to go containers for PHP, databases, etc. and it is easy to use them. On the other hand, you have to link them together to allow them to interact. For a development environment and if you use multiple containers, I would advise to use docker-compose.
Another path is to build a Docker image that is the closest to your production machine (assuming you have only one machine) which would run the database, the web server, and PHP. A container from such an image would have to run multiple processes. This can be achieved in different ways. Take a look at supervisor or phusion/baseimage.

When I talk about parts of the web application, I mean things like mysite.com, controlpanel.mysite.com, etc.

You could have them separated. If those applications need to share sessions, make sure sessions are stored in database or on a docker volume that is accessible to all.

Docker containers seem to be designed to be replaceable rather than me having to update the software inside them. What about the data they write that I don't want to lose?

Docker has a thing called volume to allow data to be written on a filesystem out of the container. There are different ways to work with volumes: you can mount a directory from the Docker host to a container volume, or you can have data volume containers, or named volumes.
Docker volumes are an important concept and it is worthwhile to take the time to master them.
If you want to easily access the data used by your containers from your Docker host, mounting a directory on the Docker host is the way to go. Although it may be tricky regarding permissions and ownership of the files.
Regarding backups, take a look at the Docker user guide where everything you need to know in regards with volumes is detailed.

Is it a good idea to use Puppet to create and manage the Docker containers, both for the development server and production server?

The best practice is to operate on your development environment the same way you will operate on your production environment. There is no point going through setting up Puppet correctly for your development environment if all that work won't be used for the production environment. Having a Vagrantfile that provision a VM with Docker is really easy with just shell provisioning ; IMHO puppet/chef/... are overkill.

You are asking the right questions, but there isn't any answer that fits all situations. In my view there are two ways to do things:

*

*make your development environment replicate exactly your production environment

*make your development environment different from production, keeping it as simple and straightforward as you can so developers won't feel the friction induced by using new tools

A: While the answer of Thomasleveil is already very good and covers all important parts, I'd like to add some additional points.
Vagrant, Puppet/Chef and docker-compose
When you're provisioning a virtual machine with Vagrant you usually use Puppet or Chef to install the required packages for your server ... along with a few shell scripts. PuPHPet is an excellent source for configuring a virtual machine-based LAMP Stack and learning how Puppet and Vagrant work together in a bit more complex setup. An alternative is Protobox by the way.
When you're using Docker containers with Vagrant in the same way like you do it with VMs. Then with vagrant up you're essentially running Docker containers with the Docker provider. Vagrant will build the containers for you from a Dockerfile or use an existing image, more or less like docker-compose (fig) and run them.
A major reason to choose Vagrant for your Docker setup is, if you or your team is partially working in a Windows environment, since Vagrant allows you to keep your setup consistent, no matter what your host system is (see Host VM).
If you're on OS X, you can use docker-compose with the VirtualBox VM, and if you're on Linux you can use Docker natively. It is also always possible to log in to the boot2docker (or another Docker Host VM) via ssh, no matter if you're on Windows or OS X.
Note: You should not SSH into your containers, but that's another topic.
As of February 2015
docker-compose feels a bit snappier to me and also handles starting, stopping and rebuilding containers more efficiently.
Vagrant has the advantage to specify a different host VM, e.g., per project, if you prefer such a setup.
Note: there's also a Docker provisioner which is more related a Puppet build process.

Should there be separate Docker containers for the web server (such as Apache), the database server (such as MySQL) and each part of the web application?

When using Docker containers you're basically running single, isolated processes. The usage of a supervisor should be avoided) and is also not needed for a LAMP stack.
So my answer is definitely: Yes, there should be separate containers!

When I talk about parts of the web application, I mean things like mysite.com, controlpanel.mysite.com, etc.

This depends on your needs. I suggest you to read 12factor application documentation, which describes the important things to take care of in a very detailed way.

Docker containers seem to be designed to be replaceable rather than me having to update the software inside them. What about the data they write that I don't want to loose?

In addition to @Thomasleveil's answer, I'd recommend you also a separate storage backend for user uploads like Amazon S3, SFTP, or WebDAV.
In my opinion, your web application container should be treated like a client application, accessing your database and storage backends (services) and not rely on data from volumes when running in a production environment.

Is it a good idea to use Puppet to create and manage the Docker containers, both for the development server and production server?

I don't know about the orchestration capabilities of Puppet, but for building containers, if you're using Vagrant I see no need for Puppet, because of the native Docker provisioner of Vagrant.

Bonus
For all those things described above, you can have a look at my 12factor PHP application template based on Yii 2.0 Framework with a dockerized LAMP stack.
With Docker you can also easily plug-in reverse proxies or selenium testing containers into your project, because they exist as pre-build images and can be downloaded and configured in a few minutes and started in seconds.


text:
Q: Appending an ending tag to incomplete input elements in HTML I have code such as:
<form>
    <input name="whatever">
    <input name="whatever2">
</form>

And for the XML parser in Visual Basic .NET to be able to parse this, I need to close each input tag. Like so:
<input></input>

How would I append this to each input in the HTML string I have? By using Regex?
Dim Method As New Regex("<input.*?>", RegexOptions.IgnoreCase)
For each Item as String in Method.Results("<form><input><input></form>")
    'Somehow append </input>
Next

A: You can use a very simple regex to fix the inputs.  And there are several replacement patterns you can use depending on how you want the format of the elements to be.
Sample Code
Function FixInputElement(htmlMarkup As String)
    Return Regex.Replace(htmlMarkup, "(<input[^>]*)(>)", "$1/$2", RegexOptions.IgnoreCase)
End Function

Replacement Patterns
Replacement     Input              Output
$1/$2           <input id="in1">   <input id="in1"/>
$1 /$2          <input id="in2">   <input id="in2" />
$1/$2</input>   <input id="in3">   <input id="in3"></input>

Adding Negative Lookbehind
In case there is a chance that some inputs are correctly closed you can add a negative lookbehind
(<input[^>]*)((?<!/)>)

Output with Negated Lookbehind
Input                         Output
<input id="in1">              <input id="in1" />
<input id="in2">              <input id="in2" />
<input id="in3-dontfix" />    <input id="in3-dontfix" />


text:
Q: How to get Lat Long on Map Tap in Flutter? Can someone tell me how get latitude and longitude on map tap in flutter. Do I need to use any plugin?

A: I think what you mean is that you want a latitude/longitude to be displayed when you tap on some location on a Google Maps widget? In that case, check out the place_picker plugin. From the readme, it sounds like what you need. Link: https://pub.dev/packages/place_picker
Edit:
If you just want the latitude/longitude of any arbitrary location on the map, you can also do the following in your Google Map constructor itself:
GoogleMap(
  // all the other arguments
  onTap: (latLng) {
    print('${latLng.latitude}, ${latLng.longitude}');
  }
);

A: If you need a Lat and lang as well other property you have to use place_picker package. This package help you to get data from users selected location. Try This Code
Widget _dropDownButton() {
    return Positioned(
        top: 40,
        right: 15,
        left: 15,
        child: Container(
          height: 50,
          child: TextFormField(
            readOnly: true,
            enableInteractiveSelection: false,
            // will disable paste operation
            textInputAction: TextInputAction.next,
            onChanged: (location) {
              setState(() {
                currentAddress = location;
              });
            },
            controller: locationController,
            decoration: InputDecoration(
              prefixIcon: InkWell(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) {
                        return PlacePicker(
                          apiKey: kGoogleApiKey,
                          initialPosition: currentPostion,
                          useCurrentLocation: true,
                          selectInitialPosition: true,
                          usePlaceDetailSearch: true,
                          onPlacePicked: (result) {
                            setState(() {
                              selectedPlace = result;
                              locationController.text =
                                  selectedPlace.formattedAddress;
                              controllers.animateCamera(
                                CameraUpdate.newCameraPosition(
                                  CameraPosition(
                                      target: LatLng(
                                          result.geometry.location.lat,
                                          result.geometry.location.lng),
                                      zoom: 20.0),
                                ),
                              );
                              Navigator.of(context).pop();
                            });
                          },
                        );
                      },
                    ),
                  );
                },
                child: Icon(
                  Icons.add_location,
                  color: Colors.black,
                  size: 20,
                ),
              ),
              hintStyle: TextStyle(
                color: Colors.black54,
              ),
              hintText: 'Please choose a Address',
            ),
          ),
        ));
  }


text:
Q: How to draw beyound view translation limits? The following program draws a pie (partial circle, a sector) while I expect it draw entire (full round) circle. How to draw entire circle?
The code of custom view:
public class CentralCircleView extends View {

private Paint circlePaint = new Paint();
{
    circlePaint.setColor(Color.RED);
    circlePaint.setAntiAlias(true);
}

public CentralCircleView(Context context) {
    super(context);
}

public CentralCircleView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onDraw(Canvas canvas) {
    canvas.drawCircle(0, 0, 100, circlePaint);
}
}

The code of activity:
public class TransformsActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    CentralCircleView centralCircleView = (CentralCircleView) findViewById(R.id.centralCircleView);
    centralCircleView.setTranslationX(200f);
    centralCircleView.setTranslationY(200f);
    centralCircleView.invalidate();
}
}

The code of layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"

>

<com.inthemoon.incubation.CentralCircleView
    android:id="@+id/centralCircleView"
    android:layout_marginLeft="0dp"
    android:layout_marginTop="0dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
     />

</RelativeLayout>

This is what it draws. Where is the rest of the circle?

A: Your View has its height set to wrap_content which means you need to implement the method onMeasure() to tell RelativeLayout how big the view wants to be.

A: To draw "outside the view" one should use clipRect() method. For example, in my case, I was to write onDraw() in the following way:
protected void onDraw(Canvas canvas) {
    canvas.clipRect(new Rect(-100,-100,100,100), Region.Op.UNION);
    canvas.drawCircle(0, 0, 100, circlePaint);
}


text:
Q: How to use the non-const getter if there's a const one too? If I have a class with getters of return type both const and non-const, how can I use the non-const one?
The class (MeshManipulator.h):
namespace vortex::meshSculptEngine
{
    class MeshManipulator
    {
    public:
        ...
        topologyMesh::Mesh* getMesh();
        const topologyMesh::Mesh* getMesh() const;
        ...
    };
}

The code where I want to use the Mesh (SimpleMeshCorrector.cpp):
void SimpleMeshCorrector::smoothBoundaryLoops(float distance)
{
    if (!_boundaryLoops.empty()) {
        Mesh* mesh = getEngine()->getManipulator()->getMesh();
        ...
    }
}

I get the following error:

A value of type "const vortex::topologyMesh::Mesh*" cannot be used to
initialize an entity of type "vortex::topologyMesh::Mesh*"

I can use const_cast but I just don't feel that this is the correct way to solve this problem.

A: Root cause is (as clarified in comments) that getManipulator() returns a const MeshManipulator*. On a const object, only methods declared const can be called. Thus, the const getter is always called and never the non-const version.
Depending on the context, there are three ways to go on:

*

*Use (or write) a method that returns a mutable MeshManipulator*.

*Copy the const Mesh* to a local, mutable object.

*Use const_cast<Mesh*> to be able to mutate the object in place. This, however, defeats the purpose of constness. What's more, if the object pointed to was declared const this will result in undefined behavior. So use with care.


text:
Q: MongoDB - avoid "downtime" during import? I am using MongoLab to store 60 datasets that update a few times per month.
I currently have an import script that drops the database and then reimports the 60 or so CSV files.
//drop -> then insert each indicator
db.dropDatabase(function(err, result){
....
db.collection("indicators").insert(group, grpCallback);

During import, this obviously yields X minutes with an empty/non-complete database.
What are some options for avoiding this "downtime" using either the single instance I have today or a more advanced MongoDB configuration?


text:
Q: How to add a keystore to an Eclipse project I've asked a similar question not too long ago, but I feel like I didn't ask it correctly.  I've been tasked with creating a project that consumes a web service.  This web service requires a certificate to send ajax calls to.  My team member sent me a jks file that contains the relevant cert, but I'm unsure on how to actually add it to my eclipse project, and I can't find any information through searches.
How do I add the keystore to my project so that I have the necessary PKC and AC to make AJAX calls?

A: The keystore (with certificate) should be included/assigned in your Tomcat instance.  Use the following link to do so:
http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html


text:
Q: How to post to someone's FaceBook / Twitter w/o their password (but with their permission)? I don't use either FaceBook or Twitter, so I am somewhat hampered here.
A friend is going on a once in a life-tine yacht journey and their will be a satellite modem which reports latitude/longitude (and some more data) data on a regular basis. This data gets stored in a database, to which I will have access.
My friend wants to Face/Tweet updates, hopefully with a Google Maps map. He doesn't want to give me his passwords as that would give me full access and let me read his private stuff.
I quite understand that, but what are my options? Obviously, the APIs to FaceTweet won't allow me to post without (his) credentials. Can I create accounts of my own and he can then configure his FaceTweet to say "anything that gets posted there, I want to post it on my site too"? Does Face/Tweet offer such a facility?
The alternative seems to be to code a desktop app to scan the database regularly and post new updates using his password which he must enter into the app, so the app must run on his home PC.
Of course, that is not perfect; if his home PC crashes when he is away then the updates will cease. If it runs on my server, then no problem, but he doesn't want to give me his password and lives too far away to come here and type it in himself.
Can anyone advise me as to how best to implement this? Thanks in advance.

A: For Facebook you will have to create an application with "Post on your behalf" permission.
Update:
For Twitter it's much trickier: you will have to deal with OAuth tokens to access someone's account after you ask user to authenticate. Here is a fine article on that. You will have to press some free PDF download on our members page and it will ask for you e-mail, but you can press cancel and it redirects you to article anyway.


text:
Q: ENCODER-DECODER : Decoder not accepting large string value Actually I made this program just for fun. It comprises of an encoder and a decoder. The encoder works as follows :

*

*user will input a string

*it will take out each character one by one from the string

*it will store its ASCII equivalent in a variable

*will generate a binary equivalent of this ASCII value

*then it will print this binary equivalent in form of "dots('.')" and "spaces(' ')"

*there is a DOT for every "one('1')" and a SPACE for every "zero('0')"

The decoder works just in the opposite way. It takes this code from the user, which is in the form of dots and spaces, and prints the corresponding string. Since the ASCII value of characters that I'm working upon range from 32(space) to 126(~), thus the maximum length of the binary equivalent can be 7. Therefore if the length of a binary equivalent is less than 7 the encoder will automatically add required amount of zeroes before the binary equivalent to make the length 7, so that the decoder can easily decode. The decoder works well for the codes of small sentences. But when I try to input the code of a long sentence(such as the one I'm writing) it does not accept in Bluej but accepts it in command-prompt; can anybody tell me why is this happening. Everybody please try this program on command prompt or whatever you guys use. Please suggest any ideas to improve my program and make the code more complicated.
This is the code :
import java.io.*;

class ed2 {

    BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));

    void encode() throws InterruptedException, IOException {
        String rs, ren;

        encoder_symbol();
        rs = encode_input();
        ren = encode_find(rs);
        encode_display(ren);
    }

    void decode() throws InterruptedException, IOException {
        String rs, rde;

        decoder_symbol();
        rs = decode_input();
        rde = decode_find(rs);
        decode_display(rde);
    }

    void encoder_symbol() throws InterruptedException // just for fun
    {
        System.out.println("********  ***         ***  *********  ************  ******      ********  *****");
        Thread.sleep(100);
        System.out.println("********  ****        ***  *********  ************  ********    ********  *** **");
        Thread.sleep(100);
        System.out.println("***       *****       ***  ***        ***      ***  ***   ***   ***       ***  **");
        Thread.sleep(100);
        System.out.println("***       *** **      ***  ***        ***      ***  ***    ***  ***       *** **");
        Thread.sleep(100);
        System.out.println("******    ***  **     ***  ***        ***      ***  ***    ***  ******    *****");
        Thread.sleep(100);
        System.out.println("******    ***   **    ***  ***        ***      ***  ***    ***  ******    *****");
        Thread.sleep(100);
        System.out.println("***       ***     **  ***  ***        ***      ***  ***    ***  ***       *** **");
        Thread.sleep(100);
        System.out.println("***       ***      ** ***  ***        ***      ***  ***   ***   ***       ***  **");
        Thread.sleep(100);
        System.out.println("*******   ***       *****  *********  ************  ********    ********  ***   **");
        Thread.sleep(100);
        System.out.println("*******   ***        ****  *********  ************  ******      ********  ***    **");
        Thread.sleep(2700);

        System.out.println();
        System.out.println();
    }

    void decoder_symbol() throws InterruptedException // just for fun
    {
        System.out.println("******      ********  *********  ************  ******      ********  *****");
        Thread.sleep(100);
        System.out.println("********    ********  *********  ************  ********    ********  *** **");
        Thread.sleep(100);
        System.out.println("***   ***   ***       ***        ***      ***  ***   ***   ***       ***  **");
        Thread.sleep(100);
        System.out.println("***    ***  ***       ***        ***      ***  ***    ***  ***       *** **");
        Thread.sleep(100);
        System.out.println("***    ***  ******    ***        ***      ***  ***    ***  ******    *****");
        Thread.sleep(100);
        System.out.println("***    ***  ******    ***        ***      ***  ***    ***  ******    *****");
        Thread.sleep(100);
        System.out.println("***    ***  ***       ***        ***      ***  ***    ***  ***       *** **");
        Thread.sleep(100);
        System.out.println("***   ***   ***       ***        ***      ***  ***   ***   ***       ***  **");
        Thread.sleep(100);
        System.out.println("********    ********  *********  ************  ********    ********  ***   **");
        Thread.sleep(100);
        System.out.println("******      ********  *********  ************  ******      ********  ***    **");
        Thread.sleep(1000);

        System.out.println();
        System.out.println();
    }

    String encode_input() throws IOException {
        String s;
        System.out.println("ENTER THE STRING TO BE ENCODED");
        s = obj.readLine();
        return (s);
    }

    String decode_input() throws IOException {
        String s;
        System.out.println("ENTER THE CODE TO BE DECODED");
        s = obj.readLine();
        return (s);
    }

    String encode_find(String s)// converting the string into its binary
                                // equivalent
    {
        int ac, i, j, l, chklen;
        String bc, en = "";
        char ic;
        l = s.length();
        for (i = 0; i < l; i++) {
            ic = s.charAt(i); // takes out every character
            bc = "";
            ac = (int) ic; // ASCII value of this character
            while (ac != 0) {
                bc = Integer.toString((ac % 2)) + bc; // converting the ASCII
                                                      // value into binary
                                                      // equivalent
                ac = ac / 2;
            }
            chklen = bc.length();// length of the binary equivalent
            if (chklen < 7) {
                for (j = 1; j <= (7 - chklen); j++) // increasing the length of
                                                    // binary equivalent so that
                                                    // it becomes equal to 7
                {
                    bc = "0" + bc;
                }
            }
            en = en + bc; // concatenating all the binary equivalent into one
                          // string
        }
        return (en);
    }

    String decode_find(String s)// converts binary(i.e. in the form of dots and
                                // space) to decimal
    {
        int f;// for the index of every character of code
        long l, i, j, ac;
        char c;
        String de = "";

        l = s.length();
        f = 0;// index of first caharcter
        for (i = 0; i < (l / 7); i++)// since the length of every binary
                                     // equivalent of a character is 7 therefore
                                     // there will be (length/7) characters in a
                                     // code of length l
        {
            ac = 0;// intializes the decimal(ASCII) equivalent to zero
            for (j = 6; j >= 0; j--)// loop will work 7 times for every binary
                                    // equivalent of a character
            {
                c = s.charAt(f);// takes out every dot or space
                if (c == '.')// it means that c corresponds to 'one'
                {
                    ac = ac + ((int) Math.pow(2, j));// converting binary into
                                                     // decimal(ASCII)
                                                     // equivalent by adding all
                                                     // the powers of 2 which
                                                     // correspond to one('.')
                }
                f++;// increasing the index for next character of binary
                    // equivalent
            }
            de = de + ((char) ac);// converts the ASCII equivalent into
                                  // character and then concatenates it with the
                                  // intitial string
        }
        return (de);
    }

    void encode_display(String en)// displays the code
    {
        int i, l;
        char ic;
        System.out.println("YOUR ENCODED MESSAGE IS :");
        l = en.length();
        for (i = 0; i < l; i++) {
            ic = en.charAt(i);
            if (ic == '1')// for every 'one' it will print '.'(dot)
            {
                System.out.print(".");
            } else if (ic == '0')// for every 'zero' it will print ' '(space)
            {
                System.out.print(" ");
            }
        }
    }

    void decode_display(String de) {
        System.out.println(de);
    }

    public static void main(String args[]) throws IOException, InterruptedException {
        BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));

        char ch;

        ed2 ed = new ed2();

        System.out.println("PRESS 'E' TO ENCODE A MESSAGE OR PRESS 'D' TO DECODE A MESSAGE");
        ch = (char) obj.read();

        if ((ch == 'e') || (ch == 'E')) {
            ed.encode();
        } else if ((ch == 'd') || (ch == 'D')) {
            ed.decode();
        }
    }
}


text:
Q: FFMPEG bottleneck in relaying data from a dshow camera to stdout PIPE without any processing or conversion I have a USB camera (FSCAM_CU135) that can encode the video to MJPEG internally and it supports DirectShow. My goal is to retrieve the binary stream of the encoded video as it is (without decoding or preview) and send it to my program for further processing.
I choose to use FFMPEG to read the MJPEG stream and pipe to stdout so that I can read it using Python's subprocess.Popen .
ffmpeg -y -f dshow -vsync 2 -rtbufsize 1000M -video_size 1920x1440 -vcodec mjpeg -i video="FSCAM_CU135" -vcodec copy -f mjpeg pipe:1

At this resolution, the camera is able to capture and transmit at 60 fps.
In this case, I expect FFMPEG to pass the data as fast as possible with no calculation.
With the output of FFMPEG I can tell how fast it moves the data from rtbuffer to the output pipe.
With just one camera, FFMPEG works with no problem and move the data at 60 fps.
However, when I run 2 cameras simultaneously, the cameras still generate data at 60 fps but FFMPEG can only move the data around 55 fps. This means that I am unable to consume the video in realtime and the buffer consumption will be larger over time.
I guess that FFMPEG didn't just simply move the data but did some processing such as searching for the beginning, the end, and the timestamp of each video frame so that it can count frames and report.
Is there a way to force FFMPEG to not doing those things and focus on passing the data only to make it faster?
If I purely use directshow API without FFMPEG, can it be faster?


text:
Q: Why does moving WCF proxy from Silverlight into a portable class library require CreateChannel to be implemented? I have a WCF service which is called from a Silverlight UI. The proxy is defined in the Silverlight code and looks like this:
public class MyServiceProxy : ClientBase<IMyService>, IMyService
{
    public IAsyncResult BeginGetId(string name, AsyncCallback callback, object asyncState)
    {
        return this.Channel.BeginGetId(name, callback, asyncState);
    }

    public int EndGetId(IAsyncResult result)
    {
        return this.Channel.EndGetId(result);
    }
}

I now want to call the WCF from a different application which isn't in Silverlight. I thought I'd try to share the proxy by moving it into a portable class library which targets .Net 4 and Silverlight 5.
After moving the class, the interface now wants me to override CreateChannel:
protected override IMyService CreateChannel()

I'm confused what implementation I should be providing here. Is sharing the proxy in a PCL a sensible thing to do or am I going about this the wrong way?

A: I know this question is old now, but I ran into this problem recently and it took me a little while to find the answer, so hopefully this can help someone save some time.
If you target Silverlight in your PCL, then ChannelFactory<T> is not available to you and thus you must create your own implementation of CreateChannel() on ClientBase<T>.
If you want to avoid implementing CreateChannel() yourself, then you can only target .NET 4.5 and Windows 8 and/or Windows Phone Silverlight 8.
If you select Windows Phone Silverlight 7 or 7.5, it will automatically require Silverlight 4 and higher. Similarly, if you select Windows Phone Silverlight 8 but a .NET version below 4.5, it will automatically require Silverlight 5. Both will force you to provide you own implementation of CreateChannel().
Targeting Windows Phone 8.1 completely removes ClientBase<T>, because System.ServiceModel is not available in Windows Phone 8.1.


text:
Q: How to show select-app dialog through Javascript? I'm working with an android wrapped app (using web viewer), and I would like to ask the user which app wants to use when pressing in address from my app.
Example pop-up in android (Spanish): https://puu.sh/EEXBK/388b01494d.png
I have tried using the google API launcher which is: https://www.google.com/maps/dir/?api=1&origin=xxx&destination=xxx&travelmode=driving
But this opens directly maps, without asking if you want to use Waze or not.
It is possible with Javascript?
My targets are Maps and Waze.
Any suggestions?
Thanks.

A: check this document for opening waze and for google map check this
you can create url for each one

example waze:
https://www.waze.com/ul?ll=40.75889500%2C-73.98513100&navigate=yes&zoom=17

example google maps:
https://www.google.com/maps/@?api=1&map_action=map&center=-33.712206,150.311941&zoom=12&basemap=terrain

A: You can use these URLs:
   appleURL = "http://maps.apple.com/?daddr=\(latitude),\(longitude)"
   googleURL = "comgooglemaps://?daddr=\(latitude),\(longitude)&directionsmode=driving"
   wazeURL = "waze://?ll=\(latitude),\(longitude)&navigate=false"

For more see this link


text:
Q: How do i draw an accurate parametric eq curve given gain, freq, and q? After a lot of googling I still can't find an equation to give me the path I need. I am creating a gui for a parametric eq and just can't get the curve drawing to look or feel accurate. Although I know most eq plugins are just eye candy giving a representation of the actual audio processing, I stil want it be at least as accurate as what is out there.
I have tried using a single CubicCurve2D and also a pair of QuadCurves. It has become clear that using these is not going to do what I want and I will need to just use the actual equation and create a path.
I am doing the project in clojure so if anyone can give an example of how I might plot the x y coords given gain, freq, and q, or even just a generic equation to do so in any language would be a huge help
thanks

A: Incanter is a great tool for doing chart plotting in Clojure.
Here's a simple parametric xy-plot:
(ns incantertest
  (:use [incanter core stats charts]))

(let [points (map
               (fn [t]
                 (let [t (double t)]
                   [(+ (Math/sin (* t 0.01)) (Math/sin (* t 0.08)))
                    (+ (Math/cos (* t 0.2)) (Math/sin (* t 0.13)))]))
               (range 1000))
         xs (map first points)
         ys (map second points)]
     (view (incanter.charts/xy-plot xs ys)))

Which produces something like:


text:
Q: Background-image - Webp, display in older Safari versions I need to display my .png in background-image in older Safari versions and for the rest of browsers just display .webp format.
I need to do it only throught CSS and HTML. No script insluded. (@supports doesn´t support older Safari versions as well).
Thank you for any advice!

A: The webp format is not supported by Safari as of today, and I'm not sure if it is planned for implementation in the near future. But you can give the browser a choice whether to use webp or jpg like so.
The browsers are smart enough to download and use only the best supported image.
You can give a fallback or default img
refer this - How to add webp support in Safari browser

A: <picture>
  <source srcset="
    /uploads/img_small.webp 1x,
    /uploads/img_big.webp 2x" type="image/webp">
  <source srcset="
    /uploads/img_small.jpg 1x,
    /uploads/img_big.jpg 2x" type="image/jpeg">

</picture>

The above example allows the browser to choose either a .jpeg or .webp image.
And as far as .webp goes, it is available on Safari 14
Answer Source

A: <picture>
  <source type="image/svg+xml" srcset="stackoverflow.svg">
  <source type="image/webp" srcset="stackoverflow.webp">

</picture>

This allows browser to reject the unsupported file types.
Source

A: Just for completenes sake, image-set is the way to set webp background-image with fallback:
.some-class {
  background-image: url('fallback-image.png');
  background-image: image-set(
    url('image.webp') 1x,
    url('image@2x.webp') 2x,
    url('fallback-image.png') 1x,
    url('fallback-image@2x.png') 2x
  );
}

The webkit-prefix might have to be used depending on the browser. And to this day firefox does not seem to support it. Check out caniuse for more info.
Edit: Just tried it myself in firefox and the webkit-prefix seems to work. This just shows that one should rather trust the official docs and test it yourself.


text:
Q: I have a JSON file with 379000 lines and it is full with double quotes inside the string objects,how can I delete all of them? The invalid format:
"studwhere": "Academia de Muzica "Gheorghe Dima" Cluj-Napoca",
Expected result:
"studwhere": "Academia de Muzica Gheorghe Dima Cluj-Napoca",
or
"studwhere": "Academia de Muzica \"Gheorghe Dima\" Cluj-Napoca",


text:
Q: Matplotlib PGF Export: Error Dimension too large I have an issue I could not find any other threads on, only for people who create their pgf plot manually. I have created a boxplot using matplotlib and Seaborn. I want to export this plot to TeX, so I can include it natively in my thesis.
I've first tried using the matplotlib pgf export. While this has worked for me in many cases, this time, it didn't. I get various errors:

img/exampleplot.pgf|1000 error| Dimension too large.
img/exampleplot.pgf|1001 error| Dimension too large.
img/exampleplot.pgf|1002 error| Dimension too large.
img/exampleplot.pgf|1003 error| Dimension too large.
img/exampleplot.pgf|1018 error| Dimension too large.
img/exampleplot.pgf|1019 error| Dimension too large.
img/exampleplot.pgf|1020 error| Dimension too large.
img/exampleplot.pgf|1021 error| Dimension too large.
img/exampleplot.pgf|1036 error| Dimension too large.
img/exampleplot.pgf|1037 error| Dimension too large.
img/exampleplot.pgf|1038 error| Dimension too large.
img/exampleplot.pgf|1039 error| Dimension too large.
img/exampleplot.pgf|1054 error| Dimension too large.
img/exampleplot.pgf|1055 error| Dimension too large.
img/exampleplot.pgf|1056 error| Dimension too large.
img/exampleplot.pgf|1057 error| Dimension too large.

You can find the pgf code at the end of this post. The only thing I've noticed is that other people had similar issues when using log scale boxplots (I am using log scale boxplots as well).
Then, I've tried tikzplotlib, but the plot genereted by it misses the x-ticks and all labels that are there when using the matplotlib pdf export
Tikzplotlib Result:

How it should look like (don't mind the rotation, this is fine):

So I am lost on how to continue here. Any help on how to either fix the matplotlib pgf export or the tikzplotlib result would be appreciated.
Here is the matplotlib pgf source: https://pastebin.com/JH7ZCvrb

A: Round about line 1000 of the .pgf file, you have four instances where things are drawn at a coordinate of (1.004445in, -2250.839168in), I'm guessing 2250 inches is more than TeX can handle.
Try commenting out everything from the \begin{pgfscope} at line 989 to the \end{pgfscope} at line 1060, and check if the output is as it should be. I get


text:
Q: django-filter: TypeError at /goods/ __init__() got an unexpected keyword argument 'name' I am learning Django REST Framework. And I want to use the django-filter in django rest framework to choose the result I want.
I wrote a filter.py to get goods whose price is between pricemin and pricemax:
class GoodsFilter(filters.FilterSet):
    pricemin = filters.NumberFilter(name="shop_price", lookup_expr='gte')
    pricemax = filters.NumberFilter(name="shop_price", lookup_expr='lte')

    class Meta:
        model = Goods
        fields = ['pricemin', 'pricemax']

then I used this filter in view.py:
class GoodsListViewSet(mixins.ListModelMixin,viewsets.GenericViewSet):
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer
    pagination_class = GoodsPagination
    filter_backends = (DjangoFilterBackend,)
    filter_class = GoodsFilter

when I run my project, there is an error like this:
TypeError at /goods/
__init__() got an unexpected keyword argument 'name'

I did not use argument 'name' in my code, so I have no idea about this error.
Traceback:
Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/goods/

Django Version: 2.0.3
Python Version: 3.6.4
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'DjangoUeditor',
 'users.apps.UsersConfig',
 'goods.apps.GoodsConfig',
 'trade.apps.TradeConfig',
 'user_operation.apps.UserOperationConfig',
 'crispy_forms',
 'xadmin',
 'rest_framework',
 'django_filters']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:
File "C:\Users\Harry\Envs\testvir2\lib\site-packages\django\core\handlers\exception.py" in inner
  35.             response = get_response(request)

File "C:\Users\Harry\Envs\testvir2\lib\site-packages\django\core\handlers\base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\Harry\Envs\testvir2\lib\site-packages\django\core\handlers\base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Harry\Envs\testvir2\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
  54.         return view_func(*args, **kwargs)

File "C:\Users\Harry\Envs\testvir2\lib\site-packages\rest_framework\viewsets.py" in view
  103.             return self.dispatch(request, *args, **kwargs)

File "C:\Users\Harry\Envs\testvir2\lib\site-packages\rest_framework\views.py" in dispatch
  483.             response = self.handle_exception(exc)

File "C:\Users\Harry\Envs\testvir2\lib\site-packages\rest_framework\views.py" in handle_exception
  443.             self.raise_uncaught_exception(exc)

File "C:\Users\Harry\Envs\testvir2\lib\site-packages\rest_framework\views.py" in dispatch
  480.             response = handler(request, *args, **kwargs)

File "C:\Users\Harry\Envs\testvir2\lib\site-packages\rest_framework\mixins.py" in list
  40.         queryset = self.filter_queryset(self.get_queryset())

File "C:\Users\Harry\Envs\testvir2\lib\site-packages\rest_framework\generics.py" in filter_queryset
  152.             queryset = backend().filter_queryset(self.request, queryset, self)

File "C:\Users\Harry\Envs\testvir2\lib\site-packages\django_filters\rest_framework\backends.py" in filter_queryset
  94.         if not filterset.is_valid() and self.raise_exception:

File "C:\Users\Harry\Envs\testvir2\lib\site-packages\django_filters\filterset.py" in is_valid
  206.         return self.is_bound and self.form.is_valid()

File "C:\Users\Harry\Envs\testvir2\lib\site-packages\django_filters\rest_framework\filterset.py" in form
  24.         form = super().form

File "C:\Users\Harry\Envs\testvir2\lib\site-packages\django_filters\filterset.py" in form
  258.             Form = self.get_form_class()

File "C:\Users\Harry\Envs\testvir2\lib\site-packages\django_filters\filterset.py" in get_form_class
  250.             for name, filter_ in self.filters.items()])

File "C:\Users\Harry\Envs\testvir2\lib\site-packages\django_filters\filterset.py" in <listcomp>
  250.             for name, filter_ in self.filters.items()])

File "C:\Users\Harry\Envs\testvir2\lib\site-packages\django_filters\filters.py" in field
  138.             self._field = self.field_class(label=self.label, **field_kwargs)

File "C:\Users\Harry\Envs\testvir2\lib\site-packages\django\forms\fields.py" in __init__
  330.         super().__init__(max_value=max_value, min_value=min_value, **kwargs)

File "C:\Users\Harry\Envs\testvir2\lib\site-packages\django\forms\fields.py" in __init__
  254.         super().__init__(**kwargs)

Exception Type: TypeError at /goods/
Exception Value: __init__() got an unexpected keyword argument 'name'

A: From the Migrating to 2.0 guide,

Filter.name renamed to Filter.field_name (#792)
The filter name has been renamed to field_name as a way to disambiguate the filter's attribute name on its FilterSet class from the field_name used for filtering purposes.

So, from django-filter==2.0 onwards, use field_name instead of name
class GoodsFilter(filters.FilterSet):
    pricemin = filters.NumberFilter(field_name="shop_price", lookup_expr='gte')
    pricemax = filters.NumberFilter(field_name="shop_price", lookup_expr='lte')

    class Meta:
        model = Goods
        fields = ['pricemin', 'pricemax']


text:
Q: Drawing complex polygons with PyQGIS In PyQGIS, I kwnow how to draw polygons starting from a list of points which represent the nodes of the shape. An example of list could be this:
# First polygon
list_1 = [QgsPoint(0,0),QgsPoint(0,50),QgsPoint(50,50),QgsPoint(50,0)]

# Second polygon
list_2 = [QgsPoint(10,10),QgsPoint(10,30),QgsPoint(30,30),QgsPoint(30,20)]

which lead to the representation of these polygons:

If I manually do some operations, I can create a unique polygon like this one:

My question is: Is there a specific rule or a particular way to handle points (in or outside a list) for obtaining the result above? I only know that, for simple polygons, the points must to be ordered clockwise.
My goal is similar to that one in this question, but I think that the context is different here.

A: You need this kind of list (where the first and last point match on each sub-list):
pol = [[QgsPoint(0,0),QgsPoint(0,50),QgsPoint(50,50),QgsPoint(50,0),QgsPoint(0,0)],
       [QgsPoint(10,10),QgsPoint(10,30),QgsPoint(30,30),QgsPoint(30,20),QgsPoint(10,10)]]

pol_wkt = QgsGeometry.fromPolygon(pol).exportToWkt()

print pol_wkt

I created an objet of QgsGeometry (Python Console of QGIS) to get its expression in WKT format. By using QuickWKT plugin, it can be observed that the result is identical to yours.

Editing Note:
As order (outer ring must include inner rings) and intersection of inner polygons is very important, it could be necessary to validate the geometry before printing it. In next case, where the original order of sub-lists was interchanged, the geometry is not valid:
pol = [[QgsPoint(10,10),QgsPoint(10,30),QgsPoint(30,30),QgsPoint(30,20),QgsPoint(10,10)],
       [QgsPoint(0,0),QgsPoint(0,50),QgsPoint(50,50),QgsPoint(50,0),QgsPoint(0,0)]]

if QgsGeometry.fromPolygon(pol).isGeosValid():
    pol_wkt = QgsGeometry.fromPolygon(pol).exportToWkt()

    print pol_wkt

else:
    print "geometry is not valid"


text:
Q: How to solve this integral on the unit interval I'm trying to solve the following integral
$$
I(x)= \int_0^1  \frac{[1-(1-w)^2][1-w^2]}{[1-w(1-w)]^2}\exp\left( -
\frac{1}{xw(1-w)}
\right)dw.
$$
for $x>0$. The aim is to obtain some closed form solution, or a solution in terms of some special function depending on $x$.
I've attempted a solution through the change of variable $w=\frac{1}{2}(1+\tanh(t))$ and the properties of hyperbolic functions. This has led me to
\begin{equation}
\begin{split}
I(x)&= 2\int_{-\infty}^{\infty}\frac{5+2(e^{2t}+e^{-2t})}{(e^{2t}+e^{-2t}+1)(e^{2t}+e^{-2t}+2)^2} \exp\left(
-\frac{1}{x} (e^{2t}+e^{-2t})
\right)dt\\
&=\int_0^\infty \frac{1}{s}\frac{5+2(s+s^{-1})}{(s+s^{-1}+1)(s+s^{-1}+2)^2}\exp\left(
-\frac{1}{x}(s+s^{-1})
\right)ds\\
&=:\int_0^\infty f(s) ds
\end{split}
\end{equation}
Afterwards, I've tried to split the integral as $\int_0^1f(s)ds$ and $\int_1^\infty f(s)ds$ and perform the change of variable $y=s+1/s$, but this hasn't produced anything useful (apparently). Any suggestion would be much appreciated.

A: With $w=\frac{1+t}2$, the integral simplifies to
$$I(x) =\int_0^1 \left( 1- \left(\frac{4t}{t^2+3}\right)^2\right)e^{-\frac4{x(1-t^2)}}dt
$$
which is unlikely to yield a close-form result.


text:
Q: How can I convert a NSString that contains timezone info to NSDate? I am receiving JSON data from a web service where the dates are in string format and includes the timezone format as you can see below:
{
        currencyName = EUR;
        itemID = 101064027138011;
        price = "6.95";
        priceIncTAX = 1;
        validFromDate = "2016-11-03T00:00:00";
        validToDate = "2020-01-01T00:00:00";
}

When I try convert the string that contains timezone into NSDate the return value is always nil/null, if I manually send in a string without the timezone info i,e @"2016-11-03" then the conversion works fine BUT the resulting date includes timezone offset etc and does not adhere to my dateFormatter
I use the following code to show the challenge at hand
NSString *validTo = @"2016-11-03";
NSString *validFrom = @"2020-11-03T00:00:00";

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-MM-dd"];
NSDate *validToDate = [dateFormat dateFromString:validTo];
NSDate *validFromDate = [dateFormat dateFromString:validFrom];

if([NWTillHelper isDebug] == 1) {
    NSLog(@"WebServices:fetchPriceList:validToDate: >>>> %@ <<<<", validToDate);
    NSLog(@"WebServices:fetchPriceList:validFromDate: %@", validFromDate);
}

The debugs tell me that the string without tz info works fine (apart from not adhering to my dateFormatter) but the string with tz info does not.
How can I convert a string that contains tz info to NSDate and why is it not adhering to my dateFormatter when I send in a string without timezone information.
016-11-27 12:09:22.194 NWMobileTill[4275:235671] WebServices:fetchPriceList:validToDate: >>>> 2016-11-02 16:00:00 +0000 <<<<
2016-11-27 12:09:22.194 NWMobileTill[4275:235671] WebServices:fetchPriceList:validFromDate: (null)

A: Change your date formatter from this
[dateFormat setDateFormat:@"YYYY-MM-dd"];

To this
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];

As your format is different which you are getting from server and in your code you are using different date format
Edit
As @rmaddy mentioned in his comment you are not getting timezone in your date string which you are getting from your server and date formatter will convert you string to date as per the user's current time zone.
As a suggestion I would like to mention to you that your date string must contain timezone as well something like this

2016-11-27T10:39:57-05:30

This string contains IST timezone and with your date formatter which is
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];

You will get the date as per the timezone of your date string not as per user's locale.


text:
Q: React Native : BLE, Discover & Broadcast (advertise data) I'm very new to BLE APIs and capabilities. I want to achieve a "simple" thing. Let's say I'm developing the APP-X. I want to be able to scan other phone around me, with APP-X installed (exactly like this app here https://www.tracetogether.gov.sg/ ). I want to scan and filter the wanted devices via a "simple" metadata (advertising data ? specific for my app) within the signal emitted by the concerned phones. I'm stuck because Idk how to "emit" (broadcast) that custom signal.
Can you please help me find a way to do this in RN ?
I have already check those libs:

*

*https://github.com/Polidea/react-native-ble-plx : but they have noticed that the lib does not support communicating between phones using BLE (Peripheral support)

*https://github.com/innoveit/react-native-ble-manager : Didn't see any Advertising API there

Many thanks

A: I'm currently using React Native Ble PLX !
And indeed, they don't support ble peripheral.
In the react native ble plx, i found an issue when a developper posted a link to a library that can do advertising :
https://github.com/petrbela/react-native-peripheral
But it seems Android not supported ?
Another do an advertising :
https://github.com/himelbrand/react-native-ble-peripheral#readme
But i don't know if it's the best way to achieve what you want.


text:
Q: Is there a way to test for enum value in a list of candidates? (Java) This is a simplified example. I have this enum declaration as follows:
public enum ELogLevel {
    None,
    Debug,
    Info,
    Error
}

I have this code in another class:
if ((CLog._logLevel == ELogLevel.Info) || (CLog._logLevel == ELogLevel.Debug) || (CLog._logLevel == ELogLevel.Error)) {
    System.out.println(formatMessage(message));
}

My question is if there is a way to shorten the test.  Ideally i would like somethign to the tune of (this is borrowed from Pascal/Delphi):
if (CLog._logLevel in [ELogLevel.Info, ELogLevel.Debug, ELogLevel.Error])

Instead of the long list of comparisons. Is there such a thing in Java, or maybe a way to achieve it?  I am using a trivial example, my intention is to find out if there is a pattern so I can do these types of tests with enum value lists of many more elements.
EDIT: It looks like EnumSet is the closest thing to what I want. The Naïve way of implementing it is via something like:
if (EnumSet.of(ELogLevel.Info, ELogLevel.Debug, ELogLevel.Error).contains(CLog._logLevel))

But under benchmarking, this performs two orders of magnitude slower than the long if/then statement, I guess because the EnumSet is being instantiated every time it runs. This is a problem only for code that runs very often, and even then it's a very minor problem, since over 100M iterations we are talking about 7ms vs 450ms on my box; a very minimal amount of time either way.
What I settled on for code that runs very often is to pre-instantiate the EnumSet in a static variable, and use that instance in the loop, which cuts down the runtime back down to a much more palatable 9ms over 100M iterations.
So it looks like we have a winner!  Thanks guys for your quick replies.

A: what you want is an enum set
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/EnumSet.html
put the elements you want to test for in the set, and then use the Set method contains().
import java.util.EnumSet;

public class EnumSetExample
{
  enum Level { NONE, DEBUG, INFO, ERROR };

  public static void main(String[] args)
  {
    EnumSet<Level> subset = EnumSet.of(Level.DEBUG, Level.INFO);

    for(Level currentLevel : EnumSet.allOf(Level.class))
    {
      if (subset.contains(currentLevel))
      {
        System.out.println("we have " + currentLevel.toString());
      }
      else
      {
        System.out.println("we don't have " + currentLevel.toString());
      }
    }
  }

}

A: There's no way to do it concisely in Java. The closest you can come is to dump the values in a set and call contains(). An EnumSet is probably most efficient in your case. You can shorted the set initialization a little using the double brace idiom, though this has the drawback of creating a new inner class each time you use it, and hence increases the memory usage slightly.

A: In general, logging levels are implemented as integers:
public static int LEVEL_NONE  = 0;
public static int LEVEL_DEBUG = 1;
public static int LEVEL_INFO  = 2;
public static int LEVEL_ERROR = 3;

and then you can test for severity using simple comparisons:
if (Clog._loglevel >= LEVEL_DEBUG) {
    // log
}

A: You could use a list of required levels, ie:
List<ELogLevel> levels = Lists.newArrayList(ELogLevel.Info,
        ELogLevel.Debug, ELogLevel.Error);
if (levels.contains(CLog._logLevel)) {
    //
}


text:
Q: Get the list of fitted GLIF model ids I want to look at some statistics over many cells of the GLIF model parameters that are already fitted in the database.
From the tutorial [1], I understand how to get the fitted parameters of a single model using GlifApi().get_neuronal_models_by_id(neuron_model_id). But how can I get a relevant list of neuron models ids ?
I already found how to get a list of cell. So getting the list of models that were fitted to a particular cell is also relevant.
[1] http://alleninstitute.github.io/AllenSDK/glif_models.html

A: If you have a cell's ID, you can use the function in GlifApi called get_neuronal_models() to access that list of neuronal model IDs. The function takes a list of cell IDs and returns metadata (including neuronal model information) associated with those cells.
For example:
from allensdk.api.queries.glif_api import GlifApi

# Specify the IDs of the cells you are interested in
cell_ids = [486239338, 323540736]

# Get the metadata associated with those cells
ga = GlifApi()
nm_info = ga.get_neuronal_models(ephys_experiment_ids=cell_ids)

# Print out the IDs and names of models associated with those cells
for cell_info in nm_info:
    print "Cell ID", cell_info["id"]
    for nm in cell_info["neuronal_models"]:
        print "Neuronal model ID:", nm["id"]
        print "Neuronal model name:", nm["name"]

If you run that example, you see that you get information about both GLIF models and biophysical models. If you want to limit it to GLIF models, you can use the neuronal model template IDs to do that.
# Define a list with all the GLIF neuronal model templates
GLIF_TEMPLATES = [
    395310469, # GLIF 1 - LIF
    395310479, # GLIF 2 - LIF + reset rules
    395310475, # GLIF 3 - LIF + afterspike currents
    471355161, # GLIF 4 - LIF + reset rules + afterspike currents
    395310498, # GLIF 5 - GLIF 4 + threshold adaptation
]

# Only print info for the GLIF models
for cell_info in nm_info:
    print "Cell ID", cell_info["id"]
    for nm in cell_info["neuronal_models"]:
        if nm["neuronal_model_template_id"] in GLIF_TEMPLATES:
            print "Neuronal model ID:", nm["id"]
            print "Neuronal model name:", nm["name"]


text:
Q: Regex replace string but not inside html tag I want to replace a string in HTML page using JavaScript but ignore it, if it is in an HTML tag, for example:
visit google search engine
you can search on google tatatata...

I want to replace google by google, but not here:
visit google search engine
you can search on google tatatata...

I tried with this one:
regex = new RegExp(">([^<]*)?(google)([^>]*)?<", 'i');
el.innerHTML =  el.innerHTML.replace(regex,'>$1$2$3<');

but the problem: I got google inside the  tag:
visit google search engine
you can search on google tatatata...

How can fix this?

A: You'd be better using an html parser for this, rather than regex. I'm not sure it can be done 100% reliably.

A: You may or may not be able to do with with a regexp. It depends on how precisely you can define the conditions. Saying you want the string replaced except if it's in an HTML tag is not narrow enough, since everything on the page is presumably within some HTML tag (BODY if nothing else).
It would probably work better to traverse the DOM tree for this instead of trying to use a regexp on the HTML.

A: Parsing HTML with a regular expression is not going to be easy for anything other than trivial cases, since HTML isn't regular.
For more details see this Stackoverflow question (and answers).

A: I think you're all missing the question here...
When he says inside the tag, he means inside the opening tag, as in the  tag...This is something quite different than text, say, inside a

 tag pair or  . While I don't have the answer yet, I'm struggling with this same problem and I know it has to be solvable using regex. Once I figure it out, i'll come back and post.

A: WORKAROUND
If You can't use a html parser or are quite confident about Your html structure try this:

*

*do the "bad" changing

*repeat replace (<[^>]*)(<[^>]+>) to $1 a few times (as much as You need)

It's a simple workaround, but works for me.
Cons?
Well... You have to do the replace twice for the case  ...  ...> as it removes only first unwanted tag from every tag on the page
[edit:]
SOLUTION
Why not use jQuery, put the html code into the page and do something like this:
$(containerOrSth).find('a').each(function(){
 if($(this).children().length==0){
 $(this).text($(this).text().replace('google','evil'));
 }else{
 //here You have to care about children tags, but You have to know where to expect them - before or after text. comment for more help
 }
});

A: I'm using
regex = new RegExp("(?=[^>]*<)google", 'i');

A: you can't really do that, your "google" is always in some tag, either replace all or none

A: Well, since everything is part of a tag, your request makes no real sense. If it's just the  tag, you might just check for that part. Mainly by making sure you don't have a tailing  tag before a fresh

A: You can do that using REGEX, but filtering blocks like STYLE, SCRIPT and CDATA will need more work, and not implemented in the following solution.
Most of the answers state that 'your data is always in some tags' but they are missing the point, the data is always 'between' some tags, and you want to filter where it is 'in' a tag.
Note that tag characters in inline scripts will likely break this, so if they exist, they should be processed seperately with this method. Take a look at here :
complex html string.replace function

A: I can give you a hacky solution…
Pick a non printable  character that's not in your string….  Dup your buffer… now overwrite the tags in your dup buffer using the non printable character… perform regex to find position and length of match on dup buffer …  Now you know where to perform replace in original buffer


text:
Q: What is the best oscillator to be used in a capacitive soil moisture sensor? I am working on this project where I am going to make a soil moisture sensor. The principal that I'm going to use is the change of capacitance of the soil with moisture. What I'm going to do is make a capacitor that would be buried under the soil, and connect it to an oscillator. Then I'm going to get the output frequency from the oscillator and use it to calibrate and measure the moisture level of soil. I know there had been several discussions about this project on this site and elsewhere on the internet but non of them answers my questions.
When thinking about which oscillator would best suit my project, the thing which popped into my head was to use a 555 timer based oscillator. Then after some research on the internet I read that an oscillator based on 74HC00 (NAND IC) would give better results. I'm including schematics of both the oscillators here. First one is the 74HC00 oscillator and the second is a classic 555 timer based one.

My first question is, Why 74HC00 based oscillator is suitable than a 555 timer based one? or are there any other suggestions (which I love to hear)?
The next question is rather subjective.
After getting the output frequency I am planning to connect the circuit into a speaker and make the frequency audible. That is, a pitch varying sound would be generated when the frequency changes. To do this, first I thought of feeding a sinusoidal wave as the input voltage, then send it through a quadrature oscillator and get a sinusoidal wave as the output. A capacitor in the quadrature oscillator is replaced with my sensor capacitor. This method is in contrast to the other two methods (using 74HC00 and 555) as discussed above as both of them are generating square waves as the output. This very much relates to the audio which I will get as the output.

So my second question is, would it be practical and worthy to use a sinusoidal oscillator instead of a square wave one if I want to get a frequency in the audible range? Are there any perks of using a sinusoidal wave to get a sound instead of using a square wave?

A: There are lots of Oscillator circuits that could work .Circuits that have a grounded cap will be more noise immune .RC oscillator circuits are generally not as stable as LC circuits .These days there are lots of SMD inductors to chose from on the internet so going LC is not a cost penalty .LC circuits generally make sinewaves so they are better from an EMC viewpoint .Chose an LC oscillator circuit that uses a single inductor to keep purchasing easy .I have used a   modified dynatron osc for capacitive liquid sensing .The output level of this circuit is about 600mV peak sinewave .I used a comparetor to square it up for counting by a micro .

A: This is a more comprehensive answer to your questions.
1) In general, a 555 timer will create more frequency drift than the schematic that you found out. While I didn't do the full research to quantify the difference between the two, a quick reading of this article was useful to figure out the main difference. The author of this article stated that 555 timer astable are useful to low importance or utility clocking. With that being said, depending on your end application (I'm assuming some kind of hobby or DIY experiment here), both will work properly and you will not have to bother that much with it. I, however, could be corrected by other members since I never really bothered with clock generation above 100khz (aside from crystal oscillator for PIC microcontroller).
2) Since you will already have a squarewave generated somewhere on your circuit, you will not need to generate one externally. You could choose to buffer it with an op-amp before playing with it to isolate the humidity sensing part and the DJ/hearing part. For your information, if your base frequency is between 1khz and 10 khz, you will have no problem hearing a result. Like I previously stated in the comments, you can transform any square wave into a sine wave by using a bandpass filter (can be combined with the buffer to do it in one go) on the base frequency. To output sound properly, you will need to add an amplifier before your speaker, but that is another question altogether.
Edit: An op-amp buffer circuit is used to separate two different sections of a circuit and prevent problems with impedance. By definition, the input is simply translated to the output with a unity gain. Most of the op-amp basic amplification topology will also act as a buffer (not always true, but most of the time!).  The schematic bellow illustrate a op-amp buffer and a band-pass filter using an op-amp.

simulate this circuit – Schematic created using CircuitLab
Keep in mind that these are simplified explanations to guide you. Before plugging anything, you should sketch out the basic function block of your circuit (oscillator, audio amplifier, capacities soil moisture, frequency readout etc...) and then choose how to implement (wire, create..) each function block. Like it was pointed out in another answer, there are many way to do an oscillator and there are many other way to filter, amplify etc...


text:
Q: Global mutable HashMap in a library I want to have an extendable dictionary linking together Object with a &'static str inside my library. HashMap seems like the right data structure for this, but how do I make it global, initialised on declaration and mutable?
So something like this:
use std::collections::HashMap;

enum Object { A, B, C }

const OBJECT_STR: &'static [&'static str] = &[ "a", "b", "c" ];

static mut word_map: HashMap<&'static str, Object> = {
    let mut m = HashMap::new();
    m.insert(OBJECT_STR[0], Object::A);
    m.insert(OBJECT_STR[1], Object::B);
    m.insert(OBJECT_STR[2], Object::C);
    m
};

impl Object {
...
}

A: This would be possible with the lazy_static crate. As seen in their example. Since mutablity accessing a static variable is unsafe, it would need to wrapped into a Mutex. I would recommend not making the HashMap public, but instead provide a set of methods that lock, and provide access to the HashMap. See this answer on making a globally mutable singleton.

#[macro_use]
extern crate lazy_static;

use std::collections::HashMap;
use std::sync::Mutex;

lazy_static! {
    static ref HASHMAP: Mutex<HashMap<u32, &'static str>> = {
        let mut m = HashMap::new();
        m.insert(0, "foo");
        m.insert(1, "bar");
        m.insert(2, "baz");
        Mutex::new(m)
    };
}

fn main() {
    let mut map = HASHMAP.lock().unwrap();
    map.insert(3, "sample");
}


text:
Q: postgres error when starting Phoenix server I Just made a new app in phoenix. Im following along with the Programming Phoenix book. I am on chapter 3 and after making the files and using:
mix phoenix.server

I get an angry red error saying:
[error] Postgrex.Protocol (#PID<0.234.0>) failed to connect: **
(Postgrex.Error) FATAL 28000 (invalid_authorization_specification):
role "postgres" does not exist

it keeps repeating this over and over.

A: Edit: Changes made to reflect comments.
This will delete all local databases

*

*rm -rf /usr/local/var/postgres && initdb /usr/local/var/postgres -E utf8

*sudo -u <your local username> psql postgres

*CREATE USER postgres SUPERUSER;

*CREATE DATABASE postgres WITH OWNER postgres;
This simply creates the Postgres user

*

*psql -U postgres

*CREATE USER postgres;
Thanks @Dogbert, @mudasobwa