text:
Q: How do I use Virtual Environments with SublimeREPL? I am a beginner to coding in general and I just found out that we could create virtual environments and was soon disappointed to see that there was no tutorial or answer anywhere for a Windows user and the only one I found was THIS. Which kinda solves my problem but isn't ideal. And I wanted to follow forms that actually SOLVED my problem but they were for mac and linux users. So can someone help me out?
Thanks in advance !!!

A: It is mentioned in the docs:

For virtualenv created environments to be discoverable by SublimeREPL
they should be created or symlinked in one of the following:

*

*~/.virtualenvs default for virtualenvwrapper

*~/.venvs default for venv

Alternatively, more paths can be added to "python_virtualenv_paths" in
the SublimeREPL configuration file.

If your virtualenvs are created in another directory add them to SublimeREPL.sublime-settings. For me, they are in ~/Envs:
{
    "python_virtualenv_paths": ["C:\\Users\\my_username\\Envs"]
}

Assuming you're using the correct path, sublimeREPL: Python - virtualenv allows you to select the venv you want to work with:


text:
Q: Returning DataTable objects with WCF service This is a strange problem that I am having with WCF trying to send DataTable in the response. I have the following service contract:
[ServiceContract]
public interface ISapphireDataService {
    [OperationContract]
    DataTable LoadData(string query, DateTime start, DateTime end);

    [OperationContract]
    string LoadDataTest();
}

And the following implementation of the methods (where provider is a class that makes the database call and returns back a DataTable):
public DataTable LoadData(string query, DateTime start, DateTime end) {
    //DataSet temp = new DataSet();
    //temp.Tables.Add(provider.LoadData(query, start, end).Copy());
    //return temp;

    return provider.LoadData(query, start, end).Copy();
}

public string LoadDataTest() {
    return "Hello World!";
}

Now, when I leave it like this, I always get an error when calling the LoadData(...) method:

An error occurred while receiving the HTTP response to
  http://localhost:8731/Design_Time_Addresses/DataProviderServiceLibrary/SapphireDataService/.
  This could be due to the service endpoint binding not using the HTTP
  protocol.
  This could also be due to an HTTP request context being
  aborted by the server (possibly due to the service shutting down).
  See server logs for more details.

