text:
Q: Как стилизовать placeholder? Хочу убрать рамку у плэйсхолдера и как-нибудь его украсить, но не могу понять как:

Нашёл лишь способ изменить цвет и расположение текста в нём:

.trial__form {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background-color: #ffffff;
  border-radius: 5px;
  height: 362px;
  width: 360px;
}

.trial__form ::placeholder {
  color: #b0b0b0;
  position: relative;
  left: 15px;
  top: -5px;
  font-family: 'Open Sans';
  font-size: 14px;
}

.input__trial {
  margin: 0 auto;
  border: 0;
  padding: 5px;
  border-bottom: 1px solid #b0b0b0;
  width: 250px;
}

Try Your FREE Trial Today

  <input class="input__trial" type="text" placeholder="Name">
  <input class="input__trial" type="email" placeholder="Email">
  <input class="input__trial" type="password" placeholder="Password">

  Get Started

A: Рамка принадлежит не плейсхолдеру, а инпуту. Она появляется при фокусе на поле ввода. Ее можно убрать так:

.input__trial:focus {
  outline: none;
  border-bottom: 1px solid green;
}


text:
Q: Ruby: How to print strings from arrays in parallel I have 3 arrays and I'm trying to print the respective strings in parallel. Very new to Ruby. Not sure if I should be concatenating? I'd really like to create a table, but I have no idea how.
My current code:
name = ["Buffy Summers", "Willow Rosenberg", "Xander Harris"]
age = ["17", "16", "18"]
hair_color = ["blonde", "red", "brown"]

print name[0]
print " "
print age[0]
print " "
puts hair_color[0]

print name[1]
print " "
print age[1]
print " "
puts hair_color[1]

print name[2]
print " "
print age[2]
print " "
puts hair_color[2]

Output looks like this:
Buffy Summers 17 Blonde
Willow Rosenberg 16 Red
Xander Harris 18 Brown

I'd really like them to align. I realize that I also should be looping. I'm a beginner.
I want the output to read:
Buffy Summers    17  Blonde
Willow Rosenberg 16  Red
Xander Harris    18  Brown

A: To get the aligning as you want, more information at String#%.
max = name.group_by(&:length).max.first

name.zip(age, hair_color).each do |name, age, hair_color|
  puts "%-#{max}s %s %s" % [name, age, hair_color]
end

=> Buffy Summers    17 blonde
=> Willow Rosenberg 16 red
=> Xander Harris    18 brown

A: Suppose your data were contained in the following four arrays.
name       = ["Buffy Summers", "Willow Rosenberg", "Xander Harris", "Granny", "Lucy"]
age        = ["17", "16", "18", "101", "7"]
hair_color = ["blonde", "red", "brown", "white", "purple"]
col_fmt    = [{justify: :L, pad: 4}, {justify: :R, pad: 2}, {justify: :L, pad: 3}]

Then you could pretty-print as follows.
arr = [name, age, hair_color]
columns = col_fmt.zip(arr.map { |a| a.max_by(&:size).size }).
  map { |h, sz| h.merge(width: sz) }
  #=> [{:justify=>:L, :pad=>4, :width=>16}, {:justify=>:R, :pad=>2, :width=>3},
  #    {:justify=>:L, :pad=>3, :width=>6}]
arr.transpose.each do |a|
  a.zip(columns).each do |attr, fmt|
    print ' ' * fmt[:pad]
    print fmt[:justify] == :L ? attr.ljust(fmt[:width]) : attr.rjust(fmt[:width])
  end
  puts
end
#     Buffy Summers      17   blonde
#     Willow Rosenberg   16   red
#     Xander Harris      18   brown
#     Granny            101   white
#     Lucy                7   purple

A: Please do following
name = ["Buffy Summers", "Willow Rosenberg", "Xander Harris"]
age = ["17", "16", "18"]
hair_color = ["blonde", "red", "brown"]

    name.count.times do |index|
puts "#{name[index]} #{age[index]} #{hair_color[index]}"
end
name.count.times do |index|
  printf "%-20s %-2s %-10s\n", name[index],age[index] , hair_color[index]
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dialog box in Adobe reader is scrambled I use win 7 and Adobe reader 11. After updating from ADobe reader 9 to 10 (automatically) I can´t see a proper dialog boxx when i print the PDF. EIther it har veryyyyy big letters or the text is missing in the Printing option box. I have tried to uninstall and reinstall several times, but there is no difference.
I have also tried to download the sherife sans font.
When I hade Adoobe reader 8, there was no problem.
On an other computer I had the same problem, but I could resolve it by uninstalling and reinstallation Adobe reader.
Rutred

A: This is almost always a function of the printer driver.  First check the mfr's website to see if there are updated drivers available, or else use a different printer with a different driver.
Then check to see if you are using PCL5e, PCL6, Postscript, or a Universal driver.  Usually the most successful driver is the Postscript driver, but if you want PCL functionality, just switch to the alternate of 5e or 6.


text:
Q: how to open new form in another phtml without url change I have put the form for add new address of Address book in address book index page itself without redirecting it to a new page for adding a new address.
I need to open the form html on click of add address without changing the url and redirecting to the http://localhost/customer/address/new/
instead i want to remain in http://localhost/customer/address/ page
1) http://localhost/customer/address/ page UI

2) on clicking + Add New Address i need to put the html of the form which is at http://localhost/customer/address/new/ url

So that Save button will work exactly like as it will in /address/new url form.
How to achieve this.
Since address has /** @var \Magento\Customer\Block\Address\Book $block */
and address new has /** @var \Magento\Customer\Block\Address\Edit $block */ block, so i cannot just put the form phtml from edit.phtml to book.phtml
I cannot put edit.phtml form code in book.phtml it throw error
as in edit.phtml  has it down block
<?php $_company = $block->getLayout()-
>createBlock(\Magento\Customer\Block\Widget\Company::class) ?>
<?php $_telephone = $block->getLayout()-
>createBlock(\Magento\Customer\Block\Widget\Telephone::class) ?>
<?php $_fax = $block->getLayout()-
>createBlock(\Magento\Customer\Block\Widget\Fax::class) ?>

codes like this throw error
<?php if ($_company->isEnabled()): ?>
        <?= $_company->setCompany($block->getAddress()->getCompany())->toHtml() ?>
    <?php endif ?>

where $_company variable is being used

A: Add These code in your phtml
 <button>Add New Address</button>

Your phtml code for new ADDRESS


text:
Q: How to query AddressBook contacts according to the given number? I use  the method loop all the contacts in addressbook, but It's too hard when too many contacts in AddressBook.
How to query AddressBook contacts according to the given number?

A: Try to loop the contacts in other thread in background. Try Grand Central Dispatch.


text:
Q: HttpHandler Listen for Client Disconnect? Does an HttpHandler listen for a disconnect from the browser?
My guess is "no" since it seems to be mostly/only used for dynamic file creation, so why would it?
But I can't find an answer in the docs or goog.
Many thanks in advance!
Background
I'd like to "abort" an HttpHandler because currently, I allow huge excel exports (~150k sql rows, so ~600k html lines).  For reasons almost as ridiculous as the code, I have a query that fires for as many sql rows that the user tries to export.  As you can imagine, this takes a very long time.
I think I'm getting backed up with worker processes because users probably get frustrated with the lag, and try again with a smaller result.  I currently flush the worker procs automatically every 30 min, but I'd rather cleanup more quickly.
I don't have the time to clean up the sql right now, so I'd like to just listen for an "abort" from the client and kill the handler if "aborted".

A: What you're hoping to accomplish by listening for a client connection drop won't really help solve your problem at all. The core of your problem is a long running task being kicked off in an HttpHandler directly.
In this case, even if you could listen for a client disconnect it wouldn't ever be acted upon as your code will be too busy executing to listen for it.
The only way to properly determine progress and perform actions during long running processes such as this is to ensure that your code is multi-threaded. The problem with doing this in ASP.NET for long running processes is they'll suck up threads from the thread pool needed to serve your pages. This could result in your website hanging or responding very slowly, as you've been experiencing.
I would recommend writing a Windows Service to handle these long running jobs and having it spit the results into a staging directory. I would then use MSMQ or similar to throw the request to the service for processing.
Ultimately, you want to get this long running thread outside of ASP.NET where you can take advantage of the benefits that multi-threading can offer you. Such as, the ability to report back the progress and to abort when needed.


text:
Q: Android border stroke with proper corner I have a textview which is having a dotted border as shown in the attached image.

In the image, only top left corner is having continuous right angled line, other corners are having dash gap. How can I make all the corners without dash gap? All 4 corners should be continuous right angled line.
My code for the selector is as below.
    <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke
        android:width="3dp"
        android:color="#FF0000"
        android:dashWidth="35dp"
        android:dashGap="10px"/>
    <padding android:left="5dp"
             android:top="5dp"
             android:right="5dp"
             android:bottom="5dp" />
    <corners
        android:radius="0dp"/>
</shape>

Thanks in advance.


text:
Q: ORACLE SQL - how to manipulate single column without selecting it How can I manipulate a single column without actually "selecting" it specifically?
So, lets say I have a table with columns A, B , C, D, ... and I want to multiply column C by 2, but want to get all columns as output without having to "select" them all, so I would like to use select *.
So, instead of
SELECT A, B, 2*C, D, E, F, ..... FROM T

I would like to
SELECT * FROM T [do something here to multiply C by 2]

How could I do that?

A: You could do
SELECT 2*C AS DOUBLE_C, T.* FROM T

You'll still get C as well, but it will be one single SELECT statement.


text:
Q: Rectangle exclusion by monominoes Here is the question: Given an $m\times n$ chessboard, what is the least number of monominoes can be placed on it so that the rectangle of shape $a\times b$ (or $b\times a$) can no longer be fitted onto the board? Here $a,b,m,n$ are positive integers and we assume that $a\leq m,b\leq n$.
Since the question seems quite classical, I wonder if it has already been (at least partially) solved somewhere, but unfortunately I can't find any reference.
Up to now, the following cases are known to me:

*

*Either $a$ or $b$ is equal to $1$;

*$a=b$.

It is likely that things would be easier if both $m$ and $n$ are multiples of $ab$, but I'm not sure to which extent does this assumption simplify the problem.
Any advice or hint is appreciated.

A: A key search term is "blocking set." Here is one paper whose references and citations might lead you to useful literature.

Cano, J., García, A., Hurtado, F., Sakai, T., Tejel, J., & Urrutia, J. (2015). Blocking the $k$-holes of point sets in the plane. Graphs and combinatorics, 31(5), 1271-1287.


text:
Q: Output all language strings in Revel? I'm developing an API Server in Go and the server (at the moment) handles all translations for clients. When an API client fetches particular data it also asks for the translations that are available for the given section.
Ideally I want to have the following folder structure:
/messages
  /home.en
  /home.fr
  /home.sv
  /news.en
  /news.fr
  /news.sv

Where news and home are distinct modules.
Now the question I have for Revel is is it possible to fetch ALL language strings for a given module and given locale? For example pull all home strings for en-US.
EDIT:
I would like the output (something I can return to the client) a key:value string of translations.
Any guidance would be appreciated.