This is rather odd because the service is configured to use the wsHttpBinding, which I assume uses HTTP propocol. This error does not occur if I try calling the LoadDataTest() method!
So what I have done was put this table I have gotten from the database into a DataSet object and it worked! No errors or anything of the sort. BUT, the table that was returned in the DataSet was EMPTY. All the fields were Null and no data has been transfered/de-serialized properly, it seems :(
This seems to be a common issue but I am yet to see an answer to this that works. Any ideas?

A: Using DataSets and DataTables aren't best practice. They are quite bulky, best to use a collection of dataclasses (poco's / dto's).
Some background info:
Returning DataSets from WebServices is the Spawn of Satan and Represents All That Is Truly Evil in the World

A: While I admit that sending DataSets and DataTables via services is BAD and I actually have changed it so I am not doing so, the root of the problem lied elsewhere.
For those that absolutely HAVE to use DataTables/DataSets, the error I was getting was because I was trying to send a DbNull object. I guess it is not serializable or there is some other reason it refused to send it.
After manually "converting" DbNull into null (I had to do this to extract data into my own custom DataContract anyways), the error was gone and it worked!

A: I know this is an old question, but maybe someone is still experiencing the same problem (like I did).
I was faced with the same confusing error message and spent hours banging my head  when it hit me....
    public DataTable GetDataTable()
    {
        DataTable dt = new DataTable(**"MY_NAME"**);
        dt.Columns.Add("ID", typeof(int));
        dt.Columns.Add("Caption", typeof(string));

        dt.Rows.Add(new object[] { 1, "hooray!" });
        return dt;
    }

you should give your DataTable a name, i used a overloaded constructor and no more errors!
EDIT:
Of course, you really shouldn't use DataTable or DataSet as a return type from a WCF service. For me it was just for testing purposes, because I thought it's the quickest way to get something out of a database and over the wire....boy was i wrong :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting PyScripter Portable to work with IPython How can I set PyScripter up to work with IPython as the "embedded" interpreter rather than the plain Python one?
I am using portable python.
I've tried for a few hours with no success.
I imagined it's just a C/L parameter.
But that doesn't seem the case.
Help much appreciated.

A: I don't think that this is possible as PyScripter does this based on a specified Python engine. For portable installation these settings are used and this is also what Portable Python shortcut

PyScripter-Portable.exe

does to set up the environment and configure Python engine to be used.

A: I don't know if this will work but you could try the following in the embedded interpreter:
>>> from IPython import embed
>>> embed()


text:
Q: $sp register does not change at the beginning of the function Linked to: How to get a call stack backtrace?(GCC,MIPS,no frame pointer)
I am reproducing the call stack(more details at the link above) by iterating the function using the assembly code and user stack.
I have to find the previous $sp for each function, most of the functions start with the following instruction:
addiu sp, sp, -80
I can easily conclude the previous $sp from the opcode.
The problem is that I found functions that never changes the $sp even though they use the stack, it seems that the functions that call this kind of functions use the same activation frame on the stack In other words never change $sp.
How can I reproduce the previous $sp in this case?

A: This can happen with optimized code.
If a leaf function only modifies the temporary registers, and returns to a return statement in its caller's code, then there is no need for $ra to be changed, and there is no need for a stack frame for that function. Example:
int caller(....) {
  int a, b, c;
  ...
  c = leaf(a,b);
  return c;
}
int leaf(int a, int b) {
  return a + b;
}

See also tail calls.


text:
Q: Using the Apple Battery Charger with non-Apple batteries The Apple Battery Charger's product description page states:

The Apple Battery Charger can recharge one or two batteries at a time. It's optimized for Apple-supplied batteries and it works with AA NiMH batteries from other companies, too.

Does anyone know the required specifications for using non-Apple batteries?
The Apple supplied batteries are AA Ni-MH Min. 1900 mAh 1.2V HR6.
I have some Powerex AA Ni-MH Min. 2500 mAh 1.2V, so I'm wondering if they are compatible. I'm also curious what other non-Apple batteries are compatible.

A: Apple Batteries are Rebranded Sanyo Batteries
According to engadget, the Apple supplied batteries are actually Sanyo Eneloop HR-3UTG, so it appears that's one option for buying additional batteries to use with the Apple Battery Charger.
Powerex Batteries Don't Work
According to the Apple Battery Charger Manual,

*

*Flashing Amber: May indicate any of the following conditions:

*

*The batteries haven't been properly installed in the charger.

*An unsupported type of battery is in the charger.

*The batteries may be faulty or damaged and should be replaced.

With that information, I tried charging the Powerex 2500 and 2700 batteries but received a flashing amber light.
Looks like I need to buy some of the Sanyo Eneloop HR-3UTG batteries.

A: I too had original apple batteries and the orange light was flashing.  I took carefully reinserted (rotated and cleaned the bottom and top of the leads) them and they seem to be charging now.

A: And in my case, cleaning the terminals on the Apple charger made all the difference


text:
Q: Web Service Architecture - multi tenancy design pattern (maybe) I having a slight design problem : I have to create a Web Service (asmx or wcf) that retrieves customer data from multiple database servers, each one is exactly the same except they will contain data for different States (1 DB server per state, big states can have multiples etc).
This will be used by a call center, for example, someone calls the call center and says, can i have an indication when my order will be delivered my order no is "aa_etc" and the service should run a query on all servers and return all the orders details for that order.
This is straight forward, except there is multiple servers to query.My idea is to have central sqlite db with all connection strings of the current online servers and then query each one in turn

public class OnlineServer
{
 public string Name {get;set;}
 public string ConnectionString {get;set;}
}
...
public class Order
{
   public List OrderDetail getDetails(string orderno,string connstring)
   {
     //Code to get all orders from database using specified connstring
   }
   ....
}
....

List servers = getOnlineServers();

foreach(OnlineServer in servers)
{
  OrderDetails d = Order.getDetails("aa_etc",OnlineServer.ConnectionString);
}

Just writing down this idea feels totally wrong.
I would really appreciate it if someone can help me get going with this in the right direction, this is a really big project and starting this wrong will just end up in tears later on.
Thanks

A: If you cannot some how merge the data in to a single DB.
You may be able to use nHibernate. It can query multiple databases see http://mikehadlow.blogspot.com/2008/10/mapping-entities-to-multiple-databases.html
You would have to set up a different entity per server. By doing it this way it would take care of all your DB connections, pooling, sessions etc.

A: I want to consider this problem a bit futher but I have an off-the-wall idea which might be of interest so I'll through it out there.

My idea is to have central sqlite db
  with all connection strings of the
  current online servers and then query
  each one in turn

This gave me an idea: why not fire off a search query to each system asynchonously?  I'm thinking AJAX here (but you could use iFrames)...

*

*The user enters a search and hits "Go".

*Somehow you loop through your collection of known data sources, but each "sub" search is seperate and asynchonous (think federated search).

*As results come back they are displayed on screen to the user - who can then stop the search process if they get a match they like.

I'm assuming the data would be "pulled together" visually by the UI - either by straight layout or via clever client-side code - this would give you further options to tailor the UI but at the expense of a more complex client-side code base.
You'd have other options too, like allowing the user to narrow their search by data source if they wanted to.
Also, adding / removing data sources would be simple.
This is where I need to address you're actual question more directly; in my opinion you'd most definately want a seperate service per database - but there's flexibility in how you do that.

*

*Having a collection of services that reflects the data sources gives you a clean logical architecture.

*Doing this doesn't preclude putting something over the top that brings it together (thinking of loose-coupling here).

*It's always much easier to put stuff together than tear them apart.

*You'd still be able to re-use code: multiple instances perhaps.

*You'd have some management overhead due to multiple instances - but also the flexibility to management them better: access control, dedication of resources, etc.


text:
Q: how can I access my ustom attribute in the Azure AD B2C I use
POST https://graph.windows.net/contosob2c.onmicrosoft.com/users?api-version=1.6
to get the Information from users in my Azure AD B2C.
But how can I access my ustom attribute in the Azure AD B2C?
Thanks for your help
Stefan

A: You can extend your Azure AD schema in the same way you would your on-premises directory. The following page on MSDN has some information on this for you.
You can also use the Graph API to achieve this as well using a POST.
Specifically for Azure AD B2C, you can do this in the portal.

A: you can try with B2CGraphClient, in this link https://azure.microsoft.com/en-gb/documentation/articles/active-directory-b2c-devquickstarts-graph-dotnet/ you will find how you can see your custom attributes (see the last section)


text:
Q: JSDoc: Auto detecting class methods My jsdocs look like the following
module.exports = class gateio extends Exchange {
    /**
     * @class
     * @name gateio
     */

    async fetchOrder (id, symbol = undefined, params = {}) {
        /**
         * @method
         * @name gateio#fetchOrder
         * @description Retrieves information on an order
         * @param {string} id : Order id
         * @param {string} symbol : Unified market symbol
         * @param {boolean} params.stop : True if the order being fetched is a trigger order
         * @param {dictionary} params : Parameters specified by the exchange api
         * @returns [Order structure]{@link https://docs.ccxt.com/en/latest/manual.html#order-structure}
         */

Is there any way to auto detect that

*

*that fetchOrder is a method

*its name is fetchOrder and it belongs to class gateio

*its description is "Retrieves information on an order"

*That gateio is a class

*that gateio's name is gateio

Or do I have to specify @method, @name, @class, @description for every doc?
These @'s seem superfluous and I would like to exclude them if I could

A: It seems like jsdoc is confused by module.exports = class ... .
I was able to get it to work like this:
/**
 * (description text)
 */
class gateio extends Exchange {
    /**
     * Retrieves information on an order
     * @param {string} id : Order id
     * @param {string} symbol : Unified market symbol
     * @param {boolean} params.stop : True if the order being fetched is a trigger order
     * @param {dictionary} params : Parameters specified by the exchange api
     * @returns [Order structure]{@link https://docs.ccxt.com/en/latest/manual.html#order-structure}
     */
    async fetchOrder (id, symbol = undefined, params = {}) {
        // ...
    }
}
module.exports = gateio


text:
Q: Sending Parameter to Method - NSTimeInterval I am trying to send a NSTimeInterval into a method which will run on the main thread from a method running on the background thread.  Unfortunately, I get this error:
Sending 'NSTimeInterval' (aka 'double') to parameter of incompatible type 'id'

here's my code - any idea what's going wrong?
First, I setup my NSTimerInterval, and call performSelectorOnMainThread:
NSTimeInterval delayBetweenIntAdsNSTimeInterval = [responseStringTimeBetweenAds doubleValue];
[self performSelectorOnMainThread:@selector(startTimerForAds:) withObject:delayBetweenIntAdsNSTimeInterval waitUntilDone:NO];

and here is the code for my method I am calling:
-(void)startTimerForAds:(NSTimeInterval)intervalBetweenAds {
}

Any ideas on what's going wrong with that?
Thanks,
UPDATE
I call:
[self performSelectorOnMainThread:@selector(startTimerForAds:) withObject:@(delayBetweenIntAds) waitUntilDone:NO];

and here is that method:
-(void)startTimerForAds:(NSInteger *)intervalBetweenIntAdsInteger {
}

but over that call (over the object), XCode shows:
Illegal type 'NSInteger *' (aka 'int *') used in a boxed expression

and it shows over [intervalBetweenIntAdsInteger doubleValue]:
Bad receiver type 'NSInteger *' (aka 'int *')

A: NSTimeInterval is not an object. Try NSNumber, that should do it :
NSTimeInterval delayBetweenIntAdsNSTimeInterval = [responseStringTimeBetweenAds doubleValue];
[self performSelectorOnMainThread:@selector(startTimerForAds:) withObject:@(delayBetweenIntAdsNSTimeInterval) waitUntilDone:NO];

-(void)startTimerForAds:(NSNumber *)intervalBetweenAds {

     NSTimeInterval i = [intervalBetweenAds doubleValue];

}

UPDATED because of your UPDATE:
[self performSelectorOnMainThread:@selector(startTimerForAds:) withObject:@(delayBetweenIntAds) waitUntilDone:NO];

-(void)startTimerForAds:(NSNumber *)intervalBetweenAds {
     int i = [intervalBetweenAds intValue];
}


text:
Q: Does yarn add package --build-from-source behave like npm install package --build-from-source when passing node-gyp flags to packages? It looks like yarn does not pass node-gyp flags to native packages the way npm does.
For example when attempting to install sqlite3@3.1.6 with:
npm install sqlite3@3.1.6 \
  --build-from-source \
  --sqlite_libname=sqlcipher \
  --sqlite=`brew --prefix` \
  --verbose

we get a successful installation of sqlite3 with sqlcipher extensions, due to passing --sqlite_libname and --sqlite, which are specified in sqlite3's binding.gyp.
But, when attempting to use yarn, and running what I would think to be the equivalent command, it looks like the flags aren't honored:
yarn add sqlite3@3.1.6 \
  --force \
  --build-from-source \
  --sqlite_libname=sqlcipher \
  --sqlite=`brew --prefix` \
  --verbose

With npm unrecognized command line arguments are converted to gyp flags.
With yarn that doesn't seem to work.
Is there a way to get this functionality with yarn?

A: Yarn does not automatically expose -- arguments of install command to lifecycle scripts (pre/post/install scripts in package.json of dependencies).
Here is the code where Yarn builds Env for the script execution https://github.com/yarnpkg/yarn/blob/master/src/util/execute-lifecycle-script.js#L39.
You can pass specific values via env setting in .yarnrc and also it builds npm_config_* settings based on .yarnrc/.npmrc configuration.

A: This is currently possible by using environment variables on the format npm_config_{snake_case_param}=true/false
For example, npm install --build-from-source=true becomes:
npm_config_build_from_source=true yarn install

It's documented here https://yarnpkg.com/lang/en/docs/envvars/#toc-npm-config


text:
Q: Search associative array for specific value based on set variable I'm retrieving some JSON that I am converting to an associative array. The issue that I am having is I am trying to get the email value from the user's who id matches the value that I have already set as a variable.
Here is what the array looks like
Array
(
[object] => list
[data] => Array
    (
        [0] => Array
            (
                [object] => pro
                [id] => pro_77c9c6a85d814e059a6a2690989bae29
                [first_name] => Jane
                [last_name] => Doe
                [full_name] => Jane Doe
                [initials] => JD
                [email] => admin@testorg.com
                [mobile_number] => 9998761234
                [messaging_uuid] => 4547c231c3e7d0ff1796f47b88f166d5
                [color_hex] => EF9159
                [avatar_url] => /assets/add_image.png
                [avatar_thumb_url] =>
                [has_avatar] =>
                [organization_name] => testorg
                [is_admin] => 1
                [permissions] => Array
                    (
                        [show_company_setup] => 1
                        [can_see_home_data] => 1
                        [show_reporting] => 1
                    )

                [is_super_pro] =>
                [is_archived] =>
                [impersonated] =>
            )

        [1] => Array
            (
                [object] => pro
                [id] => pro_0fcb8e8610e54c518078db77ced7530e
                [first_name] => Robert
                [last_name] => Jordan
                [full_name] => Robert Jordan
                [initials] => RJ
                [email] => rj@testorg.com
                [mobile_number] => 4547457742
                [messaging_uuid] => 0fcb8e8610e54c518078db77ced7530e
                [color_hex] => EF9159
                [avatar_url] => /assets/add_image.png
                [avatar_thumb_url] =>
                [has_avatar] =>
                [organization_name] => testorg
                [is_admin] => 1
                [permissions] => Array
                    (
                        [show_company_setup] => 1
                        [can_see_home_data] => 1
                        [show_reporting] => 1
                    )

                [is_super_pro] =>
                [is_archived] =>
                [impersonated] =>
            )

    )

[url] => /pros

)
Im basically trying to match the value that I have set in my pro_id variable
pro_0fcb8e8610e54c518078db77ced7530e

To the 'ID' Key in the array above and get the 'email' value associated to that same array and store for use later in my code.
Here is what I have so far, but no joy
    foreach ($proObject as $key => $value) {

  if ($key['id'] == $pro_id)
    $techmail = $key['email'];

}

A: From my understanding of your question, and if you want to get only one element, you should be able to use array_search with array_column to get the index of the searched element. Using that you can then access the element and its corresponding email value. If you might expect more than one element I would use array_filter.
One Element:
In short:
$i = array_search($pro_id, array_column($proObject, 'id'));
$element = ($i !== false ? $proObject[$i] : null);
print_r($element["email"]);

Full code:
<?php
$proObject = array(
    array(
        "object" => "pro",
        "id" => "pro_77c9c6a85d814e059a6a2690989bae29",
        "first_name" => "Jane",
        "last_name" => "Doe",
        "full_name" => "Jane Doe",
        "initials" => "JD",
        "email" => "admin@testorg.com",
        "mobile_number" => "9998761234",
        "messaging_uuid" => "4547c231c3e7d0ff1796f47b88f166d5",
        "color_hex" => "EF9159",
        "avatar_url" => "/assets/add_image.png",
        "avatar_thumb_url" => "",
        "has_avatar" => "",
        "organization_name" => "testorg",
        "is_admin" => "1",
        "permissions" => array(
            "show_company_setup" => "1",
            "can_see_home_data" => "1",
            "show_reporting" => "1",
        ) ,

        "is_super_pro" => "",
        "is_archived" => "",
        "impersonated" => "",
    ) ,
    array(
        "object" => "pro",
        "id" => "pro_0fcb8e8610e54c518078db77ced7530e",
        "first_name" => "Robert",
        "last_name" => "Jordan",
        "full_name" => "Robert Jordan",
        "initials" => "RJ",
        "email" => "rj@testorg.com",
        "mobile_number" => "4547457742",
        "messaging_uuid" => "0fcb8e8610e54c518078db77ced7530e",
        "color_hex" => "EF9159",
        "avatar_url" => "/assets/add_image.png",
        "avatar_thumb_url" => "",
        "has_avatar" => "",
        "organization_name" => "testorg",
        "is_admin" => "1",
        "permissions" => array(
            "show_company_setup" => "1",
            "can_see_home_data" => "1",
            "show_reporting" => "1",
        ) ,

        "is_super_pro" => "",
        "is_archived" => "",
        "impersonated" => "",
    )
);
$pro_id = "pro_0fcb8e8610e54c518078db77ced7530e";

$i = array_search($pro_id, array_column($proObject, 'id'));
$element = ($i !== false ? $proObject[$i] : null);
print_r($element["email"]);
?>

Multiple Elements:
In short:
class idEqualsFilter {
    private $id;

    public function __construct($id) {
        $this->id = $id;
    }

    function __invoke($i) {
        return $this->id === $i["id"];
    }
};
$elements = array_filter($proObject, new idEqualsFilter($pro_id));
print_r(array_column($elements, "email"));

Full code:
<?php
$proObject = array(
            array(
                "object" => "pro",
                "id" => "pro_77c9c6a85d814e059a6a2690989bae29",
                "first_name" => "Jane",
                "last_name" => "Doe",
                "full_name" => "Jane Doe",
                "initials" => "JD",
                "email" => "admin@testorg.com",
                "mobile_number" => "9998761234",
                "messaging_uuid" => "4547c231c3e7d0ff1796f47b88f166d5",
                "color_hex" => "EF9159",
                "avatar_url" => "/assets/add_image.png",
                "avatar_thumb_url" => "",
                "has_avatar" => "",
                "organization_name" => "testorg",
                "is_admin" => "1",
                "permissions" => array
                    (
                        "show_company_setup" => "1",
                        "can_see_home_data" => "1",
                        "show_reporting" => "1",
                    ),

                "is_super_pro" => "",
                "is_archived" => "",
                "impersonated" => "",
            ),
            array(
                "object" => "pro",
                "id" => "pro_0fcb8e8610e54c518078db77ced7530e",
                "first_name" => "Robert",
                "last_name" => "Jordan",
                "full_name" => "Robert Jordan",
                "initials" => "RJ",
                "email" => "rj@testorg.com",
                "mobile_number" => "4547457742",
                "messaging_uuid" => "0fcb8e8610e54c518078db77ced7530e",
                "color_hex" => "EF9159",
                "avatar_url" => "/assets/add_image.png",
                "avatar_thumb_url" => "",
                "has_avatar" => "",
                "organization_name" => "testorg",
                "is_admin" => "1",
                "permissions" => array
                    (
                        "show_company_setup" => "1",
                        "can_see_home_data" => "1",
                        "show_reporting" => "1",
                    ),

                "is_super_pro" => "",
                "is_archived" => "",
                "impersonated" => "",
            )
    );
$pro_id = "pro_0fcb8e8610e54c518078db77ced7530e";

class idEqualsFilter {
    private $id;

    public function __construct($id) {
        $this->id = $id;
    }

    function __invoke($i) {
        return $this->id === $i["id"];
    }
};
$elements = array_filter($proObject, new idEqualsFilter($pro_id));
print_r(array_column($elements, "email"));
?>


text:
Q: Can I make Entity Associations optional or nullable? I have a Superhero. Superheros can have many weapons. Superheros can have many vehicles.
Superheros can attach their weapons to vehicles, but they shouldn't have to.
http://fm001-forumimages.s3.amazonaws.com/EntityHero.png
In the Entity Framework, if I create a weapon and assign it to a Superhero, it also forces me to attach it to a vehicle (error below).

*

*Is this the expected behavior?

*What's the correct Entity Association mapping between Superhero, Weapon, and Vehicle?

*What's a good sample Google search phrase to understand this better?

Thanks!

A: You need a many to many relation on the weapons to superheroes and weapons to vehicles. It'd be likely expressed as a pair of linking tables, like this:
CREATE TABLE SuperheroWeapons (
    SuperheroId bigint NOT NULL,
    WeaponId bigint NOT NULL,
    CONSTRAINT SuperheroWeapons_PK PRIMARY KEY CLUSTERED (SuperheroId ASC, WeaponId ASC),
    CONSTRAINT SuperheroWeapons_FK_SuperheroId FOREIGN KEY (SuperheroId) REFERENCES Superheros (SuperheroId),
    CONSTRAINT SuperheroWeapons_FK_WeaponId FOREIGN KEY (WeaponId) REFERENCES Weapons (WeaponId)
)

and similar for the VehicleWeapons table.

A: Your Entity framework relationship between Weapons and Vehicles is off as well as superheros and weapons.
You'll want to make it a many to many relationship, ie. There are many vehicles with many weapons, and there also are many weapons that belong to many vehicles.
You can accomplish this with an intermediary entity one that maps to both weapons and vehicles and superhero and weapons.
take a look at Many to Many Relationships with EF


text:
Q: How to make a generic type an union type of Record and an interface in Typescript? I want to declare a couple singleton class (Angular service) that must have some members named after an enum. Until now I had it as a const:
enum RewardId {
  HEHE = 'AdMobRewardIdHEHE',
  HOHO = 'AdMobRewardIdHOHO',
}

interface RewardObject {
  id: RewardId;
  someData: any
}

const MyConst: Record<RewardId, RewardObject> = {
  [RewardId.HEHE]: {
    id: RewardId.HEHE,
    someData: 'someData'
  },

  [RewardId.HOHO]: {
    id: RewardId.HOHO,
    someData: 'someData'
  }
}

If I add a new RewardId Typescript lets me know that I have to implement it on MyConst this is what I want

[Typescript Playground link][2]
Now, I want to change it to a service (so a class) because it is easier to test and I also need some methods there.
interface VaultMethods {
   someMethod1(): void;
  someMethod2(): void;
}

class MyClass implements Record<RewardId, RewardObject>, VaultMethods {
  [RewardId.HEHE] = {
    id: RewardId.HEHE,
    someData: 'someData'
  };

  [RewardId.HOHO] = {
    id: RewardId.HOHO,
    someData: 'someData'
  };

  someMethod1() { }

  someMethod2() { }
}

[Typescript Playground][3]
As final step I need this to convert that class definition in a generic interface:
This does not work interface Vault<K, V> extends VaultMethods, Record<K, V> because An interface can only extend an object type or intersection of object types with statically known members.
If I make it a type it kind of works in the way that Typescript ask me to implement the methods and members
type Vault<K, V> = Record<K, V> & VaultMethods;
class MyClass2 implements Vault<RewardId, RewardObject> {

}

Typescript Playground

But It shows an error in the Type Definition:

Is there a way to fix this?

A: It seems that you were missing a constraint on type parameter K. Since you're passing it to Record and that the K is probably an enum, you can say that K extends string.
type Vault<K extends string, V> = Record<K, V> & VaultMethods;

typescript playground


text:
Q: Convert date format qlikview My date is in the form of 31/01/2017. I want to format it as 31-Jan. How do I do it?
This doesn't work. There is an error.
=date(date#(=maxstring({[Date1]} [DATE]),'DD/MM/YYYY'), 'DD-MMM')

A: Function Date#() returns the expression as a date according to the string given as format-code. If the format code is omitted, the default date format set in the operating system is used.
Syntax:-
Date# (text [, format])

After that use Date function to convert it to date. Let's look at below example:-
Example:-
=Date(Date#('16JAN2014','DDMMMYYY'))

Above we have converted character format of date to date using date# and date functions.
Your Example:
I am confused what are you doing here. Just check (=maxstring({[Date1]} [DATE]),'DD/MM/YYYY') and check is Date1 matching 'DD/MM/YYYY' format.
And put it your date conversion format.
=date(date#( (=maxstring({[Date1]} [DATE]),'DD/MM/YYYY') , 'DD-MMM'))

A: The solution depends on your source data too.
If the data format in the source is a date, then it will be read by QlikView as a date and the conversion is simple.
Solution: date(Date, 'DD-MMM') as Date
If the data format in the source is NOT a date format, but text, then you need to split the text string in pieces and tell for each section what it is, using the subfield() function. You enclose this with a date#() function, telling that these pieces of text have to be interpreted as a date. Finally you perform a simple date formatting function date() on this to get it in the DD-MMM format.
Solution: date(date#(subfield(Date,'/',1)&subfield(Date,'/',2)&subfield(Date,'/',3),'DDMMYYYY'),'DD-MMM') as Date
If it is important that your month is capitalized, you may want to check your initial SET statement in the script specifying the MonthNames:
SET MonthNames='jan;feb;mrt;apr;mei;jun;jul;aug;sep;okt;nov;dec';


text:
Q: hue issues migrating from sqlite to maria db As one for the steps for migrating sqlite to maria db.I am dumping data to a json file.I am having the error ImportError: libsasl2.so.2: cannot open shared object file: No such file or directory.
plz advise how to resolve the issue.
Below is the log:
(env)[mapr@anvmaprpd04:39:/opt/mapr/hue/hue-3.10.0/build/env/bin] ./hue dumpdata >/tmp/sql-lite.json
[26/Apr/2017 13:55:36 +0000] settings     DEBUG    DESKTOP_DB_TEST_NAME SET: /opt/mapr/hue/hue-3.10.0/desktop/desktop-test.db
[26/Apr/2017 13:55:36 +0000] settings     DEBUG    DESKTOP_DB_TEST_USER SET: hue_test
Traceback (most recent call last):
  File "./hue", line 12, in <module>
    load_entry_point('desktop==3.10.0', 'console_scripts', 'hue')()
  File "/opt/mapr/hue/hue-3.10.0/desktop/core/src/desktop/manage_entry.py", line 57, in entry
    execute_from_command_line(sys.argv)
  File "/opt/mapr/hue/hue-3.10.0/build/env/lib/python2.6/site-packages/Django-1.6.10-py2.6.egg/django/core/management/__init__.py", line 399, in execute_from_command_line
    utility.execute()
  File "/opt/mapr/hue/hue-3.10.0/build/env/lib/python2.6/site-packages/Django-1.6.10-py2.6.egg/django/core/management/__init__.py", line 392, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/opt/mapr/hue/hue-3.10.0/build/env/lib/python2.6/site-packages/Django-1.6.10-py2.6.egg/django/core/management/base.py", line 242, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/opt/mapr/hue/hue-3.10.0/build/env/lib/python2.6/site-packages/Django-1.6.10-py2.6.egg/django/core/management/base.py", line 284, in execute
    self.validate()
  File "/opt/mapr/hue/hue-3.10.0/build/env/lib/python2.6/site-packages/Django-1.6.10-py2.6.egg/django/core/management/base.py", line 310, in validate
    num_errors = get_validation_errors(s, app)
  File "/opt/mapr/hue/hue-3.10.0/build/env/lib/python2.6/site-packages/Django-1.6.10-py2.6.egg/django/core/management/validation.py", line 34, in get_validation_errors
    for (app_name, error) in get_app_errors().items():
  File "/opt/mapr/hue/hue-3.10.0/build/env/lib/python2.6/site-packages/Django-1.6.10-py2.6.egg/django/db/models/loading.py", line 196, in get_app_errors
    self._populate()
  File "/opt/mapr/hue/hue-3.10.0/build/env/lib/python2.6/site-packages/Django-1.6.10-py2.6.egg/django/db/models/loading.py", line 78, in _populate
    self.load_app(app_name)
  File "/opt/mapr/hue/hue-3.10.0/build/env/lib/python2.6/site-packages/Django-1.6.10-py2.6.egg/django/db/models/loading.py", line 99, in load_app
    models = import_module('%s.models' % app_name)
  File "/opt/mapr/hue/hue-3.10.0/build/env/lib/python2.6/site-packages/Django-1.6.10-py2.6.egg/django/utils/importlib.py", line 40, in import_module
    __import__(name)
  File "/opt/mapr/hue/hue-3.10.0/desktop/core/src/desktop/models.py", line 40, in <module>
    from desktop.lib.exceptions_renderable import PopupException
  File "/opt/mapr/hue/hue-3.10.0/desktop/core/src/desktop/lib/exceptions_renderable.py", line 28, in <module>
    import desktop.lib.django_util
  File "/opt/mapr/hue/hue-3.10.0/desktop/core/src/desktop/lib/django_util.py", line 40, in <module>
    import desktop.lib.thrift_util
  File "/opt/mapr/hue/hue-3.10.0/desktop/core/src/desktop/lib/thrift_util.py", line 24, in <module>
    import sasl
  File "/opt/mapr/hue/hue-3.10.0/build/env/lib/python2.6/site-packages/sasl-0.1.1-py2.6-linux-x86_64.egg/sasl/__init__.py", line 1, in <module>
    from sasl.saslwrapper import *
  File "/opt/mapr/hue/hue-3.10.0/build/env/lib/python2.6/site-packages/sasl-0.1.1-py2.6-linux-x86_64.egg/sasl/saslwrapper.py", line 7, in <module>
    import _saslwrapper
ImportError: libsasl2.so.2: cannot open shared object file: No such file or directory


text:
Q: rm -rf written in Node.js I'd like to achieve rm -rf or a directory and all of it's contents with the minimum amount of code possible.
I've only found scripts with around 50 lines or more of code, there must be a less than 10 line code snippet for this?
There are two ways of doing this, pure Node.js or using spawn/exec to use the rm -rf command.
rm -rf way:
function spawnCustom(command, options) {
    const array = command.split(' ');
    const first_command = array[0];
    array.shift();
    return new Promise((resolve, reject) => {
        const spawn = require('child_process').spawn;

        const child = spawn(first_command, array, options);
        child.stdout.on('data', function(data) {
            process.stdout.write('stdout: ' + data);
            // Here is where the output goes
        });
        child.stderr.on('data', function(data) {
            process.stdout.write('stderr: ' + data);
            // Here is where the error output goes
            reject(data);
        });
        child.on('close', function(code) {
            process.stdout.write('closing code: ' + code);
            // Here you can get the exit code of the script
            resolve();
        });
    });
}

await spawnCustom('rm -rf ~/example_dir');

Node.js way:
const fs = require('fs')
const path = require('path')

let _dirloc = '<path_do_the_directory>'

if (existsSync(_dirloc)) {
    fs.readdir(path, (error, files) => {
        if(!error) {
            for(let file of files) {
                // Delete each file
                fs.unlinkSync(path.join(_dirloc,file))
            }
        }
    })

    // After the done of each file delete,
    // Delete the directory itself
    if(fs.unlinkSync(_dirloc)) {
        console.log('Directory has been deleted!')
    }
}

A lot of code for something simple.. There must be a more simple way?

A: That would be the rimraf module.
Can be done in 2 lines
 var rimraf = require('rimraf');
 rimraf('/some/directory', () => console.log('done'));

A: Available (experimentally) since Node v12.10
As per the NodeJS v14.0.0 docs this feature has been available since v12.10.0 but is marked experimental.
https://nodejs.org/api/fs.html#fs_fs_rmdir_path_options_callback
Async
const fs = require('fs');

(async function() {
  const cleanup_result = await new Promise((resolve, reject) => {
      fs.rmdir("./temp", {recursive: true}, (err) => resolve(err));
  });

  console.log(`Cleaned up data with result "${JSON.stringify(cleanup_result)}"`);
)();

Promisified Async
const fs = require('fs');
const util = require('util');
const rmdir = util.promisify(fs.rmdir);

(async function() {
  const cleanup_result = await rmdir("./temp", {recursive: true});
)();

Sync
const fs = require('fs');
// Process blocking action which can halt
// your program if deleting a large directory tree
fs.rmdirSync("./temp", {recursive: true});

A: There were moments that I also thought: I really wish there was a function to easily delete a directory recursively. I could talk about this for hours ("what makes a language 'complete' enough") but I think that would be out of the scope for stackoverflow.
To answer your question: first of all, your first example is an overkill! I would just use exec since the output will be very small. You could rewrite it way shorter:
const { exec } = require('child_process');
const deleteDir = (dir) => {
    exec(`test -d ${dir} && rm -rf ${dir}`, (err, stdout, stderr) => {
        if (err) {
            console.error(err);
            return;
        }
        console.log(`stdout: ${stdout}`);
        console.log(`stderr: ${stderr}`);
});
deleteDir('example-dir');

In this example test -d checks for the existence of the directory and returns exit code 0 on success or 1 on failure (which will never trigger the the right part of the &&.
But the thing is: if you're writing code for a larger public, you would like to support, for example, other operating systems. Packages like rimraf will take care of that for you! Look at its source code and especially the test cases.
Of course you can write it yourself, but I think because so many people use rimraf, all kinds of weird exceptions have been noticed and fixes has been committed etc.

A: The modern way to do this is with fs.rm({ recursive: true }). See the docs on this.


text:
Q: Deleted project folders/files remain in VSO/TFVC and the file system I had a solution containing the following projects:

*

*Web App 01

*Server Control Foo

*Server Control Bar

Each project has its own directory in the root of the solution directory, directly mirroring the structure of the solution.
I branched the solution, then combined items 2 & 3 into a new project within that solution, then deleted projects 2 & 3.  I committed the changeset.  The resulting structure in VS2015 solution explorer was this:

*

*Web App 01

*Server Control Library

I then merged the branch, and committed this also.  Over time, branching and merging has got slower and slower.  On inspecting the file structure of my hard drive, and Visual Studio Online, I see this folder structure:

*

*Web App 01

*Server Control Foo

*Server Control Bar

*Server Control Library

Despite Solution Explorer not listing the deleted projects, the folders and files from all my deleted projects remain.  Despite their status, they are also being branched every time.  Is this the correct behaviour, and is it safe to delete them?  If so, should I delete using VSO, Windows, or VS2015?

A: I assume you are using TFVC (changeset, branched the solution).
First, delete the projects from solution (right click the project in VS > Remove) just remove the relationship between projects and solution, the projects' files and folder are still existing in the hard drive. So you need to delete these files and folders from hard drive (file system).
Secondly, these files are still existing in the source control too, because they aren't marked as deleted if you just remove projects from solution, so check in changes just affect the solution file, it won't delete files from source control. So you need to delete them from source control and it's safe.
Steps to delete files:

*

*Go to Source Control Explorer in VS

*Right click Folder or file > Delete

*Check in changes

BTW, the files still can be restored if you don't permanently destroy them. (Destroy command), more information, you can refer to this article: Delete or restore files and folders in Team Foundation Version Control (TFVC)


text:
Q: need help modifying small javascript for rotating images I found this small code for rotating images in a placeholder, at this time I can only place one, could someone help me code this to place different folders to rotate in same or different pages..

A: Try using a jquery plugin like jCarousel or rCarousel
http://sorgalla.com/jcarousel/


text:
Q: Elasticsearch does not filter as expected I am using Elasticsearch 1.4
I have an Index:
curl -XPUT "http://localhost:49200/customer" -d '{"mappings": {"venues": {"properties": {"party_id": {"type": "string"},"sup_party_id": {"type": "string"},"location": {"type": "geo_point"}            }       }    }}'

And put some data, for instances:
curl -XPOST "http://localhost:49200/customer/venues/RO2" -d '{ "party_id":"RO2",  "sup_party_id": "SUP_GT_R1A_0001","location":{ "lat":"21.030347","lon":"105.842896" }}'
curl -XPOST "http://localhost:49200/customer/venues/RO3" -d '{ "party_id":"RO3",  "sup_party_id": "SUP_GT_R1A_0004","location":{ "lat":"20.9602051","lon":"105.78709179999998" }}'

and my filter is:
{"constant_score":
    {"filter":
        {"and":
            [{"terms":
                {"sup_party_id":["SUP_GT_R1A_0004","SUP_GT_R1A_0001","RO2","RO3","RO4"]
                }
            },{"geo_bounding_box":
                {"location":
                    {"top_left":{"lat":25.74546096707413,"lon":70.43503197075188},
                    "bottom_right":{"lat":6.342579199578783,"lon":168.96042259575188}
                    }
                }
            }]
        }
    }
}

the above query does not return data but It return data when I remove the following terms:
{"terms":
    {"sup_party_id":["SUP_GT_R1A_0004","SUP_GT_R1A_0001","RO2","RO3","RO4"]
    }
}

Please show me the problem, any suggestions is appreciated!

A: That's because the sup_party_id field is an analyzed string. Change your mapping like this instead and it will work:
curl -XPUT "http://localhost:49200/customer" -d '{
  "mappings": {
    "venues": {
      "properties": {
        "party_id": {
          "type": "string"
        },
        "sup_party_id": {
          "type": "string",
          "index": "not_analyzed"     <--- add this
        },
        "location": {
          "type": "geo_point"
        }
      }
    }
  }
}'


text:
Q: How to create S3 Bucket for three different environments using single root account? I've one AWS root account, if I need to grant the S3 bucket access to our application resides in Dev, Test and Prod environments. These S3 bucket will be accessed only by application and not by individual / manual user. I can refer multiple approaches, not sure which one is best approach here? Could you pls suggest on this?
Option-1: Create IAM user account for each environment with programmatic access only. Provide the Access KeyId and Secret Access key to respective environment(Dev, Test and Prod) to access the S3 resource. Separate S3 bucket will be created for each environment, S3 bucket policy will only allow the access to specific IAM user account only.
Option-2: Three separate AWS accounts. Not sure how to proceed on this further, will be having three root accounts to manage and separate billing, one S3 bucket for each AWS account.
Option-3: I can refer the landing zone concepts that comes with AWS organization account, Shared Services account, Log Archive Account and Security Account. Not sure where to specify / create the resources and IAM user account.


text:
Q: C++ function overload cause seg fault I have struct called Set.
struct Set {
string name;
string value;
bool is_condition;
bool is_bool_val; };

I have to store many of these 'Set' structures, so I am using a vector.
vector<Set> list;

For context, I am storing data about a mobile device such as an iPhone. A list of Set's describes one device! For example, an instance of set could have the following...
Set phone;
phone.name = "Serial Number";
phone.value = "FLMJ0000GGGG";
phone.is_condition = false;
phone.is_bool = false;

is_condition, tells me that this instance of Set needs to store either 'Good' or 'Bad' as the value. is_bool, tells me that the instance of Set needs to store a boolean value. See the below example.
Set device_wiped;
device_wiped.name = "Device Wiped";
device_wiped.is_bool = true;

Extrapolating from is_bool allows me to get input of either true or false, meaning the device either has, or has not been wiped (restored to factory settings).
I am using an overloaded wrapper function called new_set to create my Set elements, which are stored in my 'list' vector.
Set new_set(string name, const bool is_bool, const bool is_condition) {
    Set set;
    set.name = name;
    set.is_bool = is_bool;
    set.is_condition = is_condition;
    return set;
}

Set new_set(string name, const bool is_bool) {
    return new_set(name, is_bool);
}

Set new_set(string name) {
    return new_set(name, false, false);
}

I have three wrapper functions as this makes it easier to implement (I only want to write parameters if I have to!). This compiles fine, but I can not run. Crashes on a segmentation fault. Let me know if you need the entire code.
For now I am not needing to store data in the Set.value or Set.condition fields. I just want to initialise them all with a name the booleans.

A: The problem is in the second function:
Set new_set(string name, const bool is_bool) {
    return new_set(name, is_bool);
}

There's an endless recursion here. I guess you meant return new_set(name, is_bool, false); or return new_set(name, is_bool, true);.
By the way, your three functions can be simplified into one as follow (as @SirGuy mentioned):
Set new_set(string name, const bool is_bool = false, const bool is_condition = false) {
    Set set;
    set.name = name;
    set.is_bool_val = is_bool;
    set.is_condition = is_condition;
    return set;
}


text:
Q: Рейтинг игроков через google play plugin - Unity3d Здравствуйте, при добавлении рейтинга в игру, столкнулся с проблемой, которая вроде и подгружает google play после чего не открывает таблицу рейтинга. Вот что выдает logcat:
 E/TokenRequestor: You have wrong OAuth2 related configurations, please check. Detailed error: UNREGISTERED_ON_API_CONSOLE.
Добавлял все как по документации гугл сервисов, но все равно наткнулся на эту проблему. В консоли все создано правильно и приложение привязано к гугл сервисам.
Если у кого была такая проблема, как можно ее решить?
Версия Unity 5.6.4p2

A: Эта ошибка - несоответствие сертификатов приложения и сертификата, которым вы подписываете сборку. Вероятнее всего, ваше приложение вообще не подписано.
Вот вам тема на сайте Unity с ответом от официального представителя компании.
Если к сути, то алгоритм следующий:
1) Зайдите в Publishing Settings в PlayerSettings
2) Выберете "Create a new keystore", а затем нажмите "Browse Keystore". Введите название и сохраните файл, следом впишите пароль в поля password и confirm the password
3) В выпадающем списке Key -> Alias выберете "Create a new key"
4) В новом, открывшемся окне введите необходимую информацию.
5) Выберете созданный ключ.
6) Соберите ваше приложение. Теперь оно подписано.
Важно помнить, что Unity не запоминает пароль от вашего Keystore, поэтому его придётся помнить самостоятельно
Если не ошибаюсь, этот же сертификат теперь нужно загрузить на странице разработчика.
Видеоролик с описанными выше действиями


text:
Q: Getting rid of period and comma I am using apa.bst and want to know how to:
1) Get rid of the period after the year; and
2) Get rid of the comma after the journal title.
I currently have:
Baba, SA (1997). Democracies and inefficiency. Economics and Politics, 9(2):99–114.
I need it to be:
Baba, SA (1997) Democracies and inefficiency. Economics and Politics 9(2):99–114.

A: You can use biblatex and more specifically biblatex-apa, as it is easy to customise. Here is an example where you'll find the lines of code to add to your preamble. Note that the syntax to produce a bibliography is somewhat different with biblatex:
\documentclass[12pt,american, a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\usepackage{babel}
\usepackage{csquotes}

    \usepackage[style=apa, backend=biber]{biblatex}
\DeclareLanguageMapping{american}{american-apa}

\begin{filecontents}{ashortone.bib}
@article{DroitVolet2007,
 author = {Droit-Volet, S. and Meck, W. H.},
 year = {2007},
 title = {{H}ow emotions colour our perception of time},
 pages = {504--513},
 volume = {11},
 number = {12},
 journal = {Trends in Cognitive Sciences}
}
\end{filecontents}

%%% add the following lines to your preamble

\renewcommand{\labelnamepunct}{\addspace}
\renewcommand{\bibpagespunct}{\addcolon\space}

\usepackage{xpatch}
\xpatchbibmacro{journal+issuetitle}{%
  \usebibmacro{journal}%
  \setunit*{\addcomma\addspace}%
}
{%
  \usebibmacro{journal}%
  \setunit*{\addspace}%
}{}{}

    \addbibresource{ashortone.bib}

    \begin{document}
\nocite{*}

    \printbibliography

    \end{document}


text:
Q: CW-Complexes Clarification: Finite Verses Infinite Cells in each Dimension Question: Consider the following construction: take any uncountable set of elements and form a chain ($x < y < z <\dots$ ) of the elements (in particular, I think one can well-order the reals using the AoC, and then take this ordering) and now consider these elements to be 0-cells.  Now attach a 1-cell between two 0-cells $x, y$ if there is no $z$ between $x$ and $y$.  [Intuitively, this kind of looks like a "really long" real line.]  The claim is that this is not a CW-complex.  But why?
Motivation:  On a final, I was asked a question which sparked my interest in this finite vs infinite distinction in CW complexes.  In particular, I thought that this "long line" construction, though somewhat artificial, should qualify as a "nice space" since it is contractible.  When I asked about it, I was told that this was not a CW complex because the topology restricts us to putting a finite number of cells in each dimension.  I'm not quite sure why this is true.
Can anyone shed some light on this for me?

A: To elaborate on Chris Eagle's point, if you really only add edges between elements $x$ and their immediate successors $S(x)$, then the resulting space is not connected. For example consider the well-ordered set $\{1,2\}\times \mathbb Z_+$ in the dictionary order. Then your construction fills in the edges in the two vertical copies of $\mathbb Z_+$ giving you a disjoint union of two copies of $[0,+\infty)$. Things are even worse when you look at an uncountable well-ordered set, since you will have uncountably many points with no immediate predecessor.
On the other hand, if you glue together all of the copies of $[0,+\infty)$ you get the "long line," which is not a CW complex. In each case, the underlying set is the same, but the CW topology is different.
In general, CW complexes are allowed to have infinitely many cells in each dimension. The topology is given by the so-called weak topology. A subset is open if and only if its intersection with each cell is open in that cell.


text:
Q: Shared Hashref of hashes possible? Im trying to use a hashref of hashes to store a persistant field and a timestamp of when that field was changed.
It needs to be shared though as I have 2 threads that are required to access it although only one sets the values.
here is my current code with several commented out variations:
my $status = {};
share($status);
sub get_status {
    my($raid) = @_;
    return $status->{$raid}->{status} if exists $status->{$raid};
    return 1;
}
sub set_status {
    my($raid,$newstatus) = @_;
    my %t;
    $t{status} = $newstatus;
    $t{timestamp} = Time::HiRes::time;
    $status->{$raid} = \%t;
    #$status->{$raid} = {
        #status => $newstatus,
        #timestamp => Time::HiRes::time()
    #};
    #$status->{$raid}->{status}=$newstatus;
    #$status->{$raid}->{timestamp} = Time::HiRes::time;
    return 1;
}
set_status('680','1');
get_status('680');

I continually get Invalid value for shared scalar at ./hashtest line 19.
Could anyone help please :D?

A: This perlmonks page should explain the problem. One of the posts claims:

You can share nested hash, as long as the internal hashes are also marked as shared.

You can try something like this:
share( %t );
$status->{ $raid } = \%t;


text:
Q: VHDL extract constant from entity My VHDL designs usually contain a decent level of hierarchical "blocks" (entities): a sub-block is made up of multiple sub-blocks that's made up of multiple sub-blocks, etc.
It's very common for me to have to latency match the outputs of internal-blocks before driving the outputs of a given block. When I change the internal blocks and they end up with different latencies, I have to manually re-calculate how to compensate the neighboring block's latencies. If the update affects the given block's overall latency, I then have to repeat the process in any higher level block containing the given block.
It would be much simpler if a block could "tell" the calling entity what its latency is and have these compensations calculated automatically.
Is there a nifty way to do this? Something like a generic-output?

A: The right and general solution is to make a package for each sub-module, like mdl_sub_pkg, with a constant of the latency in that sub-module.  Then make a package for the enclosing module, like mdl_pkg, and use the constant from the mdl_sub_pkg package to calculate the latency that the enclosing module should generate.  Finally use the mdl_pkg in the enclosing module, and generate the latency based on the calculated constant in the mdl_pkg.  Remember to include test of the latency constants in the verification.
An alternative and dubious solution is to make an output port (as alternative to the non-existing output generic) on the sub-module and assign this with a constant that matches the latency in the sub-module.  The enclosing modules may then use the output port from the sub-modules to calculate the resulting latency for that module.  However, whether this solution works and generates minimum size synthesized design depends heavily on how the latency compensation is implemented, and on how the synthesis tool handles elaboration and reduction of design parts containing constants.  In certain situations it may be a workable solution and a nice trick, but it is not a general applicable solution.

A: Another alternative is to pass in your expected(or desired) latency as a generic.
Internally, assert actual latency = generic latency and fail if wrong.
Or insert pipe stages if actual latency < generic latency until they match, and assert/fail if actual latency > generic latency, and do nothing if they are equal. This gives an easy way of synchronising pipelines from the top level.


text:
Q: Dismissing Reminders - Runtime error '-2147024809 (80070057)' I have a VBA macro for Outlook 2016 that enables or disables an email rule when a named appointment reminder fires.
The auto-enable and auto-disable parts are working, but I want to auto-dismiss the reminder afterwards.
I get

Runtime error '-2147024809 (80070057)'

with olRemind(i).Dismiss highlighted.
I am pretty sure it is throwing an error because the reminder hasn't shown up in the list of reminders yet. However, when I check ?olRemind(i) in the Immediate window it does return the correct caption (Enable TEST). It seems like the reminder both does and does not exist?
When I halt code execution, the reminder pops up and the email rule is auto-enabled (or disabled), so I know the rest of the code is working.
My hypothesis is that I need to refresh either the list of Reminder objects or the application itself (something similar to Excel's Application.ScreenUpdating). I called DoEvents to try and accomplish this but it didn't fix the problem. I couldn't find another method or property that does this in Outlook.
Public WithEvents olRemind As Outlook.Reminders

Private Sub Application_Reminder(ByVal Item As Object)

    Set olRemind = Outlook.Reminders

    Dim i As Integer

    If Item.MessageClass <> "IPM.Appointment" Then
        Exit Sub
    End If

    If Item.Subject = "Enable TEST" Then
        Call OnOffRunRule("TEST", True, False)
        DoEvents
        'Wait 5 seconds
        Wait (5)
        'Dismiss reminder
        For i = olRemind.Count To 1 Step -1
            If olRemind(i).Caption = "Enable TEST" Then
'***THE FOLLOWING LINE CAUSES A RUNTIME ERROR***
                olRemind(i).Dismiss
            End If
        Next
    End If

    If Item.Subject = "Disable TEST" Then
        Call OnOffRunRule("TEST", False, False)
        DoEvents
        'Wait 5 seconds
        Wait (5)
        'Dismiss reminder
'***THE FOLLOWING LINE CAUSES A RUNTIME ERROR***
        Application.Reminders("Disable TEST").Dismiss
    End If
End Sub 'Application_Reminder

'Enable or disable a rule
Sub OnOffRunRule(RuleName As String, Enable As Boolean, Optional blnExecute As Boolean = True)
    Dim olRules As Outlook.Rules
    Dim olRule As Outlook.Rule
    Dim intCount As Integer

    Set olRules = Application.Session.DefaultStore.GetRules
    Set olRule = olRules.Item(RuleName)

    If Enable Then olRule.Enabled = True Else olRule.Enabled = False

    If blnExecute Then olRule.Execute ShowProgress:=True
        olRules.Save

    Set olRules = Nothing
    Set olRule = Nothing
End Sub 'OnOffRunRule

I tried two different methods for dismissing the reminder (see the two comments under "Enable TEST" vs. "Disable TEST"). Both triggered the same runtime error.
Ignore the Wait (5) call, that just loops DoEvents until 5 seconds from the current time.

A: The error is MAPI_E_INVALID_PARAMETER. Try to set Item.ReminderSet = false instead of calling Reminder.Dismiss.
You will probably be better off using Reminders.BeforeReminderShow event (where Reminders comes from Application.Reminders) - you can set the Cancel parameter passed to your event handler to true.


text:
Q: Value of type 'UICollectionViewCell' has no member 'imageView' I'm setting up a new project with a UICollectionView that displays an image. I created the ViewController and the CellViewController, just like its supposed to.
In the CellViewController the code is the following:
import UIKit

class ClubCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var imageView: UIImageView!
}

But in the ViewController when I'm setting up the image it gives me the error. Here's the code:
 override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
                                                      for: indexPath)
    // Configure the cell
    cell.backgroundColor = UIColor.black
    cell.imageView.image = UIImage(named: "pic1")
    return cell;
}

Thanks in advance..

A: You should cast your collectionViewCell subclass as your custom one ClubCollectionViewCell.
Use guard to check for the type of the cell, do fatalError() if it fails.
 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
                                                            for: indexPath) as? ClubCollectionViewCell else {
                                                                    fatalError("Wrong cell class dequeued")
    }
        // Configure the cell
        cell.backgroundColor = UIColor.black
        cell.imageView.image = UIImage(named: "pic1")
        return cell
 }


text: Q: motivation of group actions I don't understand what's the motivation to define group actions, from what I can understand we associate a group with a set, but that doesn't tell me much. Can I have an example that shows how useful group action is?  Can the set be a lie group ?


text:
Q: Asignar nuevo valor dentro de un vector de objetos Tengo un vector vropa al que quiero aplicar un método según la categoría, por ejemplo, aplicar descuento a todos los objetos cuya categoría sea Pantalón, el problema que tengo es que al recorrer el vector me pregunta el porcentaje a aplicar a cada instancia y lo que quiero yo es que el descuento se aplique a todos los productos cuya categoría coincida  a la indicada por consola:
 public cdouble getPrecioDescuento() {
     Scanner teclado = new Scanner (System.in);
     double descuento;
     System.out.print("Ingrese el porcentaje de descuento: ");
     descuento = Double.parseDouble(teclado.nextLine());

     return this.precio * (descuento / 100);

 }
    //*****************METODO DESCUENTO*************************

 public void descuentoCategoria () {

     Scanner teclado = new Scanner(System.in);
     String categoria;

     System.out.print("Ingrese la categoría para descuento: ");
     categoria = teclado.nextLine();

     for (int i = 0; i < vropa.size(); i++) {

         if(vropa.elementAt(i).getCategoria().compareTo(categoria) == 0) {
             vropa.elementAt(i).Setprecio(vropa.elementAt(i).getPrecioDescuento());
         }
     }
 }