A: It seems to me that revel uses messaged based translation (just like gettext does), so you need
the original string to get the translation. These strings are stored in Config objects,
which are themselves stored in messages of i18n.go, sorted by language.
As you can see, this mapping is not exported, so you can't access it. The best way
to fix this is to write a function for what you want (getting the config by supplying a language)
or exporting one of the existing functions and create a pull request for revel.
You may workaround this by copying the code of loadMessageFile or by forking your version
of revel and exporting loadMessageFile or parseMessagesFile. This also is a great opportunity
to create a pull request.
Note that the localizations are stored in a INI file format parsed by robfig/config,
so manually parsing is also an option (although not recommended).


text:
Q: Should I be able to update a MySQL enum type with a text value? I'm trying to update the value in a MYSQL enum field from PHP via Doctrine (5.3 and 1.2 respectively).
I get an error when I try and do this:
    $q = Doctrine_Query::create()
            ->update('StMessages')
            ->set('status','new')
            ->where('message_id = ?',$msg_id);

I get a sql state error telling me that the column 'new' does not exist. If I enter 3 instead of new (presumably the internal index of the 'new' value), then the query works. In fact it happens in a SQL client too so perhaps this is a quirk of this version of MySQL? Its 5.1.45.
Anyone know if this is how MySQL is supposed to treat enums or if this is more likely a Doctrine issue? I have 'use_native_enum' set to true.

A: Given a table
create table test (
     enumfield enum('a','b','c')
);

you should be able to do
update test set enumfield='a';

which is the whole point of the num field - not having to mess with indexes and whatnot.
What's the exact definition of your enum field?

A: I think this was actually an issue relating to the quoting of strings when updating the field's values. I'm not sure if Doctrine or I was at fault.


text:
Q: PuLP termination criterium: fracgap (COIN-CMD) I am running an optimization problem that is unable to find the optimal solution (within 10 minutes). I think that is caused by the fact that very tiny improvements keep getting found. I want to cut this proces short, so as not to spend too much time on too little improvements.
I am using the COIN-CMD class (via SolverStudio in Excel):
class pulp.solvers.COIN_CMD(path=None, keepFiles=0, mip=1, msg=0, cuts=None, presolve=None, dual=None, strong=None, options=[], fracGap=None, maxSeconds=None, threads=None)

One possibility is to set a time limit, but the downside of this is that I do not know how large the improvements of the solution are. This should therefore be a final go-to strategy.
Is there an alternative method to terminate the solving process, for example, when a sufficiently good solution is found? Alternatively, is there an place where the parameters and their workings are nicely documented? I notice that https://pythonhosted.org/PuLP/index.html is a little meager in that regard.

A: After some digging I found three different ways to specify gaps in CBC (programmed in C++) here:
bool setAllowableGap(double value)
bool setAllowablePercentageGap(double value)
bool setAllowableFractionGap(double value)

I am guessing that with setAllowableGap you set an absolute value, and whenever the gap between the best known solution and the possbile best solution is smaller than that value the solving process will terminate.
With setAllowablePercentageGap the gap should be smaller than the specified percentage (say, 5%), and the with setAllowableFractionGap it seems that the gap should smaller than a fraction (say, 0.05). I am not sure what the possible best solution would be, or how it would be calculated, though. It would be great if someone could expand on this.
In PuLP, you can only specify the fracgap parameter.


text:
Q: Accessing variables inside trigger function I'm trying to make a trigger function to create a time stamp based on a base date stored in a variable plus an interval in seconds.
This base date is given to the psql script with the -v option, e.g. "-v start_time='2013-10-10 13:48:00'".
I want to access this variable from within a trigger function a do something like:
NEW.mytimestamp = timestamp :start_time + interval NEW.elapsed_seconds ' s';

Unfortunately I cannot figure out the right syntax for that. Any ideas?

A: It is impossible. psql variables (accessed via :varname) are client side variables. Trigger functions are executed on the server and cannot access these variables.
There is a way around this, but a little difficult (one cannot simple initialize values via command line). You can use custom configuration setting variables:
postgres=# select set_config('public.xxx', '10', false);
 set_config
------------
 10
(1 row)

create or replace function foo_trg()
returns trigger as $$
begin
  raise notice '%', current_setting('public.xxx');
  return new;
end;
$$ language plpgsql;

create table foo(a int);

create trigger hh before insert on foo for each row execute procedure foo_trg();

postgres=# insert into foo values(200);
NOTICE:  10
INSERT 0 1

Another (more established) technique would be to use an auxiliary table.
On second thought, trigger parametrization (based on some global value) is usually a terrible idea. It indicates you are doing some wrong. Use a function instead.


text:
Q: Curl IPv6 /48 Addresses PHP --interface I have the following function(in functions.php, for example purposes..):
function url_get_contents($url, $ip){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_INTERFACE, $ip);
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

I need to have this function mount to IPv6 addresses that are in a mounted /48 on my interface (sit1).
The following is my /etc/sysconfig/network-scripts/ifcfg-sit1:
DEVICE=sit1
BOOTPROTO=none
ONBOOT=yes
IPV6INIT=yes
IPV6TUNNELIPV4=**.***.**.***
IPV6TUNNELIPV4LOCAL=***.**.**.**
IPV6ADDR=****:***:*:***::*/64
IPV6ADDR_SECONDARIES="****:***:*:***::/48"
IPV6_DEFAULTGW=****:***:*:***::*

Obviously in the above code, IP addresses have been starred out.
However, in php:
<?php
require_once('functions.php');
function randomString(){
$length = 16;
$chars = "0123456789abcdef";
$str = "";
for($i = 0; $i < $length; $i++){ $str .= $chars[mt_rand(0, strlen($chars) - 1)]; }
$str = str_split($str, 4); $str = implode(":", $str);
return $str;
}
$url="http://www.whatismyipv6.com";
$ip="****:***:*:***::" . randomString();
$res=url_get_contents($url, $ip);
print($res);
exit();
?>

This doesn't seem to work (address cannot be bound to possibly??).
Anyone know how I can get this to work?
Thanks!
** NOTE: THIS ALL WORKS IF I MANUALLY ADD THE IP WITH /128 IN ifcfg-sit1**


text:
Q: How to update knockout model in mvc3 app I've been playing with MVC3 with KnockoutJs for a few weeks and I've been wondering about something
say I have an mvc action which returns a simple list
public ActionResult AddFoos()
{
    List<Foo> funds = new List<Foo>();
    .. etc
    return Json(funds.ToList(), JsonRequestBehavior.AllowGet);
}

which is then passed into the view model
var viewModel = {
  fooChocies: ko.mapping.fromJS([]),
  fooOptions: ko.mapping.fromJS([]),
    loadInitialData: function () {

        ko.mapping.fromJS(serverData, dataMappingOptions, viewModel.fooOptions);
    },
};

In my type Foo I also have properties that show or hide ui elements
var Foo = function (data, preselect) {

    var self = this;
    self.id = ko.observable(data.id);
    self.Name = ko.observable(data.Name);
    self.number = ko.observable('');

    self.showProducts = ko.observable(false);   <---
    self.displayBigPanel = ko.observable(false);  <---

   }

My approach so far as been to dynamically create elements of the form

which passes through the ModelBinder and creates a List< Foo > as a parameter for controller action.
Finally the question...
When the user navigates back to this page I need to restore the UI with the fooChoices the user made.
It seems I have 2 choices with rebuilding the user selections (both via extension methods)

*

*Use raw json as seen by
ko.toJSON(viewModel.fooChoices))

which in addition to basic model properties also provides info on hiding and displaying UI elements,
            sb.Append("viewModel.fooCghoices= ko.mapping.fromJS(" + json + ");");
            sb.Append("ko.applyBindings(viewModel);");
            return new HtmlString(sb.ToString());

thus sending client ui info to the server and back
or

*

*Manipulate the ViewModel directly in effect simulating the user actions
        sb.Append("viewModel.fooChoices.push(new Foo(1509));");
        sb.Append("viewModel.fooChoices()[0].selectedSubFoo = new Foo(273);");
        sb.Append("viewModel.fooChoices()[0].showProducts(true);");

In either case it feels a bit off and that a better pattern is out there. Would like to know if one way is better than the other or none of the above.
Many Thanks

A: Presently, your controller method returns a list of Foo.  Consider creating a more complex object that holds both your Foos and your choices.
public class FooViewModel
{
  public List<Foo> Foos { get; set; };
  public UserChoices { get; set; }
}

Change your controller method so that it returns FooViewModel.  This means user choices will be returned along with any Foos you are interested in.
public ActionResult AddFoos()
{
    // Are there any choices stored in session?
    // Use those first, otherwise create a new UserChoices object
    UserChoices choices =
        Session["User.Choices"] as UserChoices ?? new UserChoices();

    List<Foo> funds = new List<Foo>();
    .. etc

    FooViewModel vm = new FooViewModel() { Foos = funds; UserChoices = choices };

    // Return the whole object, containing Choices and Foos
    return Json(vm, JsonRequestBehavior.AllowGet);
}