A: Puedes preguntar por la categoría en cuestión, si la categoría es la que quieres, en vez de hacer esto:
if(vropa.elementAt(i).getCategoria().compareTo(categoria) == 0) {
    vropa.elementAt(i).Setprecio(vropa.elementAt(i).getPrecioDescuento());

Puedes recoger el descuento en una variable para después recorrer tu vector vropa y aplicarle el descuento a cada elemento:
if(vropa.elementAt(i).getCategoria().compareTo(categoria) == 0) {
    double descuento = getPrecioDescuento();
}

for (int i = 0; i < vropa.size(); i++) {
    vropa.elementAt(i).Setprecio(descuento);
}


text:
Q: Postgresql insert table data into another table I've got a database with a table containing different calendars (table events). Now I created a new table (events_backup) and imported all entries from table events from an older backup.
Now I want to insert in the event table all entries for a specific calendar (query calendar_id = 'foo') from events_backup but only if the don't exists.
How can I do that?

A: insert into DESTINATION_TABLE
select WANTED_COLUMNS
where not exists
     (select true
          from SOURCE_TABLE
          where query calendar_id = 'foo');

A: Maybe I'm missing something, but is sounds as if you are just looking for:
insert into event (pk_column, e1.calendar_id, ...)
select e1.pk_column, e1.calendar_id, ...
from event e1
where e1.calendar_id = 'foo'
  and not exists (select 1
                  from event e2
                  where e2.pk_column = e1.pk_column);

The above assumes that there is a column named pk_column in the event table that is a primary or unique key.
Another alternative starting with Postgres 9.5 is to use the on conflict clause to ignore all inserts that would fail due to a unique constraint violation:
insert into event (pk_column, e1.calendar_id, ...)
select e1.pk_column, e1.calendar_id, ...
from event e1
on conflict do nothing;


text:
Q: Using SSH authentication with JGit to Access a Git Repository Securely / Auth fail I'm using JGit in scala to access a remote Git repo, and I need to use SSH for authentication. JGit uses JSch to provide secure access.
I followed this tutorial : http://www.codeaffine.com/2014/12/09/jgit-authentication/
However, i have always, an  ,com.jcraft.jsch.JSchException: Auth fail
my method is:
def sshCloneRemoteRepository() = {

// 1 / Override SSH configuration with JschConfigSessionFactory
val sshSessionFactory: SshSessionFactory  = new JschConfigSessionFactory() {

  override protected def createDefaultJSch(fs: FS): JSch = {
    val defaultJSch = super.createDefaultJSch(fs)
    defaultJSch.removeAllIdentity()
    defaultJSch.addIdentity(new File("/home/xw/.ssh/id_rsa").getAbsolutePath)
    defaultJSch.setKnownHosts("/home/xw/.ssh/known_hosts")
    val configRepository:ConfigRepository = com.jcraft.jsch.OpenSSHConfig.parseFile("/home/xw/.ssh/config")
    defaultJSch.setConfigRepository(configRepository)
    defaultJSch
  }

  override protected def configure(host:OpenSshConfig.Host, session:Session ) {
    // This still checks existing host keys and will disable "unsafe" authentication mechanisms
    // if the hostkey doesn't match.
    session.setConfig("StrictHostKeyChecking", "no")
  }
}

// 2 / Preparing cloneCommand
val cloneCommand: CloneCommand = Git.cloneRepository()
cloneCommand.setURI(sshOriginRepositoryPath)
cloneCommand.setDirectory(localRepository)
cloneCommand.setRemote(originBranch)
cloneCommand.setTransportConfigCallback( new TransportConfigCallback() {
  override def configure(transport:Transport ) {
    val sshTransport:SshTransport = transport match {
      case t:SshTransport => t
      case _ => throw new ClassCastException("Variable of type Transport cannot be cast to the SshTransport")
    }
    sshTransport.setSshSessionFactory(sshSessionFactory)
  }

})

but I have always, this exception:
org.eclipse.jgit.api.errors.TransportException: ssh://git@vod.canal-bis.com:22/edt/json-edito.git: Auth fail
    at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:139) ~[org.eclipse.jgit-3.7.0.201502260915-r.jar:3.7.0.201502260915-r]
    at org.eclipse.jgit.api.CloneCommand.fetch(CloneCommand.java:193) ~[org.eclipse.jgit-3.7.0.201502260915-r.jar:3.7.0.201502260915-r]
    at org.eclipse.jgit.api.CloneCommand.call(CloneCommand.java:133) ~[org.eclipse.jgit-3.7.0.201502260915-r.jar:3.7.0.201502260915-r]
    at fr.canal.face.services.TGitServicee$class.sshCloneRemoteRepository(GitServicee.scala:109) ~[classes/:na]
    at fr.canal.face.services.GitServicee$.sshCloneRemoteRepository(GitServicee.scala:22) [classes/:na]
    at fr.canal.face.biz.actors.EditoPullerActor.cloneOrPull(EditoPullerActor.scala:50) [classes/:na]
    at fr.canal.face.biz.actors.EditoPullerActor$$anonfun$receive$1.applyOrElse(EditoPullerActor.scala:34) [classes/:na]
    at akka.actor.Actor$class.aroundReceive(Actor.scala:465) [akka-actor_2.11-2.3.6.jar:na]
    at fr.canal.face.biz.actors.EditoPullerActor.aroundReceive(EditoPullerActor.scala:22) [classes/:na]
    at akka.actor.ActorCell.receiveMessage(ActorCell.scala:516) [akka-actor_2.11-2.3.6.jar:na]
    at akka.actor.ActorCell.invoke(ActorCell.scala:487) [akka-actor_2.11-2.3.6.jar:na]
    at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:238) [akka-actor_2.11-2.3.6.jar:na]
    at akka.dispatch.Mailbox.run(Mailbox.scala:220) [akka-actor_2.11-2.3.6.jar:na]
    at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:393) [akka-actor_2.11-2.3.6.jar:na]
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260) [scala-library-2.11.2.jar:na]
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339) [scala-library-2.11.2.jar:na]
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979) [scala-library-2.11.2.jar:na]
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107) [scala-library-2.11.2.jar:na]
Caused by: org.eclipse.jgit.errors.TransportException: ssh://git@vod.canal-bis.com:22/edt/json-edito.git: Auth fail
    at org.eclipse.jgit.transport.JschConfigSessionFactory.getSession(JschConfigSessionFactory.java:159) ~[org.eclipse.jgit-3.7.0.201502260915-r.jar:3.7.0.201502260915-r]
    at org.eclipse.jgit.transport.SshTransport.getSession(SshTransport.java:136) ~[org.eclipse.jgit-3.7.0.201502260915-r.jar:3.7.0.201502260915-r]
    at org.eclipse.jgit.transport.TransportGitSsh$SshFetchConnection.<init>(TransportGitSsh.java:262) ~[org.eclipse.jgit-3.7.0.201502260915-r.jar:3.7.0.201502260915-r]
    at org.eclipse.jgit.transport.TransportGitSsh.openFetch(TransportGitSsh.java:161) ~[org.eclipse.jgit-3.7.0.201502260915-r.jar:3.7.0.201502260915-r]
    at org.eclipse.jgit.transport.FetchProcess.executeImp(FetchProcess.java:136) ~[org.eclipse.jgit-3.7.0.201502260915-r.jar:3.7.0.201502260915-r]
    at org.eclipse.jgit.transport.FetchProcess.execute(FetchProcess.java:122) ~[org.eclipse.jgit-3.7.0.201502260915-r.jar:3.7.0.201502260915-r]
    at org.eclipse.jgit.transport.Transport.fetch(Transport.java:1138) ~[org.eclipse.jgit-3.7.0.201502260915-r.jar:3.7.0.201502260915-r]
    at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:130) ~[org.eclipse.jgit-3.7.0.201502260915-r.jar:3.7.0.201502260915-r]
    ... 17 common frames omitted
Caused by: com.jcraft.jsch.JSchException: Auth fail
    at com.jcraft.jsch.Session.connect(Session.java:512) ~[jsch-0.1.50.jar:na]
    at org.eclipse.jgit.transport.JschConfigSessionFactory.getSession(JschConfigSessionFactory.java:116) ~[org.eclipse.jgit-3.7.0.201502260915-r.jar:3.7.0.201502260915-r]
    ... 24 common frames omitted

A: I Solved my problem, the code is fine, but the Auth fail problem is caused by my proxy configuration that i have in my .ssh/config file ( My machine => Amazon AWS Machine => Stach Git Server ) , So the code in this tutorial :
http://www.codeaffine.com/2014/12/09/jgit-authentication/
word fine, thanks Rudiger

A: try generated a new key use ssh-keygen -t rsa -m PEM for the default key

A: You can also do this
override protected def createDefaultJSch(fs: FS): JSch = {
....
session.setConfig("StrictHostKeyChecking", "no") //instead of configure()
....
defaultJSch
}

instead of configure function and this should work.


text:
Q: clearing port for errors I have an issue here, a blade has gone faulty a couple of days back. Now one of the servers (Unix) is having I/O errors. I've troubleshooted from Clariion end and everything is fine.
I need to clear the port stats for port 371(recommended by EMC), which actually is under the Index column.
In order to clear the port do I have to run the portstatsclear 12/35 (slot/port) which shows in the row where index 371 is and observer for 24 hours for any error?
Do I have to only look for CRC errors after clearing if error are increasing or something else?
The command I will be using is porterrshow.
And how do i know when were the errors cleared last?
Thanks!
Please guide me, I just want to make sure I am doing the right troubleshooting.