Also, consider some kind of action filter to allow you to pass complete objects easily.  ObjectFilter is a good approach.  It allows you to pass complex object structures easily without having to rely on specific markup.
http://www.c-sharpcorner.com/blogs/863/passing-json-into-an-asp-net-mvc-controller.aspx
ObjectFilter above a controller method.  Pretty simple, just declaring that the controller should attempt to treat any incoming parameter called fooStuff as type FooViewModel.
    [HttpPost,
     ObjectFilter(Param = "fooStuff", RootType = typeof(FooViewModel)),
     UnitOfWork]
    public JsonResult ProcessFoos(FooViewModel fooStuff) {

By defining a corresponding JavaScript view model, you can just convert the whole thing to a json string and pass it to the controller method fully populated.
So, example of corresponding js vm would be:-
var fooViewModel = function(data) {
  var self = this;
  self.Foos = ko.observableArray(data.Foos);
  self.UserChoices = ko.observable(data.UserChoices);

  // Don't worry about properties or methods that don't exist
  // on the C# end of things.  They'll just be ignored.
  self.usefulJSOnlyMethod = function() {
    // behaviour
  };
}

var userChoice = function(data) {
  var self = this;
  self.DinnerId = ko.observable(data.DinnerId);
}

Typical call to a controller method decorated by ObjectFilter would be something like this ( assuming self is a fooViewModel ):-
var queryData = ko.mapping.toJSON(self);
$.ajax(
   //...
   data: queryData,

Any matching ( same name, same type case-sensitive ) property from the js vm will automatically end up in the fooStuff parameter of your controller method.  Time to save those choices:-
Also note that I'm persisting user choices in the session here.  This'll allow them to be picked up by any other controller method which may need them ( example in AddFoos above ).
    [HttpPost,
     ObjectFilter(Param = "fooStuff", RootType = typeof(FooViewModel)),
     UnitOfWork]
    public JsonResult ProcessFoos(FooViewModel fooStuff)
    {
        // hey!  I have a fully mapped FooViewModel right here!
        // ( _fooServices.ProcessFoos will return updated version of viewmodel )
        FooViewModel vm = _fooServices.ProcessFoos(fooStuff);

        // What about those choices?
        // Put them in the session at this point in case anyone else comes asking
        // after them.
        Session["User.Choices"] = vm.UserChoices;

        return Json(vm);
    }

Because we've:-

*

*Defined a better C# view model

*Defined a corresponding JS view model

*Including UserChoices as part of that view model

....restoring the choice is simple at this point.  Reference the part of the view model that contains the user's selected choice.
<select id="dinnerChoice"
   data-bind="value: UserChoices.DinnerId"
>
</select>


text:
Q: Azure cosmos DB- how can I change a name of tables? I want to change the name of the tables that I have, the name should be like in my  cosmos DB.
For now I see the names of tables like here http://joxi.ru/brRykZoIBdgPKA
its should be like here http://joxi.ru/12Mn36ocgxezdA
I  am try to get a tableName from the data base and set it in refresh function, but it is not changed.
Its my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
    private static readonly string endpointUri = ConfigurationManager.AppSettings["EndpointUri"];
    private static readonly string primaryKey = ConfigurationManager.AppSettings["PrimaryKey"];
    private static readonly string partitionKey = ConfigurationManager.AppSettings["PartitionKey"];
    private static readonly int maxTimeForCloudActivities =
        Convert.ToInt32(ConfigurationManager.AppSettings["MaxTimeForCloudActivities"]);

    private CloudDataAndServices cloudDateAndServices;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        cloudDateAndServices = new CloudDataAndServices(endpointUri, primaryKey);

        //Present the connection dtails from the configuration file
        textBox1_AzureAccountEndPointUri.Text = endpointUri;
        textBox2_AzureAccountPrimaryKey.Text = primaryKey;
    }

    private void btn_CreateCosmosClient_Click(object sender, EventArgs e)
    {
        try
        {
            cloudDateAndServices.CreateCosmosClient();
            MessageBox.Show("COSMOS DB client successfully created", "Success",MessageBoxButtons.OK,
                MessageBoxIcon.Information);
            btn_CreateCosmosClient.Enabled = false;
        }
        catch(Exception ex)
        {
            MessageBox.Show("We could not create COSMOS DB Client, and the following exception" +
                " occured: \n\n" + ex.Message, "Cosmos DB Client failed to " +
                "create", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void btn_checkConnection_Click(object sender, EventArgs e)
    {
        if (cloudDateAndServices.IsCosmosClientCreated)
        {
            MessageBox.Show("I am connected");
        }
        else
        {
            MessageBox.Show("I am not connected");
        }
    }

    private void textBox_DataBaseName_TextChanged(object sender, EventArgs e)
    {
        //if the user typed database name - then we can enablr the create button
        if (!textBox_DataBaseName.Text.Equals(string.Empty))
            btn_CreateDatabaseEntitiesInCloud.Enabled = true;
        else
            btn_CreateDatabaseEntitiesInCloud.Enabled = false;
    }

    private async void btn_CreateDatabaseEntitiesInCloud_Click(object sender, EventArgs e)
    {
        string databaseName = textBox_DataBaseName.Text;
        string tableName = textBox_TabelName.Text;
        await CreateDataBaseAndTableInCloudAsync(databaseName, tableName);
    }

    private async Task CreateDataBaseAndTableInCloudAsync(string databaseName, string tableName)
    {
        Microsoft.Azure.Cosmos.Database createDB = null;

        #region Stage1: Create database in cloud

        try
        {
            Microsoft.Azure.Cosmos.DatabaseResponse result =
                await cloudDateAndServices.CreateDatabaseAsync(databaseName);
            System.Net.HttpStatusCode resultCode = result.StatusCode;
            createDB = result.Database;

            //The databse was created in the cloud
            if(resultCode == System.Net.HttpStatusCode.Created)
            {
                MessageBox.Show("The database '" + databaseName + "' was created in your cloud account."
                    , "Database was created", MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }

            //The database already exists in the cloud, so the Azure didn`t create it again
            else if (resultCode  == System.Net.HttpStatusCode.OK
                || resultCode == System.Net.HttpStatusCode.Accepted)
            {
                MessageBox.Show("The database '" + databaseName + "' already exists in " +
                    "your cloud account.", "Database already exists",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }
            else // Another value of HttpStatusCode
            {
                MessageBox.Show("Database was not created, and we got the following status code" +
                    ":\n\n\n" + resultCode,
                    "Database was not crerated", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show("Database was not created. The following error:\n\n\n"
                + ex.Message, "Database was not created", MessageBoxButtons.OK,
                MessageBoxIcon.Error);
         }
        #endregion

        //If the database was not created- then we cannot proceed to the table creation process
        if (createDB == null)
        {
            MessageBox.Show("Since the database ws not created- the table creation" +
                " process will not be done", "Table will not be created",
                MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

        #region Stage2: Create table in cloud
        if(!String.IsNullOrEmpty(tableName))
        {
            try
            {
                Microsoft.Azure.Cosmos.ContainerResponse result =
                    await cloudDateAndServices.CreateContainerAsync(createDB, tableName, partitionKey);

                //Get the status code out of the create container activity
                System.Net.HttpStatusCode statusCode = result.StatusCode;

                if (statusCode == System.Net.HttpStatusCode.Created)
                {
                    MessageBox.Show("The table '" + tableName + "' was created in your cloud account,within" +
                        databaseName +" "
                        , "table was created", MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                }

                //The table already exists in the cloud, so the Azure didn`t create it again
                else if (statusCode == System.Net.HttpStatusCode.OK
                    || statusCode == System.Net.HttpStatusCode.Accepted)
                {
                    MessageBox.Show("The table '" + tableName + "' already exists in " +
                        "your cloud account.", "table already exists",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                }
                else // Another value of HttpStatusCode
                {
                    MessageBox.Show("table was not created, and we got the following status code" +
                        ":\n\n\n" + statusCode,
                        "table was not crerated", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Table was not created, and we got the following  exception:" +
                    "\n\n\n" + ex.Message);
            }
        }

        #endregion
    }

    private void label3_Click(object sender, EventArgs e)
    {

    }

    private void button3_Click(object sender, EventArgs e)
    {

    }

    private void btn_RefreshDatabaseList_Click(object sender, EventArgs e)
    {
        //Ask the cloud object to get our database, with a time limitation
        cloudDateAndServices.getCloudData(CloudDataAndServices.TaskType.GetCloudDatabasesTask, maxTimeForCloudActivities);
        PopulateDatabasesInCombo();

    }

    private void PopulateDatabasesInCombo()
    {
        comboBox_CloudDatabases.DataSource = null;
        comboBox_CloudDatabases.Items.Clear();

        //Attached the cloudDateAndServices.CloudDatabases list to the UI control
        //and display a specific member in the UI
        comboBox_CloudDatabases.DataSource = cloudDateAndServices.CloudDatabases;
        comboBox_CloudDatabases.DisplayMember = "databaseId";

     }

    private void btn_RefreshTable_Click(object sender, EventArgs e)
    {
        cloudDateAndServices.getCloudData(CloudDataAndServices.TaskType.GetCloudTablesTask, maxTimeForCloudActivities);
        PopulateTablesInCombo();
    }

    private void PopulateTablesInCombo()
    {
        conboBox_CloudTables.DataSource = null;
        conboBox_CloudTables.Items.Clear();

        //Attached the cloudDateAndServices.CloudTables list to the UI control
        //and display a specific member in the UI
        conboBox_CloudTables.DataSource = cloudDateAndServices.CloudTables;
        conboBox_CloudTables.DisplayMember = "tableName";

    }

    private void btn_DeletedSelectedDadabase_Click(object sender, EventArgs e)
    {
        String dbIdForDelete = ((Models.Database)comboBox_CloudDatabases.SelectedItem).databaseId;

    }
}

}
its class CloudDataAndServices:
using Microsoft.Azure.Cosmos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApp1
{
public class CloudDataAndServices
{

    //Azure cosmos DB params, required for creating Azure Cosmos DB client
    private string endPointUri;

    public string EndPointUri
    {
        get
        {
            return endPointUri;
        }
    }

    private string primaryKey;

    public string PrimaryKey
    {
        get
        {
            return primaryKey;
        }
    }

    //Indication if we have created a cosmos client
    private bool isCosmosClientCreated = false;
    public bool IsCosmosClientCreated
    {
        get
        {
            return isCosmosClientCreated;
        }
    }

    private CosmosClient cosmosClient;

    private System.Collections.Generic.List<Models.Database> cloudDatabases =
        new List<Models.Database>();

    public System.Collections.Generic.List<Models.Database> CloudDatabases
    {
        get { return cloudDatabases; }
    }

    private System.Collections.Generic.List<Models.Table> cloudTables =
        new List<Models.Table>();

    public System.Collections.Generic.List<Models.Table> CloudTables
    {
        get { return cloudTables; }
    }

    public enum TaskType
    {
        GetCloudDatabasesTask,
        GetCloudTablesTask,
    }

    public CloudDataAndServices(string end_point_uri, string primary_key)
    {
        endPointUri = end_point_uri;
        primaryKey = primary_key;
    }

    public void CreateCosmosClient()
    {
        try
        {
            cosmosClient = new CosmosClient(endPointUri, primaryKey);
        }
        catch(Exception ex)
        {
            isCosmosClientCreated = false;
            throw ex;
        }

        isCosmosClientCreated = true;
    }

    public async Task<DatabaseResponse> CreateDatabaseAsync (string database_name)
    {
       DatabaseResponse result = await cosmosClient.CreateDatabaseIfNotExistsAsync(database_name);

       return result;
    }

    public async Task<ContainerResponse> CreateContainerAsync(Microsoft.Azure.Cosmos.Database databaseObject,
        string table_name, string partition_key)
    {
       ContainerResponse result = await databaseObject.CreateContainerIfNotExistsAsync(table_name, partition_key);
        return result;
    }
    //The following method gots as input:
    //a. the type of the task that we want to cloud to do: GetDatabases/GetTables
    //b. the max timeput that we want to allow the cloud.
    public void getCloudData(TaskType taskType, int timeout)
    {
        Task cloudTask = Task.Run(   async ()=>
            {
                if (taskType == TaskType.GetCloudDatabasesTask)
                    await getDatabasesAsync();
                else if (taskType == TaskType.GetCloudTablesTask)
                    await getTablesAsync();
            }

            );

        cloudTask.Wait(timeout);

        //When the code came to this place- out task is no longer running
        if (!cloudTask.IsCompleted)
            throw new TaskCanceledException(taskType.ToString() + "didn`t managed to return within " +
                (timeout / 1000) + " seconds");
    }

    //Get all the databases from the cloud, and store them into local list(cloudDatabases)
    private async Task getDatabasesAsync()
    {
        //clear all  the current data (since we are about to get the updated data from the cloud)
        this.CloudDatabases.Clear();

        //Get iterator fot looping the databases in the cloud
        FeedIterator<DatabaseProperties> iterator =
            cosmosClient.GetDatabaseQueryIterator<DatabaseProperties>();

        do
        {

            //get the next set of databases from the cloud by using the iterator
            foreach (DatabaseProperties db in await iterator.ReadNextAsync())
            {
                //Here we write the code for each one of the databases
                Models.Database currentDatabase = new Models.Database();
                currentDatabase.databaseId = db.Id;
                currentDatabase.eTag = db.ETag;

                //At this stage currentDatabase contains the information we choose
                //to  take from Microsoft.Azure.Cosmos.DatabaseProperties
                cloudDatabases.Add(currentDatabase);
            }
        } while (iterator.HasMoreResults);
    }

    //Get all the tables from the cloud, and store them into local list(cloudTables)
    private async Task getTablesAsync()
    {
        //clear all  the current data (since we are about to get the updated data from the cloud)
        this.CloudTables.Clear();

        //scan all the batabases in the cloud, based on the local list cloudDatabases
        //(for each database we want to get all its tables)

        foreach(Models.Database localDB in cloudDatabases)
        {
            //Get the azure database object from the cloud according to its id

            Microsoft.Azure.Cosmos.Database currentDatabase =
                cosmosClient.GetDatabase(localDB.databaseId);

            //Get the tables of the cloud database

            FeedIterator<ContainerProperties> iterator =
                currentDatabase.GetContainerQueryIterator<ContainerProperties>();

            //use the iterator to get the containers of the current databases
            do
            {
                foreach(ContainerProperties table in await iterator.ReadNextAsync())
                {
                    Models.Table currentTable = new Models.Table();
                    currentTable.tableName = table.Id;
                    currentTable.databaseId = localDB.databaseId;
                    cloudTables.Add(currentTable);
                }

            } while (iterator.HasMoreResults);
        }
    }
}

}


text:
Q: Connect to remote MSSQL 2016 using isql and python on Mac? Goal: Connect to remote MSSQL 2016 server via Python.
Main approach: Closely followed tutorial in https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-SQL-Server-from-Mac-OSX .
Problem: Able to connect via tsql, but isql is not working. Errors
[S1000][unixODBC][FreeTDS][SQL Server]Unable to connect to data source
[37000][unixODBC][FreeTDS][SQL Server]Login failed for user 'DOMAIN\user-p'
[37000][unixODBC][FreeTDS][SQL Server]Cannot open database "TIT_BI_OPERATIONS" requested by the login. The login failed.

Things tried:

*

*Different ODBC drivers 13.1, 17, FreeTDS

*Inclusion/exclusion of escape character in the user name.

*Host name vs host ip.

Settings:
odbc.ini
[ODS_DSN]
Description = Connection to ODS MS_SQL 2016
Driver = FreeTDS
Servername = ODS_DSN
Port = 40000
Database = TIT_BI_OPERATIONS

odbcinst.ini
[FreeTDS]
Driver=/usr/local/lib/libtdsodbc.so
Setup=/usr/local/lib/libtdsodbc.so
UsageCount=1

freetds.conf
[ODS_DSN]
host = 164.10.17.77
port = 40000
tds version = 7.4
client charset = UTF-8

Notes:

*

*Even though, its not very promising to run python without connecting through tsql and isql first, i still tried without success. Using pyodbc, pypodbc, sqlalchemy.

*Most errors in the form: Login failed for user 'DOMAIN\user-p'

*For ODBC driver 13: Can't open lib '/usr/local/lib/libmsodbcsql.13.dylib'

*I am able to connect via SQL PRO STUDIO, using exact same credentials.

If you have any thoughts which direction to go to climb out of this connection problem, it would be greatly appreciated. Thank you!

A: If you're using Windows domain auth, you'll have to use FreeTDS. Oddly enough, Windows domain auth isn't supported by the Microsoft ODBC Driver, only FreeTDS.
Since you can connect with the tsql command, that means FreeTDS is working. I'd recommend connecting directly from Python explicitly. Try a connection string like this:
import pyodbc

con = pyodbc.connect(
    r"DRIVER={FreeTDS};"
    r"SERVER=164.10.17.77;"
    r"PORT=40000;"
    r"DATABASE=TIT_BI_OPERATIONS;"
    f"UID=DOMAIN\\user-p;"
    f"PWD=yourpassword;"
    r"TDS_Version=7.3;"
)

cursor = con.cursor();

cursor.execute("SELECT 'this' AS that")

for row in cursor.fetchall():
    print(row)

Note that you do need two backslashes in the UID field to connect with Windows domain auth; that is not a typo!


text:
Q: Javascript not changing css     <!DOCTYPE html>

    <title></title>

Hello

Does anyone know what I'm doing wrong here? Shouldn't the CSS be changed by the javascript and display Hello. Thanks for any help!

A:
<title></title>

Hello

Try this its better to create custom.css file and link in head section. and also create custom.js file and link with your html befor /body tag end

A:

    <!DOCTYPE html>

    <title></title>

Hello

Put the block in quotes and move the


text:
Q: run function if form fields are not null Is it alright to post the isset password like this?
I think it should be if(isset($_POST['username']) && isset(md5($_POST['password']))) - since it posts it encrypted, but if I wrap md5 around the password w/i the conditional, it does not work properly.
if(isset($_POST['username']) && isset($_POST['password'])) {
 //run authentication
} else {
 //show form
}

A: Brad, yes it's ok. There is really no benefit to posting the password hashed (not encrypted). First, you have to use javascript to do that, and it's easily circumvented. Hashing of the submitted password should be done server side to compare with the stored hashed value.
Edit:
Plus, run the following and see what you get:
<?php echo md5(NULL);

Thus, md5 always returns a value.
On top of that try running the following:
<?php var_dump(isset(md5($_POST['password'])));

You'll see the following: Fatal error: Can't use function return value in write context
isset() can only be used with a variable.
Edit:
There is a difference between hashing and encryption. MD5 is a simple hash, one that isn't even cryptographically secure.
Yes, you should not submit passwords in plaintext to your server, but hashing them client side is the same thing. You should be using HTTPS for password form submissions, this is how you encrypt communications between your server and the client.

A: The whole purpose of
if(isset($_POST['username']) && isset($_POST['password'])) {

is to check if both POST parameters are set/available. There's no authentication involved, not even an assumption about the type of both elements (could be strings, arrays, ...). Only "is there such parameter in the request" and "can I access this element without raising a notice: undefined index".
No let's compare that to isset(md5($_POST['password']))
md5() takes a string, so md5($_POST['password']) makes two assumptions.
a) There is an element $_POST['password'], the very thing the "original" test checks.
b) (string)$_POST['password'] makes any sense, since whatever you pass to md5() is cast to string. If you pass an array the result is the same as for md5('Array');
Plus md5() always returns a string (the string representation of the hash for the input), so isset() is always true and doesn't make much sense there. (edit: would be always true, if isset() could be used with the return value of a function. But it can't, see comments)
bottom line; The "original" version serves a "well defined" purpose, the isset(md5(..)) version not so much ;-)

A: If the fields are in a form which is submitted, then those values will always be isset. What you probably want to check is whether or not they are empty. One simple way is to compare to an empty string, but that requires that you first check that the variable is set, otherwise, when the form hasn't been submitted, you'll get an "array key does not exist" warning. Thankfully, there's a handy method called empty() which checks whether a given variable has been set and whether it has a non-falsey value -- hence you usually want to check if something is not empty.
$x = "";
!empty($x);  // false
isset($x);   // true :(

// beware though:
$x = "0";
!empty($x);  // false

Think of it as a shorthand for this:
isset($x) && $x != false


text:
Q: PDF Merger using php I am working on a project in which I have to merge multiple pdf files into one.
I create one using fdpi pdf merger but it has a problem saying 'Trailer keyword not found after xref table'.
I looked on google it says I have to uncompress each pdf individually first using this website to merge them.
Can anyone provide php script for uncompress any pdf to pdf 1.7 or provide another pdf merger which merge multiple pdf into one without any version?
    <?php
include 'PDFMerger.php';

if(isset($_FILES) && !empty($_FILES)){

if(count($_FILES['file']['name'])) {
    foreach ($_FILES['file']['tmp_name'] as $each_file) {

        $files_array[] = $each_file;
    }

    $pdf = new PDFMerger;
    for ($i=0; $i<count($files_array); $i++){
      $pdf->addPDF($files_array[$i], 'all');
    }

    $pdf->merge('browser', 'samplepdfs/TEST2.pdf');
}
}
?>

<form method="POST" enctype="multipart/form-data">

            <input type="file" name="file[]" multiple>

            <input name="sub_btn" type="submit" value="Upload" multiple class="btn btn-default">

</form>

above code gives following error, FPDF error: Trailer keyword not found after xref table

A: If you are using FPDF to do merge the files together, it apparently has problems with some PDF files that are created by some programs such as Microsoft Word.  In some cases, these programs add additional information such as a signature in the properties of the document.
Editing the PDF file in Adobe Acrobat or Adobe Illustrator might resolve the problem.
Check out this answer which provides some more insight and this article which provides some more explanation.

A: We've found with similar PDF libraries (mPDF) that regressing the files to PDF ~v1.4 helps with merging; see: https://stackoverflow.com/a/40702177/427847


text:
Q: Extract slope of multiple trend lines from geom_smooth() I am trying to plot multiple trend lines (every ten years) in a time series using ggplot.
Here's the data:
dat <- structure(list(YY = 1961:2010, a = c(98L, 76L, 83L, 89L, 120L,
107L, 83L, 83L, 92L, 104L, 98L, 91L, 81L, 69L, 86L, 76L, 85L,
86L, 70L, 81L, 77L, 89L, 60L, 80L, 94L, 66L, 77L, 85L, 77L, 80L,
79L, 79L, 65L, 70L, 80L, 87L, 84L, 67L, 106L, 129L, 95L, 79L,
67L, 105L, 118L, 85L, 86L, 103L, 97L, 106L)), .Names = c("YY",
"a"), row.names = c(NA, -50L), class = "data.frame")

Here's the script:
p <- ggplot(dat, aes(x = YY))
p <- p + geom_line(aes(y=a),colour="blue",lwd=1)
p <- p + geom_point(aes(y=a),colour="blue",size=2)

p <- p + theme(panel.background=element_rect(fill="white"),
         plot.margin = unit(c(0.5,0.5,0.5,0.5),"cm"),
         panel.border=element_rect(colour="black",fill=NA,size=1),
         axis.line.x=element_line(colour="black"),
         axis.line.y=element_line(colour="black"),
         axis.text=element_text(size=15,colour="black",family="serif"),
         axis.title=element_text(size=15,colour="black",family="serif"),
         legend.position = "top")

p <- p + scale_x_discrete(limits = c(seq(1961,2010,5)),expand=c(0,0))

p <- p + geom_smooth(data=dat[1:10,],aes(x=YY,y=a),method="lm",se=FALSE,color="black",formula=y~x,linetype="dashed")

p <- p + geom_smooth(data=dat[11:20,],aes(x=YY,y=a),method="lm",se=FALSE,color="black",formula=y~x,linetype="dashed")

p <- p + geom_smooth(data=dat[21:30,],aes(x=YY,y=a),method="lm",se=FALSE,color="black",formula=y~x,linetype="dashed")

p <- p + geom_smooth(data=dat[31:40,],aes(x=YY,y=a),method="lm",se=FALSE,color="black",formula=y~x,linetype="dashed")

p <- p + geom_smooth(data=dat[41:50,],aes(x=YY,y=a),method="lm",se=FALSE,color="black",formula=y~x,linetype="dashed")

p <- p + labs(x="Year",y="Number of Days")
outImg <- paste0("test",".png")
ggsave(outImg,p,width=8,height=5)

This is the resulting image:

WHAT I WANT/PROBLEMS

*

*I want to extract the slope and add them on the the trend lines in the figure. How can I extract the slope of each line from the geom_smooth()?

*Currently, I am plotting the trend lines one by one. I want to know if there is an efficient way of doing this with adjustable time window. Suppose for example, I want to plot the trend lines for every 5 years. In the figure above the time window is 10.

*Suppose, I only want to plot the significant trend lines (i.e., p-value < 0.05, null: no trend or slope equals 0), is it possible to implement this with geom_smooth()?
I'll appreciate any help.

A: So, each of these tasks are best handled before you pipe your data into ggplot2, but they are all made fairly easy using some of the other packages from the tidyverse.
Beginning with questions 1 and 2:
While ggplot2 can plot the regression line, to extract the estimated slope coefficients you need to work with the lm() object explicitly. Using group_by() and mutate(), you can add a grouping variable (my code below does this for 5 year groups just for example) and then calculate and extract just the slope estimate into columns in your existing data frame. Then those slope estimates can be plotted in ggplot using the geom_text() call. I've done this below in a quick and dirty way (placing each label at the mean of the x and y values they regress) but you can specify their exact placement in your dataframe.
Grouping variables and data prep makes question 2 a breeze too: now that you have the grouping variables explicitly in your dataframe there is no need to plot one by one, geom_smooth() accepts the group aesthetic.
Additionally, to answer question 3, you can extract the pvalue from the summary of your lm objects and filter out only those that are significant to the level you care about. If you pass this now complete dataframe to geom_smooth() and geom_text() you will get the plot you're looking for!
library(tidyverse)

 # set up our base plot
 p <- ggplot(dat, aes(x = YY, y = a)) +
  geom_line(colour = "blue", lwd = 1) +
  geom_point(colour = "blue", size = 2) +
  theme(
    panel.background = element_rect(fill = "white"),
    plot.margin = unit(c(0.5, 0.5, 0.5, 0.5), "cm"),
    panel.border = element_rect(colour = "black", fill = NA, size = 1),
    axis.line.x = element_line(colour = "black"),
    axis.line.y = element_line(colour = "black"),
    axis.text = element_text(size = 15, colour = "black", family = "serif"),
    axis.title = element_text(size = 15, colour = "black", family = "serif"),
    legend.position = "top"
  ) +
  scale_x_discrete(limits = c(seq(1961, 2010, 5)), expand = c(0, 0))

# add a grouping variable (or many!)
 prep5 <- dat %>%
  mutate(group5 = rep(1:10, each = 5)) %>%
  group_by(group5) %>%
  mutate(
    slope = round(lm(YY ~ a)$coefficients[2], 2),
    significance = summary(lm(YY ~ a))$coefficients[2, 4],
    x = mean(YY),   # x coordinate for slope label
    y = mean(a)     # y coordinate for slope label
  ) %>%
  filter(significance < .2)   # only keep those with a pvalue < .2

p + geom_smooth(
  data = prep5, aes(x = YY, y = a, group = group5),  # grouping variable does the plots for us!
  method = "lm", se = FALSE, color = "black",
  formula = y ~ x, linetype = "dashed"
) +
  geom_text(
    data = prep5, aes(x = x, y = y, label = slope),
    nudge_y = 12, nudge_x = -1
  )

Now you may want to be a little more careful about specifying the location of your text labels than I have been here. I used means and the nudge_* arguments of geom_text() to do a quick example but keep in mind since these values are mapped explicitly to x and y coordinates, you have complete control!
Created on 2018-07-16 by the reprex
package (v0.2.0).


text:
Q: Declaring an array in CSV I am trying to Declare $GroupName array and add a couple statements for the array. I have an additional code from a different script and am trying to create an array for that script. I am trying to test the Row.Category = group and the Row.excluded = false. Then it will check the $groupname Array for duplicates. If no duplicates are found, populate $groupname.
I am need help just creating the array since I am a powershell novice.
  $GroupName = @(column1 = "Domain")(column2 = "Account")
If ($_.category0 -eq "Group") -and ($_.Excluded -match "False")
 "Account0", "Domain0" | sort Account0 -Unique

How do I improve the following code above to display the 2 columns in the new CSV.

A: This is one method to achieve what you're after, creating a new CSV file:
$Object = New-Object -TypeName PSObject -Property @{ Domain=''; Account='' }
$Object | Export-CSV $env:temp\MyCSV.csv -NoTypeInformation

We create a new PSObject called $Object and provide a hashtable object with the structure you require to the -Property parameter.
We then pass the PSObject down the pipeline to the Export-CSV cmdlet. Adding -NoTypeInformation on the end allows us to create a clean CSV file without additional information from PowerShell that other systems would not recognise.
However, I should note there are other ways to create/generate CSVs, especially if you're wanting to populate them with data.


text:
Q: How do you send .txt over TCP/IP line by line with a certain delay? My code:
Client.py
import socket
import pandas as pd
import time
import pickle

# Load data
File = pd.read_csv('Data.txt', sep='\t', skipinitialspace=True, header=None, skiprows=1)

client_socket = socket.socket()
client_socket.connect(('localhost', 5555))  # Connect to server

client_socket.send(bytes("Sending file...", 'utf-8'))  # Note

Buffer = []

for x in range(File.shape[0]):
    count = 1
    Buffer = File.loc[count]
    client_socket.send(pickle.dumps(Buffer))
    count += 1
    time.sleep(2)  # Wait 2 sec

This is my server:
Server.py
import socket
import pickle

server_socket = socket.socket()
server_socket.bind(('localhost', 5555))  # local server-client

server_socket.listen(3) # Max. 3 connections
print('Waiting for connection')

Buffer = []
i = 0

while True:
     client_socket, addr = server_socket.accept()
     received_data = client_socket.recv(1024).decode()
     print('Client address', addr, received_data)

     client_socket.recv(pickle.loads(Buffer)).decode()
     print(Buffer[i])
     i =+ 1

     if(i == 10000):
         client_socket.close()  # Closing server socket
     else: continue

I am stuck with the following error:
   BrokenPipeError: [Errno 32] Broken pipe

The problem is with SIGPIPE, because the connection is interrupted based on what I found, in case I managed to implement the pickle correctly.
Server error:
Traceback (most recent call last):
  File "/Users/David/PycharmProjects/DP1/Server.py", line 19, in <module>
    client_socket.recv(pickle.loads(Buffer))
TypeError: a bytes-like object is required, not 'list'

I expected that decode() decodes the received pickle in bytes format to readable format on the side of the server. pickle.loads uses only one argument, so I cannot specify any encoding such as utf-8.
.txt file was exported from Excel (tab spacing):
Data.txt
Time    Speed   R_Ax    Activation  Delay   KP
11:11:37    13,1    124,45  100 2   4
11:11:39    13,08   124,26  100 2   4
11:11:41    13,15   124,925 100 2   4
11:11:43    13,08   124,26  100 2   4
11:11:45    13,11   124,545 100 2   4
11:11:47    13,13   124,735 100 2   4
11:11:49    13,13   124,735 100 2   4
11:11:51    13,05   123,975 100 2   4
11:11:53    13,07   124,165 100 2   4
11:11:55    13,11   124,545 0   2   999
11:11:57    13,1    124,45  0   2   999
11:11:59    13,06   124,07  0   2   999
11:12:01    13,07   124,165 0   2   999
11:12:03    12,99   123,405 0   2   999
11:12:05    13,03   123,785 0   2   999
11:12:07    13,05   123,975 0   2   999
11:12:09    13,11   124,545 0   2   999
11:12:11    13,04   123,88  0   2   999
11:12:13    13,04   123,88  0   2   999

Thank You.

A: Since you'd like to transfer a pandas series over the wire, one way to achieve this would be to use pickle. pickle can take a Series and convert it to a byte array, and then go in the other direction and convert a byte array to a series.
On the client-side, use:
client_socket.send(pickle.dumps(Buffer))

Then, on the server-side use: pickle.loads
Detailed answer
The actual code on both sides would look like that:
client:
import socket
import pandas as pd
import time
import pickle

# Load data
File = pd.read_csv('Data.txt', sep='\t', skipinitialspace=True, header=None, skiprows=1)

client_socket = socket.socket()
client_socket.connect(('localhost', 5555))  # Connect to server

client_socket.send(bytes("Sending file...", 'utf-8'))  # Note

Buffer = []

for inx in range(File.shape[0]):
    Buffer = File.loc[inx]
    print(f"Sending \n {Buffer}")
    client_socket.send(pickle.dumps(Buffer))
    time.sleep(2)  # Wait 2 sec

Server:
import socket
import pickle

server_socket = socket.socket()
server_socket.bind(('localhost', 5555))  # local server-client

server_socket.listen(3) # Max. 3 connections
print('Waiting for connection')

Buffer = []
i = 0

client_socket, addr = server_socket.accept()
received_data = client_socket.recv(1024)
print('Client address', addr, received_data)

while True:
     received_data = client_socket.recv(10000)

     Buffer.append(pickle.loads(received_data))
     print(Buffer[i])
     i =+ 1

client_socket.close()  # Closing server socket (we'll never get here)


text:
Q: Writing git API for javascript node module Hi recently I have to implement a git API for a node module, so we can have version control through programmatic interface. I came upon this post to find some good modules that I can use.
However, after playing around with some of them, I realized that none of them provide the feature of querying the commit history of a single file (like calling 'git log --follow '). I would like to extend that feature into my module but since I have no experience before, does anyone know where I should start?

A: The libraries you mentioned should be a good starting point. Take node-git's lib/git.js file for example. There you can find the following lines:
// Call the native git binary
Git.prototype.call_git = function(prefix, command, postfix, options, args, callback) {
    // ...

This is a good starting point to understand how the author maps Node functions on system calls and and allows the callback to work with the output.
I would start a fork of the project. Look for the log function in the same file, which starts like
Git.prototype.log = function(commit, path, options, callback) {

Copy the function, give it a proper name and try to adopt it to meet your needs.
If you succeed and like to help, you could start a pull request on GitHub to help the author and add the functionallity to the official project.
I would do it this way. I hope this helps.


text:
Q: What's a good antonym for the word serendipity? I 'm looking for an antonym that has all the subtleties that serendipity carries in it.

A: I think "vicissitude" comes close. The definition of vicissitude according to Oxford Dictionaries is: "(usually vicissitudes) A change of circumstances or fortune, typically one that is unwelcome or unpleasant"
Example sentences: 1.  Governments cannot protect citizens from all the circumstances and vicissitudes of life.

*Perhaps nothing can demonstrate the city's vicissitudes better than the changes of its landmarks.

*Losing your job is just one of the vicissitudes of life

A: If you think of serendipity in a broader sense of: "all the variables in the universe coming together perfectly, like pieces in a jig saw puzzle," then "chaos" is a good antonym.
If you want to refer to a single instance, then "ill-fated" may fit.

A: While not a term for the condition, there is a term for the condition sufferer - schlimazel (also spelled schlemazel)

A consistently unlucky or accident-prone person. Oxford Dictionaries Online

The term is a Yiddishism adopted into English. Etymonline offers the following derivation

"born loser," 1948, from Yiddish shlim mazel "rotten luck," from Middle High German slim "crooked" + Hebrew mazzal "luck." British slang shemozzle "an unhappy plight" (1889) is probably from the same source.
  A shlemiel is the fellow who climbs to the top of a ladder with a bucket of paint and then drops it. A shimazl is the fellow on whose head the bucket falls. [Rep. Stephen J. Solarz (D.-N.Y.), 1986]

As noted, there is a related British term, shemozzle

A state of chaos and confusion; a muddle. Oxford Dictionaries Online


text:
Q: Why is my VBA not finding functions in a C++ DLL? I needed to write a DLL in C++ containing a couple of functions that I'd be later using in VBA.
The .h file I've written looks like this (though, I admit I have been copying from some examples on the internet since I am very new to C++, and I'm not sure I need all this stuff):
 // FieldTrans.h

#ifndef FIELDTRANS
#ifdef _WIN32
#ifdef BUILD_DLL
#define FIELDTRANS_FUNC __declspec(dllexport)
#else
#define FIELDTRANS_FUNC __declspec(dllimport)
#endif
#define FIELDTRANS_FUNC
#else
#define FIELDTRANS_FUNC __attribute__ ((visibility("default"))) type
#endif

// Returns the interpolated field matrix: 180° x 360° with Res step
FIELDTRANS_FUNC double ShannonInterp(double* Matrix, double Res, double DeltaTheta, double DeltaPhi);
// Returns the normalized cardinal sinus coefficient
FIELDTRANS_FUNC double SpecialLog(double x);
#endif

While the .cpp file contains the actual definition of those functions:
// FieldTrans.cpp

#include "stdafx.h"
#include "FieldTrans.h"
#include <array>            // for counting elements of an array
#define _USE_MATH_DEFINES   // for M_PI
#include <math.h>           // for M_PI and Log10

using namespace std;

double SinC(double x)
{
    if (x == 0)
    {
        return 1;
    }
    else
    {
        return sin(M_PI * x) / (M_PI * x);
    }
}

double ShannonInterp(double *Matrix[], double Res, double DeltaTheta, double DeltaPhi)
{
    int k, l, m, n;
    double iRes, jRes;
    double ThetaSinC, PhiSinC;
    int MatrixHeigth = sizeof(Matrix) / sizeof(Matrix[0]), MatrixWidth = sizeof(Matrix[0]) / sizeof(Matrix);
    int Height = 180 / Res, Width = 360 / Res;
    double *Interpolated = new double[Height * Width];
    k = 0;
    m = 1;

    for (int i = 0; i < Height; i++)
    {
        iRes = i * Res;
        do
        {
            k = k + 1;
            m = k + 1;
        } while (iRes > (k + 1) * DeltaTheta);
        if (m > MatrixHeigth)
        {
            m = MatrixHeigth - 1;
        }
        ThetaSinC = SinC((iRes - k * DeltaTheta) / DeltaTheta);
        l = 0;
        n = 1;
        for (int j = 0; j < Width; j++)
        {
            jRes = j * Res;
            do
            {
                l = l + 1;
                n = l + 1;
            } while (jRes > (l + 1) * DeltaPhi);
            if (n > MatrixWidth)
            {
                n = 0;
            }
            PhiSinC = SinC((jRes - l * DeltaPhi) / DeltaPhi);
            Interpolated[i * Width + j] = Matrix[k][l] * ThetaSinC * PhiSinC + Matrix[k][n] * ThetaSinC * (1 - PhiSinC) + Matrix[m][l] * (1 - ThetaSinC) * PhiSinC + Matrix[m][n] * (1 - ThetaSinC) * (1 - PhiSinC);
        }
    }
    return *Interpolated;
}

I'm quite positive that the .cpp part works just fine.
I created a DLL by using Visual Studio and using "Project"-"Project properties"-"C/C++"-"Code generation" by modifying one of the options to "Multithreaded-DLL (/MD)".
After the DLL had been created, I wrote the following code in my VBA program:
Private Declare Function Shannonize Lib "C:\Users\daquino\Documents\Visual Studio 2013\Projects\FieldTrans\Release\FieldTrans.dll" Alias _
                        "ShannonInterp" (ByRef Matrix() As Double, ByVal Res As Double, ByVal DeltaTheta As Double, ByVal DeltaPhi As Double) As Double

But it doesn't work, since when I use the function, it says that it cannot be found in the module. I'm using the function like this:
InterpCo = Shannonize(AmplCo, Resolution, 181 / (PointsTheta+1), 361 / (PointsPhi+1))

Provided AmplCo is a 2D-array of Double, and the others inputs are Integer.
Could you please help me understand what's wrong?
EDIT: if I try to insert a reference to the .dll from my VBA program, it says "bad reference".

A: It looks like names of the C++ functions that you are exporting from dll have been mangled. Unlike C, C++ functions can be overloaded (same name but different arguments), can dwell in namespaces, etc. so names of exported functions will also include some extra suffixes. You can either surround exported functions with extern "C" { /*your code*/ } block to prevent name mangling or write a module exports file (.def) with proper naming.


text:
Q: Do I need to use "--cleanDestinationDir" when building a Hugo site on Netlify? I use hugo --minify --cleanDestinationDir when developing my site locally so I can be sure that everything I can browse to is as a result of the very last build.
Without --cleanDestinationDir content can remain available from a previous build.
Is it something I need to use when building a site on Netlify?


text:
Q: Ubuntu: AMD64 vs i386? I can't understand what these are even though I've read articles about them.
Does it have something to do with 32 bits and 64 bits CPU? So why is it saying "AMD"64 and "i386"?
AMD is a label just like Intel? So, if I've got an Intel Core 2 Duo (MacBook Pro), then I can't use AMD64 even though Intel Core is 64 bits.

A: Yes, you can use amd64 on your Intel Core 2 Duo.  The architecture is named after AMD because AMD invented it, with the Athlon 64.  Similarly, the 32-bit i386 architecture is named after Intel's 386 processor, because it was the first of its kind, but i386 will also work on AMD processors.


text:
Q: Continuous function on an interval How can I prove this?

Prove that if $f$ is is continuous on $c$ and $0<f(c)<1$, then there exist $\delta >0$ such that $0<f(x)<1$ for all $x\in(c-\delta,c+\delta)$

A: First suppose $\epsilon_1=f(c)$ since $f$  is is continous at $c$ then there is $\delta_1 >0$ such that $-f(c)<f(x)-f(c)< f(c)\Rightarrow 0=-f(c)+f(c)<f(x)$ for all   $x\in(c-\delta,c+\delta)$
Again  for $\epsilon_2=1-f(c)>0$ since $f$  is is continous at $c$ then there is $\delta_2 >0$ such that $-(1-f(c))<f(x)-f(c)<1- f(c)\Rightarrow f(x)<1$ or all $x\in(c-\delta_2,c+\delta_2)$
let $\color{red}{\delta=min\{\delta_1, v_2\}}$


text:
Q: Angular 4 pass data between 2 not related components I have a questions about passing data in Angular.
First, I don't have a structure as <parent><child [data]=parent.data></child></parent>
My structure is
<container>
  <navbar>
    <summary></summary>
    <child-summary><child-summary>
  </navbar>
  <content></content>
</container>

So, in <summary /> I have a select that do send value to <child-summary /> and <content />.
OnSelect method is well fired with (change) inside <summary /> component.
So, I tried with @Input, @Output and @EventEmitter directives, but I don't see how retrieve the event as @Input of the component, unless to go on parent/child pattern. All examples I've founded has a relation between component.
EDIT : Example with BehaviorSubject not working (all connected service to API works well, only observable is fired at start but not when select has value changed)
shared service = company.service.ts (used to retrieve company data)
import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class SrvCompany {

    private accountsNumber = new BehaviorSubject<string[]>([]);
    currentAccountsNumber = this.accountsNumber.asObservable();

    changeMessage(accountsNumber: string[]) {
        this.accountsNumber.next(accountsNumber);
    }

    private _companyUrl = 'api/tiers/';

    constructor(private http: Http) { }

    getSociete(): Promise<Response> {
        let url = this._companyUrl;
        return this.http.get(url).toPromise();
    }
}

invoice.component.ts (the "child")
import { Component, OnInit, Input } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import { SrvInvoice } from './invoice.service';
import { SrvCompany } from '../company/company.service';

@Component({
    selector: 'invoice',
    templateUrl: 'tsScripts/invoice/invoice.html',
    providers: [SrvInvoice, SrvCompany]
})

export class InvoiceComponent implements OnInit  {

    invoice: any;

    constructor(private srvInvoice: SrvInvoice, private srvCompany: SrvCompany)
    {

    }

    ngOnInit(): void {
        //this.getInvoice("F001");

        // Invoice data is linked to accounts number from company.
        this.srvCompany.currentAccountsNumber.subscribe(accountsNumber => {
            console.log(accountsNumber);
            if (accountsNumber.length > 0) {
                this.srvInvoice.getInvoice(accountsNumber).then(data => this.invoice = data.json());
            }
        });
    }

    //getInvoice(id: any) {
    //    this.srvInvoice.getInvoice(id).then(data => this.invoice = data.json());
    //}
}

company.component.ts (the trigerring "parent")
import { Component, Inject, OnInit, Input } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import { SrvCompany } from './company.service';

@Component({
    selector: 'company',
    templateUrl: 'tsScripts/company/company.html',
    providers: [SrvCompany]
})

export class CompanyComponent implements OnInit {

    societes: any[];
    soc: Response[]; // debug purpose
    selectedSociete: any;

    ville: any;
    ref: any;
    cp: any;
    accountNumber: any[];

    constructor(private srvSociete: SrvCompany)
    {

    }

    ngOnInit(): void {
        this.getSocietes();
    }

    getSocietes(): void {

        this.srvSociete.getSociete()
            .then(data => this.societes = data.json())
            .then(data => this.selectItem(this.societes[0].Id));
    }

    selectItem(value: any) {
        this.selectedSociete = this.societes.filter((item: any) => item.Id === value)[0];
        this.cp = this.selectedSociete.CodePostal;
        this.ville = this.selectedSociete.Ville;
        this.ref = this.selectedSociete.Id;
        this.accountNumber = this.selectedSociete.Accounts;
        console.log(this.accountNumber);
        this.srvSociete.changeMessage(this.accountNumber);
    }
}

A: This is a case where you want to use a shared service, as your components are structured as siblings and grandchildren. Here's an example from a video I created a video about sharing data between components that solves this exact problem.
Start by creating a BehaviorSubject in the service
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject("default message");
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}

Then inject this service into each component and subscribe to the observable.
import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";
@Component({
  selector: 'app-parent',
  template: `
    {{message}}
  `,
  styleUrls: ['./sibling.component.css']
})
export class ParentComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

}

You can change the value from either component and the value will be updated, even if you don't have the parent/child relationship.
import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";
@Component({
  selector: 'app-sibling',
  template: `
    {{message}}
    <button (click)="newMessage()">New Message</button>
  `,
  styleUrls: ['./sibling.component.css']
})
export class SiblingComponent implements OnInit {

  message:string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }

  newMessage() {
    this.data.changeMessage("Hello from Sibling")
  }

}

A: if component are not related than you need use Service
https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

A: There are two solutions for this.

*

*This can be done through shared service by using observable's.

*You can use ngrx/store for this. This is similar to Redux arch. You will be getting data from state.

A: Here is the simplest example of sharing data between two independent components, using event emitter and service
https://stackoverflow.com/a/44858648/8300620

A: When you mention non related components, I'm gonna assume that they don't have any parent component. If assumption isn't correct, feel free to read another of my answers where both cases are addressed.
So, as there's no common parent, we can use an injectable service. In this case, simply inject the service in the components and subscribe to its events.
(Just like the next image shows - taken from here - except that we'll inject the service in two Components)

The documentation explains it quite well how to Create and register an injectable service.


text:
Q: Shipping Price depending on Order Total I am trying to find a way to display a different shipping price depending on the Order total amount ?

A: No need of any other module. magento is awesome as it support lot of features including this one also.
go to Backend > System > configuration > Sales  and select shipping method and try with Table rate shipping method.
in condition select Price vs Destination , than select Main website from current configuration scope than you can see export csv button. download it. than you can enter information as in following image. fill required details and upload back to backend using import button

you can follow this link for more information....

A: You can try to use default Admin > Promotions > Shopping Cart Price Rules. If this not cover your issue, you need to create new shipping method, where you can calculate shipping price depends on order total.

A: You can use default shipping method "Table Rate" for this.
In this shipping method you can import CSV file for that zip codes. and set your rates and shipping label there.
OR
You can use web shop matrix shipping method for this.
Both are same in functionality of working.


text:
Q: Extracting financial data from Bloomberg Would I be able to extract the data from Bloomberg, if I don't have a Bloomberg Serial Number. What I mean, is I have Bloomberg on my computer and a login, but I can't access it as I don't have a Bloomberg terminal. If i can't do this, what other sources could I use to get multiple stock price information because I heard Yahoo and GOOGLE API are no longer running.

A: Do you have access to Bloomberg Professional? i.e. are you/someone paying ~$2k/month licence fee? You don't need to have a physical Terminal to use Bloomberg Professional Service. If you actually have Bloomberg on your computer then yes you are able to extract data via API.
How are you planning on using the data? There is a fairly in depth user manual here if you want to know all the nitty gritty --> https://data.bloomberglp.com/labs/sites/2/2014/07/blpapi-developers-guide-2.54.pdf
If you have Bloomberg, and can navigate to some of the data you want to retrieve, please elaborate a little more on what you want to achieve and I can help further.
If however you don't actually have Bloomberg Professional and are looking for alternate sources of financial market data, here's a few you may want to look into:

*

*Quandl

*Stooq

*Alpha Vantage

*IEX Trading
Also if you are going to be coding a strategy in Python, perhaps check out the following sites where you can get stock data and a built-in IDE. Both very popular:

*

*Quantopian

*Quantiacs


text:
Q: Column Value Based On Value in Another Table So I have two Tables in my database, Table_1 and Table2.
Table_1 has three columns: First Name, Last Name, and Age.
Table_2 also has three columns: First Name, Last Name, and Age.
The only difference between the tables is that the Age column in Table_2 does not contain any data. What I am trying to do is put a search / query into the Age column of Table_2 that will search for the First Name value in Table_1, and if it finds that name in Table_1 then display that value in the Age column of Table 2.
Table_1

First Name  Last Name   Age

John        Smith       30
David       Smith       30
James       Smith       40

Table_2

First Name  Last Name   Age

John        Smith       (Will return 30)
David       Smith       (Will return 30)
James       Smith       (Will return 40)

Is this done in some way by making the column computed?

A: You could join the two tables:
SELECT    table2.firstname, table2.lastname, table1.age
FROM      table2
LEFT JOIN table1 ON table1.firstname = table2.firstname AND
                    table1.lastname  = table2.lastname

A: If you want that value to stay in table2 permanently then you can update it from table 1 using following query: (It only works for MSSQL)
UPDATE t2
SET t2.age = t1.age
FROM table2 t2
INNER JOIN table1 t1
ON t1.firstname = t2.firstname AND t1.lastname  = t2.lastname

A: if you use mysql database then update query should be like below
    UPDATE table2 a
    JOIN table1 b ON a.firstname = b.firstname
    AND a.lastname = b.lastname
    SET a.age = b.age

But for postgreSQL it would be
UPDATE table2 a
SET a.age = b.age
FROM table1 b
WHERE a.firstname = b.firstname
        AND a.lastname = b.lastname ;


text:
Q: When is crosspaths set to true? I failed to find a good documentation about the use and purpose of crosspaths. Can someone point me to the documentation or answer these specific questions.

*

*My Scala version is 2.11.6, but when crosspaths is set to true,
I see two source folders - 'scala' and 'scala-2.11'. Shouldn't there
be just one of these two? What is the meaning of these two folders?

*What code goes in 'scala' and what goes in 'scala-2.11'?

A: crossPaths is set to true to enable/disable Cross-Building (and it's true by default).
As of sbt 0.13.8 you're seeing that by default sbt handles source directories per Scala version, to remove the repetition of every project doing this themselves.
So if you have multiple Scala versions you're cross building against, out the box you have source directories where you can put that version-specific code.
But I agree that it's confusing: if you don't have multiple crossScalaVersions there's no need for both a scala and a scala-2.11.
The majority of your code should always live in scala, and if you ever have more than one Scala version you're cross building against and you have version-specific code then use scala-2.11, scala-2.10, etc.


text:
Q: Opening multiple gnome terminals from bash and execute sudo services for my measurements on a Ubuntu OS I need to open in total 8 terminal and run services/commands that requires sudo. So the idea is to do that in a bash script.
What I want:
call "sudo ./init.sh" ones, enter sudo password and then all 8 terminals should open parallel and execute the services/commands without any further sudo password request.
What I tried: (example with 2 terminals)
user:~/myFolder$ sudo ./init.sh

#!/bin/bash
gnome-terminal -- ptp4l -i enp3s0f2s -P -2 -s -m -q
gnome-terminal -- phc2sys -a -rr -q -m

that gave me an error since gnome-terminal should not be called with sudo.
user:~/myFolder$ sudo ./init.sh

#!/bin/bash
sudo -u $SUDO_USER gnome-terminal -- ptp4l -i enp3s0f2s -P -2 -s -m -q
sudo -u $SUDO_USER gnome-terminal -- phc2sys -a -rr -q -m

That give me an error since both services need sudo
user:~/myFolder$ ./init.sh

#!/bin/bash
gnome-terminal -- sudo ptp4l -i enp3s0f2s -P -2 -s -m -q
gnome-terminal -- sudo phc2sys -a -rr -q -m

no error but here I need to enter sudo password for each terminal

A: Easier way is to use tmux (see) to do it.
You can do initial sudo in terminal. Then launch the tmux with the commands you need to run in parallel (you can use the sample command below and add it in script).
tmux new-session -d -s multi-run 'your command'
tmux splitw -h -p 66 'your command'
tmux splitw -h -p 50 'your command'
tmux selectp -t 1
tmux splitw -v -p 50 'your command'
tmux selectp -t 3
tmux splitw -v -p 50 'your command'
tmux attach-session -t multi-run


text:
Q: Having Instruments always revert to script file on disk (instead of prompting) for iOS UIAutomation testing Question:
Is there some way to shush up Instruments from warning about changes on disk to the currently loaded script, and have it just use the latest version of the script on disk? I'm always editing it outside of Instruments.
Background:
I'm editing my UIAutomation scripts (JavaScript of course) inside Xcode. I select them in the UIAutomation Instrument for profiling with the Instruments tool. I can hit record and all is good.
As I'm building my testing script, I'll edit it in Xcode and toggle the record button in the Instruments app to restart the test.
Instruments prompts me about a change to the script in an external location. I say "Revert" (to disk version) every time. I'm not keen on editing my scripts inside Instruments because then I keep switching between the 'Script' view and the 'Trace Log' view.

*

*Note: I'm using Xcode 4.4.1 on Mountain Lion 10.8.1 with the iOS5.1 base SDK.

A: I found a solution:

*

*I use an #import directive in a javascript file to import the file that I'm constantly changing.

*I point Instruments to this shell of a javascript file, whose only purpose is to import my actual test file, in active development.

*I then modify the file I'm actively developing, in another editor, and Instruments won't complain


text:
Q: Can't change url with map and do redirect I need to set up redirecting some requests to api depending on the value of variables. When using if statements, everything works fine. But when I try to use map instead of if, I get a "the rewritten URI has a zero length" error.
My working config file using if:
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Server $host;
proxy_redirect off;

upstream backend {
    server 192.168.2.2:5987;
}

server {
    listen       80;
    server_name  exemple.com;
    client_max_body_size 32m;
    charset utf-8;
    location /static/ {
        alias /opt/project/public/;
    }
    location /media/ {
        alias /opt/project/media/;
    }
    location /api/v2/ {
        set $go "";

        # abc query parameter exists
        if ($arg_abc) {
            set $abc $arg_abc;
            set $go "abc";
        }

        # id query parameter exists
        if ($arg_id) {
            set $mid $arg_id;
            set $go "${go}id";
        }

        # For v2 REST API remove id query parameter from URL
        if ($args ~ (.*)id=[^&]*(.*)) {
            set $args $1$2;
        }

        # For v2 REST API remove abc query parameter from URL
        if ($args ~ (.*)abc=[^&]*(.*)) {
            set $args $1$2;
        }

        # only id query parameter exists
        if ($go = "id") {
          rewrite ^/api/v2/(.*)$ /api/v1/$1$mid/ last;
        }

        # only id and abc query parameters exists
        if ($go = "abcid") {
          rewrite ^/api/v2/(.*)$ /api/v1/$1$mid/$abc/ last;
        }
    }
    location / {
        proxy_pass http://backend;
    }
}

And my not working config using map:
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Server $host;
proxy_redirect off;

map $arg_abc $abc {
    default     $arg_abc;
}
map $arg_abc $go {
    default     abc;
}

map $arg_id $mid {
    default     $arg_id;
}
map $arg_id $go {
    default     ${go}id;
}

map $args                 $args {
    ~(.*)id=[^&]*(.*)     $1$2;
    ~(.*)abc=[^&]*(.*)     $1$2;
}

map $go $api_v1 {
    id    /api/v1/$1$mid/;
    abcid  /api/v1/$1$mid/$abc/;
}

upstream backend {
    server 192.168.2.2:5987;
}

server {
    listen       80;
    server_name  exemple.com;
    client_max_body_size 32m;
    charset utf-8;
    location /static/ {
        alias /opt/project/public/;
    }
    location /media/ {
        alias /opt/project/media/;
    }
    location /api/v2/ {
        set $go "";
        rewrite ^/api/v2/(.*)$ $api_v1 last;
    }
    location / {
        proxy_pass http://backend;
    }
}

As I found out, I get the error "the rewritten URI has a zero length" because the $api_v1 variable remains empty, since the $go value remains empty, but why is map not processing the url? I tried installing / before $api_v1 in location, but then only parameters without the /api/v1/ part come to my backend.
For example, after processing the request http://exemple.com/api/v2/exemple/test/?id=9090&abc=xyz&stop=pots&rest=api
I expect to get http://exemple.com/api/v1/exemple/test/9090/xyz/?stop=pots&rest=api
But I get http://exemple.com/?id=9090&abc=xyz&stop=pots&rest=api
What's wrong with my map settings?


text:
Q: Compare the mean of two samplings following normal distribution The following is a problem for A-level test that I don't know how to solve.
The weight of a pig is normally distributed with mean 375 g and standard deviation 22 g. The weight of a rabbit is normally distributed with mean 425 g and standard deviation 25 g.
i) Five pigs and four rabbits are randomly chosen. Find the probability that the pigs weigh more than the rabbits.
ii) Find the probability that the average weight of a sample of 10 rabbits will exceed the average weight of a sample of 8 pigs by at least 39 g.
Can someone help me? Thanks a lot!

A: Guide:
i)
Let $P_i$ be normally distributed for $i=1,2,3,4,5$ with the parameters that you mention for a pig.
Let $R_i$ be normally distributed for $i=1,2,3,4$ with the parameters that you mention for a rabbit.
Then $X:=P_1+P_2+P_3+P_4+P_5-R_1-R_2-R_3-R_4$ has normal distribution.
Now find the parameters of this distribution and then find $P(X>0)$.
ii)
If $\overline P$ denotes the average weight of $8$ pigs, and $\overline R$ denotes the average weight of $10$ rabbits.
Then $Y:=\overline R-\overline P$ has normal distribution.
Now find the parameters of this distribution and then find $P(Y>39)$ or equivalently $P(Y-39>0)$.


text:
Q: Java Lists alternate for nested forEach Below is my working code set of nested forEach. Looking for the best alternate to make code clean. Looks to be a very complex set of code
This Model1 is a List containing various SubList and other few elements
List<Model1> listModel1 = getDataForModel1(......);
listModel1.getSubList1().forEach(dataSubList1 -> {
    dataSubList1.getChildSublList2().forEach(dataChildSubList2 -> {
        dataChildSubList2.getChildSubList3().forEach(dataChildSubList3 -> {
          if (dataChildSubList3.getIsValid()) {
              // Setting my required data in this dataChildSubList3 all properties
            }
        })
    })
})

The above code is working as expected but Looking for an alternate to forEach. Thus making the above code less complex. Thanks in advance

A: This answer should be seen as a sketch. Since the code does not explicitly define the return types, the code might not work 1:1.

In the following, I assume that:

*

*listModel1.getSubList1() returns a List<Data1>,

*dataSubList1.getChildSublList2() returns a List<Data2>, and

*dataSubList2.getChildSublList3() returns a List<Data3>.

If we use Java 8+, we can utilize the stream API:
List<Model1> listModel1 = getDataForModel1(......);
listModel1.getSubList1().stream()

    // 1st block replaces 1st foreach:
    .filter(Objects::nonNull)  // remove nulls, just to be safe
    .map(Data1::getChildSublList2) // transform each Data1-object to its list of
                                   // Data2-objects
    .flatMap(List::stream) // flatten: transform each list in a stream of its
                           // elements

    // 2nd block replaces 2nd foreach:
    .filter(Objects::nonNull) // remove nulls, just to be safe
    .map(Data2::getChildSublList3) // transform each Data2-object to its list of
                                   // Data3-objects
    .flatMap(List::stream) // flatten: transform each list in a stream of its
                           // elements

    // 3rd block replaces 3rd foreach:
    .filter(Objects::nonNull) // remove nulls, just to be safe
    .filter(Data3::getIsValid) // move if-condition to here
    .forEach(dataChildSubList3 -> {
        // Setting my required data in this dataChildSubList3 all properties
    });

It would be even better if we move the lambda-body of the forEach-lambda in a separate method (e.g. named foo) that takes a Data3 as parameter and does the processing, this would simplify the forEach(...) to:
listModel1.getSubList1().stream()
    ...
    .forEach(this::foo);

A: It's hard to tell by your original question if you need the lists on the top layer.
If all you need is the list of dataChildSubList3 you could do this:
List<Model1> listModel1 = getDataForModel1(......);
listModel1.getSubList1()
.stream()
.flatMap(dataSubList1 -> dataSubList1.getChildSublList2().stream())
.flatMap(dataSubList2 -> dataSubList2.getChildSublList3().stream())
.filter(dataSubList3::getIsValid)
.forEach(dataChildSubList3 -> {
          // Setting my required data in this dataChildSubList3 all
    })


text:
Q: How to change a worksheet Macro to run a double click sub procedure over a whole workbook in Excel I have a macro that when I double click a cell it inserts a checkmark.  I use it very often and would like to have it load and run with every sheet, but I do not know what to change to have it in my Personal.XLSB Alternatively, I'd like to code it so it works on all sheets in a Workbook.
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not Intersect(Target, Range("A1:Z500")) Is Nothing Then
Application.EnableEvents = False
If Target.Value = ChrW(&H2713) Then
    Target.ClearContents
    Cancel = True
Else
    Target.Value = ChrW(&H2713)
    Cancel = True
End If
End If
    Application.EnableEvents = True
End Sub

Many thanks if anyone could help me with this, I've tried a few things, but it does not work.

A: Let's say for now you want to apply this code to all of the worksheet so you don't need to create this code one by one for all of the sheets. Simply, in the VBE, double click ThisWorkbook (left explorer) and on the right window on top choose Workbook for the left drop down and on the right drop down you will have access to all of the events that you can have for worksheets, the difference is that they start with sheet instead of worksheet so for this one you should choose SheetBeforeDoubleClick. Paste the content of your code there and that code will work on all of your worksheets, even the one you create after pasting this code.


text:
Q: Removing negatives from an unknown list in Python Working in Python, how would I write code to remove negatives from an unknown list of integers using for loops and if statements?
def mod_lis (list):
    for i in range(len(list)):
        if list[i] < 0:
            del list[i]
    return list

A: The problem with your code is that you modify your list during your for loop. The result is that you jump over elements this way and get an IndexError soon since your list has been shortened.
You can do this with this list comprehension:
mylist = [val for val in mylist if val>=0]

A: You can use filter() and a lambda function:
my_list = filter(lambda x : x >= 0, mylist)

A: It's better to make a copy of the list without selected items, but if you have to modify in place, try this:
def remove_negatives(list):
    pos = 0
    for item in list:
        if item >= 0:
            list[pos] = item
            pos += 1
    del list[pos:]


text:
Q: HTML text box or area with scrollbars, to be filled with Ajax response I need to create a fixed size (height and width) text area or box in a HTML page. This area will be filled with responses from Ajax requests. Some of these responses will be too big to fit within this area, therefore, some scroll bars should be displayed. Nice to have (but not must have), users should be to select the content of the box.
How to achieve this best in HTML? It seems like textarea could be a solution, but how do I work with height and width rather col and rows? If possible, I would like to avoid having to use a form just for this textarea. Should I use a separate Javascript/Jquery library instead?
I am looking for code examples to design/implement this box. Thanks.

A: You could do
<textarea class="myTextarea"></textarea>

and add some CSS style
.myTextarea {
 width: 300px;
 height: 200px;
}

do you already have the code to populate the text area with the Ajax response?

A: The CSS :
.className {
 width: 500px;
 height: 400px;
 overflow: scroll; /*This is not required, if it's a text area*/
}

The HTML :
<div class="className"> </div>

OR
<textarea class=".className"> </textarea>

The JQuery:
var ajax_control = jQuery.ajax({
    url: "target.php",
    type: "POST",
    data: {variable_name: variable_value}
});
ajax_control.always(function(){
    $('.className').append(ajax_control.responseText);
        //$('.className').html(ajax_control.responseText);
        //$('.className').val(ajax_control.responseText); // if this is a textarea
});


text:
Q: Android setting new Intent from Activity class I have class that extends Activity. That has a "Logout" menu options. When I click that it calling logout(context) from another class (not extends from Activity).
public class MyTask extends Activity{

@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.listlayout);
}
   @Override
   public boolean onCreateOptionsMenu(Menu menu)
   {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mytaskmenu, menu);
return true;
   }
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
       switch (item.getItemId()) {
           case R.id.logout:
               Functions.logout(getBaseContext());
               return true;
           default:
              return true;
        }
    }
}

 public class Functions {

    public static void logout(Context context)
    {
        DbAdapter_User db2= new DbAdapter_User(context);
        db2.open();
        db2.handleLogout();
        db2.close();
        context.startActivity(new Intent(context, LogIn.class));
    }

And the error is
android.util.AndroidRuntimeException:
Calling startActivity() from outside of an Activity  context requires the         FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

WHAT IS GOING WRONG?

A: You need to call the context of the MyTask activity in the functions class, by passing the context of the activity, instead of passing Functions.logout(getBaseContext()); try Functions.logout(this.getContext());


text:
Q: how user can respond to system prompts using shell script I am trying to automate something using shell script.
My question is when there is a system prompt, for e.g. "Do you want to continue (y/n):"
And I need to input y using my shell script, how can it be done ? So at the end when the system prompt displays on the shell then my shell script should be automatically able to enter y.
Thanks in advance.

A: You can try an expect script

It is used to automate control of interactive applications such as
  telnet, ftp, passwd, fsck, rlogin, tip, ssh, and others. Expect uses
  pseudo terminals (Unix) or emulates a console (Windows), starts the
  target program, and then communicates with it, just as a human would,
  via the terminal or console interface.

A: It is really quite easy using redirection, and there are several ways to do it.  This uses a here string.  First to generate that system prompt:
more one.sh
read -p "Do you want to continue (y/n): " ans
echo "Answer was $ans"

Now the script to run the program:
bash one.sh <<< 'y'

Output:
Answer was y

Warning!  This works by redirecting the process's standard input stream.  Some programs, particularly when getting passwords, access the terminal driver at a low level for security reasons.