A: Per the Brocade helpfiles, portstatsclear will just clear the values returned with porterrshow and the stats-block returned with portshow. The fact an error count has been cleared does not appear to be logged anywhere.
There are a variety of things to keep an eye on in the stats. CRC errors are one such. CRC count should not increase at all, but even a slow increase over the course of a day is indicative of something not quite right. Could be media errors creeping in (most likely), or possibly buggy driver code on the device-side.


text:
Q: Time machine deletes old backups when still >2 TB of 3 TB are free I get messages that my Time Machine backup volume is full and TM has deleted older backups. But my backup target disk is an external 3 TB HD and Finder reports that over 2 TB of it are free (only some 820 MB used)!
I am backing up the internal 1 TB SSD (850 GB in use) of my Mac Book Pro Retina to that volume. I have also reformatted the backup volume and started all over with a new Time Machine backup to that fresh and empty target. But the effect reappears after 3 to 4 days.
All my trials to find similar reports on Google failed. It seems that other users have less than 25% free on their backup target when they run into this message. The only similar question I could find was this one but it was not answered.
I am currently running OS X Yosemite 10.10.1 and the backup HD is connected through USB 3.

A: Is it possible the snapshots being deleted are local snapshots (see http://support.apple.com/en-us/HT202301) and not on the external? Local snapshots start getting deleted when free space your internal volume (not the backup volume) drops below 20%.


text:
Q: Navigation Drawer update listView and avoid crash Anyone can tell me why the Drawer Layout crashes when pressing the menu button ?
my main question is about updateing the listView? Could i just add strings and putt them under the listView or should the menu be changed to a framelayout and add buttons on it ?
hope my english isn't to bad!
EDIT
i now have problem with PlanetFragments
/** Swaps fragments in the main content view */
    private void selectItem(int position) {
        // Create a new fragment and specify the planet to show based on position
        Fragment fragment = new PlanetFragment();
        Bundle args = new Bundle();
        args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
        fragment.setArguments(args);

        // Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.content_frame, fragment)
                .commit();

        // Highlight the selected item, update the title, and close the drawer
        mDrawerList.setItemChecked(position, true);
        setTitle(mPlanetTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }

PlanetFragment cannot be resolved
andthe first problem with crashing is from here
/** Called when a drawer has settled in a completely open state. */
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            getActionBar().setTitle(mDrawerTitle);
        }

A: Use getSupportActionBar():
getSupportActionBar().setTitle(mDrawerTitle);


text:
Q: JSON response via http not working in Angular Currently working on Angular. I am trying to get the data from JSON file and I am showing the result in Ul format. When I searched in Stack Overflow, I found this link. I am trying to do the same but still I am not solving it.
This is what I am trying here in the controller:
'use strict';
 var app = angular.module('myApp', []);

 app.controller('MyController', function($scope, $http){
   $http.get('sample.json').then(function (response){
    $scope.items = response.data.countries;
   });
 });

HTML code:

Here is my plunker. What am I doing wrong here?

A: One other problem: your JSON is incorrect:
{
  "countries": {
    "State": [
      "TamilNadu"
    ],
    "State": [  <-- Error: duplicate key!
        "Karnataka"
    ]
  }
}

Here is an alternative:
{
  "countries": [
    { "USA": [
      {"State": "California"},
      {"State": "Nevada"} ]},
    { "India": [
      {"State": "TamilNadu"},
      {"State": "Karnataka"} ]}
] }

A: There are three issues,
(i)You do not need to declare the module twice , once in script.js and other one
in controller.js.
(ii) You were refering to angular 2.0 version ,and coded using angular 1.4 version.
(iii)If you want to show all states from json, it should not have a duplicate key, which you could see from the plunker itself

{   "countries": {
      "State": [
        "TamilNadu"
      ],
      "State": [  <-- Error: duplicate key!
          "Karnataka"
      ]   } }

Here is the working Application


text:
Q: Git merge using Github Desktop - Changes not getting merged I have a branch development1 branched from master and development2 branched from development1. I wanted all changes I made in development2 in development1 and when I tried merging development2 to development1 branch, I am not able to get the changes which I already have in development1 branch but I have only the changes made in development2 branch. The files already in development1 are overwritten by development2 branch. I use Github Desktop for merging. Can someone tell me what is wrong here and how to solve this? I've already spent a full day trying to sort this issue.

A: Have you tried doing a pull request from branch 2 to branch1? Upload your changes to remote, and then from the web do the pull request.


text:
Q: How do I install mdbook using Cargo inside a Docker container? I am trying to build a Docker container that includes Rust and mdbook. I have tried a number of variations on
FROM rust:latest
RUN cargo install mdbook

including specifying the exact versions. For example, these don't work work either
RUN cargo install --git https://github.com/rust-lang-nursery/mdBook.git mdbook

and
RUN cargo install mdbook --vers "^0.1.0"

Things fail when the install gets to compiling lazycell v1.2.0:
Compiling lazycell v1.2.0
error: `<core::cell::UnsafeCell<T>>::new` is not yet stable as a const fn
   --> /usr/local/cargo/registry/src/github.com-1ecc6299db9ec823/lazycell-1.2.0/src/lib.rs:233:16
    |
233 |         inner: UnsafeCell::new(None),
    |                ^^^^^^^^^^^^^^^^^^^^^
    |
    = help: in Nightly builds, add `#![feature(const_unsafe_cell_new)]` to the crate attributes to enable

A: Instead of using the Rust container from Docker, you can build your own. The version of Rust is still 1.30 (as with FROM rust:latest), but for some reason this procedure gets all the dependencies right.
FROM ubuntu:latest
FROM gcc:latest

RUN apt-get update && \
    apt-get install -y curl

WORKDIR /tmp

RUN curl https://sh.rustup.rs -sSf > rustup.sh
RUN chmod 755 rustup.sh
RUN ./rustup.sh -y
RUN rm /tmp/rustup.sh

RUN ~/.cargo/bin/cargo install mdbook


text:
Q: TableCell/TableRow Margin programmatically This has to be something super simple but it is driving me insane.  I have a Table that is created programmatically.  The Table has multiple rows and I want to control the spacing between each row.  I figured that changing the Paragraph Margin would do the trick but the Cell still has a margin. This is what I am doing;
Table tb = new Table();
tb.Columns.Add(new TableColumn());
tb.RowGroups.Add(new TableRowGroup());
TableRow tr = new TableRow();
Paragraph p1 = new Paragraph(new Run("A"));
p1.Margin = new Thickness(0);
tr.Cells.Add(new TableCell(p1));
tb.RowGroups[0].Rows.Add(tr);
tr = new TableRow();
p1 = new Paragraph(new Run("A"));
p1.Margin = new Thickness(0);
tr.Cells.Add(new TableCell(p1));
tb.RowGroups[0].Rows.Add(tr);
flowDoc.Blocks.Add(tb);

I tried to create a TableCell object and set the Padding = new Thickness(0); but this did not have any effect.
Note: I can be hard to see the extra space. If you add two Paragraph with a Margin of 0 you will see in fact there is space difference;
p1 = new Paragraph(new Run("B"));
p1.Margin = new Thickness(0);
flowDoc.Blocks.Add(p1);
p1 = new Paragraph(new Run("B"));
p1.Margin = new Thickness(0);
flowDoc.Blocks.Add(p1);

edit: it was suggested it was an issue with different sizes in the numbers verse letters.  So I changed the both examples to be letters to show the same thing occurs.
edit 2: reply to Ed Plunkett:  Your XMAL example does me no good as this needs to be programmatically created.  However, I did take your idea and does make it much clearer that the cell or the row is adding a space.  I added a red to the first Paragraph than gold to the second;

A: I bet it's a simple fix:
Table tb = new Table() { CellSpacing = 0 };

And here's my reasoning. It looks like Table.CellSpacing defaults to 2:
<Grid>
    <Grid.RenderTransform>
        <ScaleTransform ScaleX="2" ScaleY="2" />
    </Grid.RenderTransform>
    <FlowDocumentScrollViewer>
        <FlowDocument>
            <FlowDocument.Blocks>
                <Table x:Name="MyTable">
                    <Table.Columns>
                        <TableColumn />
                    </Table.Columns>
                    <Table.RowGroups>
                        <TableRowGroup>
                            <TableRow>
                                <TableCell Background="Pink">
                                    <Paragraph Background="LightBlue">
                                        <Run Background="PaleGoldenrod">0123456789Aj</Run>
                                    </Paragraph>
                                </TableCell>
                            </TableRow>
                            <TableRow>
                                <TableCell Background="Pink">
                                    <Paragraph Background="LightBlue">
                                        <Run Background="PaleGoldenrod">0123456789Aj</Run>
                                    </Paragraph>
                                </TableCell>
                            </TableRow>
                        </TableRowGroup>
                    </Table.RowGroups>
                </Table>
                <Paragraph Background="LightSkyBlue" Margin="0">
                    <Run>0123456789Aj</Run>
                </Paragraph>
                <Paragraph Background="LightSkyBlue" Margin="0">
                    <Run>0123456789Aj</Run>
                </Paragraph>
            </FlowDocument.Blocks>
        </FlowDocument>
    </FlowDocumentScrollViewer>
    <Label Content="{Binding CellSpacing, ElementName=MyTable}" />
</Grid>

So if I set it to zero in XAML...
<Table x:Name="MyTable" CellSpacing="0">


text:
Q: Conjugacy classes of unipotent $\mathbb{Z}\times\mathbb{Z}$ in $GL_3(\mathbb{Q})$ Let $G=\mathrm{GL}_3(\mathbb{Q})$.  Now, consider all subgroups in $G$ of the form $\mathbb{Z}\times\mathbb{Z}$ consisting only of unipotent elements (elements whose eigenvalues are all $1$).  How many $G$-conjugacy classes of such subgroups are there?  Does each conjugacy class have a representative that can be generated by commuting elements $A,B\in\mathrm{GL}_3(\mathbb{Z})$?
So far, I've found three conjugacy classes of such subgroups, with representatives given as follows:
$$\left\langle\begin{pmatrix}1&1&0\\0&1&0\\0&0&1\end{pmatrix},\begin{pmatrix}1&0&1\\0&1&0\\0&0&1\end{pmatrix}\right\rangle\\[.4in]\left\langle\begin{pmatrix}1&0&0\\0&1&1\\0&0&1\end{pmatrix},\begin{pmatrix}1&0&1\\0&1&0\\0&0&1\end{pmatrix}\right\rangle\\[.4in]\left\langle\begin{pmatrix}1&1&0\\0&1&1\\0&0&1\end{pmatrix},\begin{pmatrix}1&0&1\\0&1&0\\0&0&1\end{pmatrix}\right\rangle\\$$
Is this a complete list, or are there more?  It would be nice to find a solution that can be generalized to $\mathrm{GL}_n(\mathbb{Q})$ for larger $n$, although I'd even be happy with something that works for $n=4$.


text:
Q: RStata Set Stata Binary Path I am trying to use RStata in order to run Stata from R. I first did:
options("RStata.StataVersion" = 14)

That didn't cause an error.
But I also need to set the binary path. I have a Mac, and Stata is contained in a folder in the Applications folder. Here is what I have tried:
options("RStata.StataPath" = "/Applications/Stata/Stata")

Unfortunately, this causes an error. What should I do?

A: With no knowledge of RStata, I can say that on macOS 10.12.6 with Stata/SE release 15 installed, in the terminal window
open /Applications/Stata/StataSE.app

is what's required to launch Stata. It is possible that in looking for the Stata executable, your Finder Preferences does not have "show all filename extensions" set in the Advaced pane, so you weren't shown the .app extension.

A: From the README, better rendered here

Mac users are a notable group: at this stage they should set the path
  for the command line executable (not the GUI app). Eg for a Stata13 SE
  installation in El Capitain (with default options) the path is
  '/Applications/Stata/StataSE.app/Contents/MacOS/stata-se'. In other
  cases (Stata licenses, installation path and so on) the path could be
  slightly different (BTW, i've found the path 'exploring' the
  filesystem with a terminal, not the graphics explorer since it 'stops'
  at 'StataSE.app').

(yes, putting something in the manual as well is in my TODO :) )
hth, best, Luca


text:
Q: Convergence of a subsequence of a subsequence of distribution functions I'm trying to find a solution for the following problem:
Let $(\mu_n)_{n\in\mathbb{N}}$ be a sequence of signed (Baire)-measures (of bounded variation) on $[a,b]$ and let $F_{\mu_n}(t):=\mu_n([a,t))$ be the corresponding general distribution functions. By assumption there is a subsequence of a subsequence of $(F_{\mu_n}(t))_{n\in\mathbb{N}}$, denoted (ugly) by $(F_{\mu_{n_{k_l}}}(t))_{l\in\mathbb{N}}$, that converges to a distribution function $F_\mu(t)$ at all points with the exception of points of an at most countable set.
Further, by assumption, the sequence $(\mu_n)_{n\in\mathbb{N}}$ does not converge weakly to $\mu$, but I can't imagine this information is even needed here.
Is it now true that for $f\in C^\infty([a,b])$
$$\lim_{l\to\infty}\int_{[a,b]}f'(t)F_{\mu_{n_{k_l}}}(t)\,dt=\int_{[a,b]}f'(t)\lim_{l\to\infty}(F_{\mu_{n_{k_l}}}(t))\,dt=
\int_{[a,b]}f'(t)F_\mu(t)\,dt$$
holds?
Should this integral seen as a Riemann-Integral? If so, I'm aware I can exchange the limit and the integral only in the case of uniform continuity, but due to Jegorow the $F_{\mu_{n_{k_l}}}(t)$ converge to $F_\mu(t)$ only uniform almost everywhere if I'm not mistaken.
If the integrals should be seen as Lebesgue-Integrals, then I don't think I can apply dominated convergence or monotone convergence, since I'm dealing only with a subsequence of a subsequence, or am I wrong?
Thank you all very much in advance for your help, this community is great!
Greetings,
Florian


text:
Q: Proper way to close a socket to avoid "connection reset by peer" I have a client/server app that maintains a socket continuously.  When the client signs off, it sends a 'signing off' message to the server and then closes the socket and cleans up.  The server cleans up and closes the socket when it receives this message - and does not reply to the message.
On a fairly regular basis, I see "connection reset by peer" errors getting logged by the server without any complaints from end users, and I figure this must be an occasional timing issue in my sign-off sequence.  I do see the same errors when end users complain about their connections actually being dropped, so I'm wondering how to tell the difference between those scenarios - or even better, how to prevent the bogus 'connection reset' scenario in the normal case.
I'm guessing that in some cases the server's getting hit by the closed socket before (or during) receipt of the "signing off" message.  Is this possible?  Is there a proper sequence you're supposed to follow for letting a server know that the client is about to terminate before actually closing the socket?  Some way to check that the last message was delivered prior to closing?
Thanks,
Rob

A: The shutdown(s, SHUT_RDWR) function should solve your problem.  There's a more complete explanation in this document.

A: This usually means that you have either written to a connection that had already been closed by the peer, or closed a connection without reading all the pending incoming data. In other words, an application protocol error.


text:
Q: UICollectionView cells disappearing when deleting items I have a UICollectionView that scrolls horizontally. Each item can be swiped upward to delete. This is done through a pan gesture that inserted on the UICollectionViewCell. The animation code is ad follows:
let translation = gesture.translation(in: contentView)

        if gesture.state == .changed {
            tabView.center.y += translation.y
            gesture.setTranslation(CGPoint.zero, in: contentView)
        } else if gesture.state == .ended {
            if tabView.center.y < contentView.center.y {
                UIView.animate(withDuration: 0.2, animations: {
                    self.tabView.frame.origin.y = -self.tabView.frame.size.height
                }) { (_) in
                    self.delegate?.didSwipeCell(at: self.indexPath())
                }
            }
        }

This is the collection view delegate conformance
func didSwipeCell(at indexPath: IndexPath?) {
       guard indexPath != nil else {
           return
       }

       self.tabs.remove(at: indexPath!.row)
       self.deleteItems(at: [indexPath!])
   }

This produces the following effect:

As you can see, I have 6 items in my collection view, however, when swiping away and deleting the first four items for example, the last 2 items disappear. I have not been able to figure out the reason of the disappearance of those items. Any help is appreciated. Thanks.

A: I solved this issue by overriding prepareForReuse() in the UICollectionViewCell and setting the frame origin back to (0,0)


text:
Q: After reopening app, UIToolbar superview takes up whole view I have a UIToolbar setup in a superview on the bottom of my UITableView that is part of a UINavigationController.
It works fine when I'm using the app; however, when I close (send to background multitask) the app and then reopen it, the UIToolbar superview takes up the whole UITableView (but not the Navigation Bar). Is there a way to call a setFrame when the app reloads? I tried to put an NSLog in viewWillAppear, but it doesn't get called when I switch back to the app on multitask bar.
Thanks,

A: Try using the
 - (void)applicationWillEnterForeground:(UIApplication *)application

or the
 - (void)applicationDidBecomeActive:(UIApplication *)application

methods in the app delegate to implement whatever code you like.


text:
Q: How is angular velocity related to angles of spherical pendulum In a simple pendulum angular velocity $ω$ is related to angle $θ$ as $$θ = wΔt$$ But what would be the relationship between the angular velocity and angles comprising a spherical pendulum described by angles $θ$ and $\phi$?

A:
So the $3\times 3$ Rotation Matrix R is a function of
$\varphi$ and $\theta$
With

Where equation (1) and (2) are the pendulum differential equation . With the solution of $\varphi(t)$ and $\theta(t)$ you can obtain the component of the angular velocity $\vec \omega$ equation (3).
Example


text:
Q: testing using Resque with Rspec examples? I am processing my background jobs using Resque.
My model looks like this
class SomeClass
  ...
  repo = Repo.find(params[:repo_id])
  Resque.enqueue(ReopCleaner, repo.id)
  ...
end

class RepoCleaner
  @queue = :repo_cleaner

  def self.perform(repo_id)
    puts "this must get printed in console"
    repo = Repo.find(repo_id)
    # some more action here
  end
end

Now to test in synchronously i have added
Resque.inline = Rails.env.test?

in my config/initializers/resque.rb file
This was supposed to call #perform method inline without queuing it into Redis and without any Resque callbacks as Rails.env.test? returns true in test environment.
But
"this must get printed in console"

is never printed while testing. and my tests are also failing.
Is there any configurations that i have missed.
Currently i am using
resque (1.17.1)
resque_spec (0.7.0)
resque_unit (0.4.0)

A: I personally test my workers different. I use RSpec and for example in my user model I test something like this:
it "enqueue FooWorker#create_user" do
  mock(Resque).enqueue(FooWorker, :create_user, user.id)
  user.create_on_foo
end

Then I have a file called spec/workers/foo_worker_spec.rb with following content:
require 'spec_helper'

describe FooWorker do

  describe "#perform" do
    it "redirects to passed action" do
      ...
      FooWorker.perform
      ...
    end
  end

end

Then your model/controller tests run faster and you don't have the dependency between model/controller and your worker in your tests. You also don't have to mock so much things in specs which don't have to do with the worker.
But if you wan't to do it like you mentioned, it worked for me some times ago. I put Resque.inline = true into my test environment config.

A: It looks like the question about logging never got answered. I ran into something similar to this and it was from not setting up the Resque logger. You can do something as simple as:
Resque.logger = Rails.logger

Or you can setup a separate log file by adding this to your /lib/tasks/resque.rake. When you run your worker it will write to /log/resque.log
Resque.before_fork = Proc.new {
ActiveRecord::Base.establish_connection

# Open the new separate log file
logfile = File.open(File.join(Rails.root, 'log', 'resque.log'), 'a')

# Activate file synchronization
logfile.sync = true

# Create a new buffered logger
Resque.logger = ActiveSupport::Logger.new(logfile)
Resque.logger.level = Logger::INFO
Resque.logger.info "Resque Logger Initialized!"
}

Mocking like daniel-spangenberg mentioned above ought to write to STDOUT unless your methods are in the "private" section of your class. That's tripped me up a couple times when writing rspec tests. ActionMailer requires it's own log setup too. I guess I've been expecting more convention than configuration. :)


text:
Q: Alter a view that refers to a non-readable secondary database I have a database (DB1) that is not readable because it is secondary in an AG group.
I have another database (DB2) that is not replicated with the AG group. It contains some views that reference the first database. I need to periodically alter some views.
The error is:

Msg 976, Level 14, State 1, Procedure vw_xxx, Line 4 [Batch Start Line
9] The target database, 'DB1', is participating in an availability
group and is currently not accessible for queries. Either data
movement is suspended or the availability replica is not enabled for
read access. To allow read-only access to this and other databases in
the availability group, enable read access to one or more secondary
availability replicas in the group.  For more information, see the
ALTER AVAILABILITY GROUP statement in SQL Server Books Online."

I do not have these options:

*

*Enable the readable secondary (lack of licenses)

*AG failover (this is a DR site)

*Add DB2 to the same AG (too large, I only want to replicate schema not data)

Are other options available?
I have 3 AG nodes. The DR is not readable because it lacks an active license to be readable. The ALTER VIEW occurs on DB2 at the DR site, referencing DB1 in that instance. I'm altering the views because I'm deploying changes with a dacpac in that DR site. I do not have licences to cover that DR site in an active way.

A: Can you create a linked server on each AG node that references the AG listener?
You can then alter your view to query DB1 via the linked server using 4-part naming, instead of querying DB1 using 3-part naming. Then you shouldn't encounter this error as the linked server will redirect to the AG primary.


text:
Q: iPhone: Settings > Safari > Databases no longer visible All,
I'm trying to see the local storage databases on my iPhone.
A variety of Google searches made this clear - if you go to "Settings", then "Safari" - you'll see a "Database" panel (just under "Accept Cookies...")
However, on MY iPhone - "Databases" is not listed.
I'm 99.9% sure that I HAVE databases on my phone:

*

*I'm testing an HTML5 application that uses a database. According to the app, the database exists, and I can write to and read from it

*I use Gmail through Safari - I'm virtually certain that it uses a database

I'm also virtually certain that I recall seeing the "Database" options in the past.
I just upgraded to iOS 4.3.5 - is it possible that this version moved the function to view the databases to someplace besides Settings > Safari? If so, where?
Or, is it a bug that the databases aren't getting displayed?
Thanks in advance!

A: I was getting a little frustrated... I knew there were local safari databases on my phone, even though they weren't shown in the Settings > Safari panel.
So - as a last resort - I powered off my phone, and restarted. Sure enough, there they were, right where I expected them.


text:
Q: Cannot find RKJSONParserJSONKit.h I cannot import RKJSONParserJSONKit.h. I have followed the RESTKIT install tutorial RestKit Installation on Xcode 4.x and it is working very well, but I can't use JSONParser.
In the point the tutorial says Link Binary With Libraries in search dialog it can't find these libraries:
libRestKitNetwork.a
libRestKitObjectMapping.a
libRestKitSupport.a
libRestKitJSONParserJSONKit.a
libRestKitXMLParserLibxml.a

If someone can help me I apreciate it!

A: You need to link these libraries only if you are installing version 0.9.3. If you are installing the latest version, just ignore it and link libRestKit.a instead. Being not able to import RKJSONParserJSONKit.h is a different story. Do you try to import it like this?
#import <RestKit/RKJSONParserJSONKit.h>

This works for me in the latest version of RestKit.


text:
Q: Degree of freedom of prediction interval We are interested in examining the yield of tomato plants that have been grown with certain types of fertiliser. A study is conducted and the following data obtained:
enter image description here
We want to Find a 95% prediction interval for the yield of a tomato plant grown on fertiliser 1.
I not sure shall I take 1 or 5 for the degree of freedom of the prediction interval. Can someone explain for me please? Thanks very much!