text:
Q: How to match two arrays and change color where an element id matches another id in typescript I have two dynamically generated passion arrays from NodeJS MongoDB and socket.io server and I know the source may not be important but:
passions1:
[{_id: '60a1557f0b4f226732c4597b', name: 'Netflix'},
{_id: '60a1557f0b4f226732c45980', name: 'Music'},
{_id: '60a1557f0b4f226732c45991', name: 'Hiking'}]

passions2:
[{_id: '60a4457fr54646647888876d', name: 'Cooking'},
{_id: '60a1557f0b4f226732c4597b', name: 'Netflix'},
{_id: '60a1557f0b4f226732c45997', name: 'Swimming'}]

Using naked eyes one can tell that the object {_id: '60a1557f0b4f226732c4597b', name: 'Netflix'} exists on both arrays
How do you output or recreate a new array with the existing objects e.g Netflix in bold using angular?
My code:

{{passion.name}}

Any answer typescript / JavaScript would be of great help
Thanks in advance.

A: You can use the NgStyle directive for achieving this in the following way,
In your component.html file,

    {{passion.name}}

In your component.ts file,
define function getFontWeight that accepts a single parameter of type string as follows,
getFontWeight(passionName) {
    for (let i = 0; i < this.arrayOfPassions.length; i++) {
      if (passionName === this.arrayOfPassions[i]['name']) {
        return 'bold';
      }
    }
    return 'normal';
  }

StackBlitz Demo

A: It's better for Angular performance to not call methods from the template, explained here. In short, your template method is going to be re-run on every change detection.
In Angular, Pipes are pure, meaning they don't get re-run unless their inputs change. The pipe would be pretty simple:
import {
  Pipe,
  PipeTransform
} from '@angular/core';
interface PassionObj {
  _id: string;
  name: string;
}

@Pipe({
  name: 'boldCommonInterests'
})
export class BoldCommonInterestsPipe implements PipeTransform {
  transform(passion: string, passion2Arr: PassionObj[]): boolean {
    return passion2Arr.some(el => el.name === passion);
  }
}

And then the template would be:

  {{passion.name}}

Stackblitz here.


text:
Q: Texture is deformed when drawing to screen I'm trying to draw a HUD on the screen. I currently have it to display hearts depending on the Player's health. The images are transparent, and I have enabled
glEnable(GL_BLEND);
and
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
Code:
public void drawHUD() {
    for(int i = 1; i <= p.getHealth(); i++) {
        heart.bind();
        float y = 30;
        float x = 35 * i;
        glPushMatrix();
        glBegin(GL_QUADS);
            glTexCoord2f(0, 0);
            glVertex2f(x, y);
            glTexCoord2f(0, 1);
            glVertex2f(x + w.block_size, y);
            glTexCoord2f(1, 1);
            glVertex2f(x + w.block_size, y + w.block_size);
            glTexCoord2f(0, 1);
            glVertex2f(x, y + w.block_size);
        glEnd();
        glPopMatrix();
    }
}

Heart:

When its drawn:

(Texture is at 32x32)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Power D1 mini with 4 AA batteries I would like to power a Wemos D1 mini with AA batteries for a project.
I'm really new to the subject but as I understood the board runs with 3.3V.
You can power the board through the 5V pin because there is a built in dropout there.
To get 5V I thought of using 4 AA batteries (4 x 1.5 = 6V) and mount them with a resistor to lower the voltage to 5V.
What I don't understand is how the resistor is acting on the overall system.
Does it increase its lifetime or does it disperse all extra voltage into heat ?
In other words, if I use more batteries with bigger resistor, does my circuit gets longer lifetime  or should I stick to the required voltage ?
As I understood I could use 3 AA batteries (4.5V) it would work but I would opt for more lifetime if possible (Also I already bought boxes for 4 batteries ;) ).
Is there any best pattern to decrease voltage effectively ? (Diodes, ..., ?).
Thanks

A: A quick search shows me that the Wemos D1 Mini is an ESP-8266 dev board. According to the manufacturer's product summary (https://www.wemos.cc/en/latest/d1/d1_mini.html) and schematic (https://www.wemos.cc/en/latest/_static/files/sch_d1_mini_v3.0.0.pdf) it has an operating voltage of 3v3, as well as a 5v input that goes to a 3v3 LDO.
The LDO is an ME6211 (https://stm32-base.org/assets/pdf/regulators/ME6211.pdf) which has an absolute maximum input voltage of 6v5 and whose datasheet (pp. 12-14) indicates smooth and continuous regulation from an input voltage range of ~4-6v.
This means that you can tie four AA batteries directly to the 5v input pin and it will safely power your device over the usable lifetime of your cells. No resistor or other power dissipating component required – and if you were to add one, you would only be hurting your efficiency.

A: The Wemos D1 Mini(ESP8266 in general) will use lots of power to keep up with the Wifi. It may go from 80 to 120mA. It wont hurt your device if you use 4 AA battery and can be used direct in the 5V Pin as suggested(not in the 3V3 though).
However, if you are planing to have your project accessing wifi, you should consider implementing deep sleeping. Otherwise you will be changing the batteries every day or every other day. If you dont need the wifi, I would consider other Microcontroller.
That said, it is a good option if you have something that will wake up, do a quick task over wifi and go to sleep. But, I would not use AA batteries in a ESP8266 project if it requires to be on all the time. I would consider 18650 batteries and the charging circuitry to allow you to easily manage the power needs of your project


text:
Q: Busqueda y validacion de clientes en SQL Sever Actualmente estoy intentando buscar ciertos bancos en una tabla para saber si estan registrados, por ejemplo
BancoHN, BancoSA, BancoOcci y BancoPais
los unicos que tengo registrados son BancoHN y BancoPais
Entonces quiero un resultado que me diga, si el nombre BancoHN existe entonces que me muestre 2 columnas que me digan asi:
 NombreBanco                   EsCliente

  BancoHN                         Si
 BancoPais                        Si

Pero que tambiem me muestre las que no existen con la diferencia que en el campo "EsCliente" diga que no, asi:
 NombreBanco                   EsCliente

  BancoHN                         Si
 BancoPais                        Si
 BancoSA                          No
 BancoOcci                        No

El query que tengo hasta ahora es este:
SELECT
c.FullnameLocal,

FROM dbo.Clients c

WHERE  c.FullnameLocal IN ('BANCOHN','BANCOPAIS','BANCOSA','BANCOOCCI')
ORDER BY c.FullnameLocal

Estaba pensando en usar un IF EXIST para poder validar si el nombre existe entonces que diga que si es cliente, pero no se como hacer para que aunque no sea cliente siga colocando el nombre del banco y muestre el resultado como el cuadro de arriba que mostre

A: Lo que necesitas es tener una lista que pueda usarse como tabla para agregar a tu consulta. En el caso de SQL Server, lo puedes hacer con el constructor de tablas VALUES.
SELECT  b.NombreBanco,
        CASE WHEN c.FullnameLocal IS NULL
            THEN 'No'
            ELSE 'Sí' END AS EsCliente
FROM dbo.Clients c
RIGHT JOIN (VALUES('BANCOHN'),('BANCOPAIS'),('BANCOSA'),('BANCOOCCI'))b(NombreBanco) ON c.FullnameLocal = b.NombreBanco
ORDER BY c.FullnameLocal;

Sin embargo, esto solo es rentable si los valores son pocos. En caso de que sigan aumentando, lo ideal es ponerlos en una tabla real.

A: Existen muchas formas de calcular una expresión en función de unos datos. Personalmente la que más me gusta es Case, donde si la expresión a buscar es true entonces un resultado y si la expresión es false otro.
SELECT
    c.FullnameLocal,
    CASE WHEN c.FullnameLocal IN ('BANCOHN','BANCOPAIS')
        THEN 'Si'
        ELSE 'NO'
    END AS EsCliente
FROM dbo.Clients c

WHERE  c.FullnameLocal IN ('BANCOHN','BANCOPAIS','BANCOSA','BANCOOCCI')
ORDER BY c.FullnameLocal


text:
Q: Getting JSON input and pass it into a function in PHP I've got 4 classes responsive for:
1st - getting input as JSON string from url, decode it into an array and create 2 variables: $user_id, $user_text (like here below):
class Get_message{
    public $user_id, $user_text;

    public function get_input(){

        $input = json_decode(file_get_contents('myURL'), true);
        $user_id = $input['getting value from an array'];
        $user_text = $input['getting value from an array'];

        //how to return it?
        //return $input, $user_id, $user_text? it won't work I guess
    }
}

and there is my first question: how to return that 2 values so that I can use it in another classes?
2nd - check if that string contains keywords, if it contains a keyword I want to create another JSON,
so far I've got this:
class input_recognize{
const KEYWORD_HELP = 'help';
//...some more constants...
const KEYWORD_REPORT = 'report';

public function msg_recognize($user_text)
{
    switch ($user_text) {
        case self::KEYWORD_HELP:
            return new Output_msg(Output_msg::MESS_HELP);
        break;
        //... some more cases
        case self::KEYWORD_REPORT:
            return new Output_message(Output_msg::MESS_REPORT);
        break;
    }
}

}
3rd - based on that what case in class above was true create appropriate JSON, my code looks like:
class Output_message{

    const MESS_REPORT = 1;
    const MESS_HELP = 2;

    public function __construct($user_id, $user_text){
         //I guess I should use $this here, dunno how

        $json_output = array(
            "first_title" => array(
                "id" => $user_id
            ),
            "second_title" => array(
                "text" => "text to send"
            ),
        );
        $output = json_encode($json_ouput);
    }
}

4th - and I want to be able to take $output into that function and POST it to url.
I'm beginner in php, object oriented programming as well, I'll appreciate any help, and criticism. Thanks in advice.

A: *

*You can use the same class to do everything you have done, using methods. For those input variables declare them as public static and use your class constructor to set them. public static $userId;    self::$userId = .... and cal GetMesage::userId.

*Use strpos('help', $yourString), no need for constants here.

*I don't think you need to do that in a class constructor, if you do you can add more methods. Like you set you values in constructor new OutputMessage(GetMessage::$userId, GetMessage::$userText);

*use a method like sendOutput()  and post your data to url using curl.

I do not advice you to do it like you did, you can use only a class, and pass data form a method to another, you won't really need output or input, only the 2 url's. If you really want 4 classes then you can chain them, one class will return another.
This is just demonstrative, there are a loot of ways of achieving what you want, this is an example:
class Message{
    public static $userId;
    public static $userText;
    public static $messageType;

    public function __construct($inputUrl)
    {
        $this->getMessage($inputUrl);
        $this->parseMessage();
    }

    private function getMessage($inputUrl){

        $input = json_decode(file_get_contents($inputUrl), true);
        self::$userId = $input['id'];
        self::$userText = $input['text'];
    }

    private function parseMessage()
    {
        $messageText = self::$userText;
        switch (true) {
            case (strpos('help',$messageText) !== false):
                self::$messageType = "Help"; //or code, or whatever you want here
                break;
            //... some more cases
            case (strpos('report',$messageText) !== false):
                self::$messageType = "Report"; //or code, or whatever you want here
                break;
        }
    }

    public function sendResponse($outputUrl){

        $jsonOut = array(
            "first_title" => array(
                "id" => self::$userId
            ),
            "second_title" => array(
                "text" => "text to send"
            ),
        );
        $output = json_encode($jsonOut);

        $ch = curl_init($outputUrl);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $output);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($output))
        );
        return curl_exec($ch);
    }
}

$sendMessage = new Message('inputUrl');
$sendMessage->sendResponse('outputUrl');


text:
Q: Slicing Lists with Variable Based Index How can I slice a list with an index that is based off of a variable?
i.e.
splitMe = range(0,10)

startPlace = 3
endPlace = 5

splitMe[startPlace:endPlace] #<------This is essentially what I need

This way I can input different numbers into startPlace and endPlace and get a different slice. This probably seems trivial, but I am cutting sections out of 230,000 lines of data. There are calculations behind startPlace and endPlace that have to do with dates and times.
This is what I have now:
#Find matching data with datetime
for a, line in enumerate (Time):
    if line == startDate:
        print "Slice starts at:", a

for c, line in enumerate (Time):
    if line == endDate:
        print "Slice ends at:", c

#Create lists
slice_laser_c = [x for x in laser_C if a <= x < c]

EDIT
When I run this code, it prints "Slice starts at: 0" and "Slice ends at: 5" which is exactly what it"s supposed to do.
END EDIT
When I print slice_laser_c I get
[] #<----- Essentially, this is the problem

In a simple sense, this is what's going on:
big_list = range(0,10)
a = 2
c = 5

BetweenList = [x for x in big_list if a <= x < c]
print BetweenList

A: The problem appers to be that you are iterating right through all the Times without stopping when you find the values you want. Therefore at the end of both loops a and c are at their maximum value. Maybe you want to break the loop once you have found the value you want?

A: Why not use the splice syntax built into Python? (Maybe I'm not seeing something)
Like:
list = [1,2,3,4,5,6,7,8,9]
a=3
c=7
split_list = list[a:(c+1)] #<-----The +1 is because the splice syntax goes to end-1
print split_list


text:
Q: Visualize Moebius Transformations I want to visualize Moebius transformations, in particular the attractive and repulsive fixed points of a loxodromic Moebius transformation. I have had "some" success with ComplexListPlot, but when using Joined->True it all gets totally smudged up. And I'd rather see it with arrows, such as in StreamPlot or VectorPlot, ComplexVectorPlot, or ComplexStreamPlot.
Picking a specific example, 1/(2+w) is loxodromic and has an attractive and repulsive fixed point (there are up to two in a Moebius transformation, and exactly two for loxodromic). How can I visualize that for a grid of complex input?
Something like
https://en.wikipedia.org/wiki/M%C3%B6bius_transformation#Elliptic_transformations
https://en.wikipedia.org/wiki/M%C3%B6bius_transformation#Hyperbolic_transformations
I know the rules of this site require the o/p to show what he tried. All I can say is that ComplexListPlot in principle "works", but leaves a total mess. I have also tried computing derivatives, because StreamPlot and VectorPlot work on derivatives, but I couldn't find a way to generalize this enough, and the Moebius transformations have nothing to do with derivatives as such.
If I can't get arrows, that would be fine. But I definitely want lines that show the attractive and repulsive nature of loxodromic fixed points.

A: How about the following?
ComplexPlot[(z - I/2)/(1 + I/2*z), {z, -3 - 3 I, 3 + 3 I},
Mesh -> {Range[-5, 5], Range[-5, 5]},  MeshFunctions -> {Re[#2] &, Im[#2] &},
MeshStyle -> {White, Black}]

Addition. Here is a simple visualization of an attractive fixed point of a Moebius transform in the complex plane.
f[z_] := (z - I/2)/(1 + I/2*z)
ComplexListPlot[Table[Nest[f, -3, n], {n, 1, 20}]]

We see the iterated points of -3 tend to -I.
In order to produce the pictures in the "Iterating a transformation" section from the second link the TransformedRegion command may be applied.


text:
Q: Pinterest API and Rate Limiting I have a question about the Pinterest API and it's rate limiting. On Pinterest's Site it states:

Each app (with a unique app ID) is allowed 1000 calls per endpoint per hour for each unique user token. The 60-minute window is a sliding window based on when you make your first request. If you hit your rate limit, you'll only have to wait a max of 1 hour to get a few more requests.

I've never worked with Pinterest API, but based on what that says, I could authenticate a user and then that user is allowed up to 1000 calls to the API per 1 hour - correct?
I've gotten many requests from a community of users on Facebook to build a web based application utilizing the API. But in order for me to do so, I have to be able to balance the API calls some. So clarifications as to the rate limits for Pinterest would help.

A: I have develop an app with Pinterest and constantly maintaining that app.  As the doc says, for any giving app you should be able to make 1000 calls (per endpoint) (per hour).
Pinterest has many different endpoints so it you should be able to make 1000 calls for each different endpoint per hour, not just 1000 calls.
you can see the many different endpoints here Pinterest API Tool
For each distinct user you can, within 1 hour:

*

*make 1000 pins to endpoint > /v1/pins/

*make another 1000 calls to /v1/boards/ to create boards

*and yet another 1000 calls to /v1/me/following/boards// to unfollow up to 1000 followers

and so on...
Joy Breaker Follow:
At first my app works just as I described above, then out of the blue the app seems to be getting 1000 calls total for all endpoint.  And every time I contact their support, some I get an automated response that copy the exact text you reference in your question from the doc.  So I'm not sure if Pinterest understand their own doc or it's poor programming skills or bugs in their api
So brace for impact!

A: I wanted to provide an update to this question in relation to V3 of the Pinterest API.  According to the documentation here (https://developers.pinterest.com/docs/redoc/pinner_app/#section/Client-Authorization/Make-API-requests), the rate limit varies depending on the endpoint you are using and possibly the type of access you have been given.
I have pasted the pertinent documentation below:

Ads Rate Limits The Ads endpoints (e.g /ads/v3/* listed under
ENDPOINTS - ADS(V3)) adhere to any one of 4 Rate Limit categories.
• READ - 500 queries per second. • READ HIGH - 1000 queries per
minute. • WRITE - 400 queries per minute. • METRICS - 1000 queries per
minute.
You can find this info by viewing an Ads endpoint spec. For example,
Get delivery metrics' definitions has a rate limit category of READ.
Note: API calls to the same rate limit category are accumulative even
if those calls are spread across different endpoints.
Ads API response header You can inspect the response header to
determine the limit and remaining number of calls.
• x-userendpoint-ratelimit-limit - The rate limit •
x-userendpoint-ratelimit-remaining - The remaining number of calls •
x-userendpoint-ratelimit-reset-seconds - The amount of seconds until
remaining value gets reset.
For example, the latest response header will denote a limit of 1000,
remaining of 997, and reset-seconds of 40 if you make 3 API calls to
any endpoint with a READ HIGH category in the last 20 seconds.
Organic Rate Limits The Organic endpoints (e.g /v3/* listed under
ENDPOINTS - ORGANIC(V3)) adhere to a more general rate limit.
Organic API response header You can inspect the response header to
determine the limit and remaining number of calls.
• x-userendpoint-ratelimit-limit - The rate limit •
x-userendpoint-ratelimit-remaining - The remaining number of calls you
have left in a 60-minute window.
For example, the latest response header will denote a limit of 100000
and remaining of 99997 if you make 3 API calls to any Organic endpoint
in the last 60 minutes.
Note: Your rate limit may vary depending on the type of integration
you currently have. We recommend you inspect the response header for
the organic endpoint calls to determine which rate limit applies to
your App.
Exceeding rate limits If you exceed your rate limit, you'll get a 429:
Too many requests error code.


text:
Q: XPath advanced search based on other attribute of the XML I am trying to build and XPath query to select an element according to the attribute of another element. My XML goes like this:
<datadoc>
     <data>
    <molecule coorddimension="3">
      <properties>
        <property name="Mol2_MolInfo_Name" type="stringvalue">
          <val>ZINC01532215_1</val>
        </property>
      </properties>
      <atom key="0" element="6" x="8.2965" y="42.3268" z="14.1097">
        <properties>
          <property name="AtomName" type="stringvalue">
            <val>C1</val>
          </property>
        </properties>
      </atom>
      <atom key="9" element="6" x="7.3131" y="43.2537" z="13.9462">
        <properties>
          <property name="AtomName" type="stringvalue">
            <val>C10</val>
          </property>
        </properties>
      </atom>
      <bond atomref1="0" atomref2="9" type="double">
        <properties>
          <property name="BondSybylType" type="stringvalue">
            <val>ar</val>
          </property>
        </properties>
      </bond>
     </molecule>
    </data>
  </datadoc>

Basically what I want is to select the Atom which @key attribute is referenced by a Bond in @atomref1 y @atomref2 bond's attributes. That's it, being in a Bond node, get the Atom element referenced by that Bond.
What I tried is something like this:
../atom[@key = ./@atomref1]

I use .. because when I do the query I am in Bond node, but that does not seem to work. Any ideas if that can be done with XPath?
Thanks.

A: Try this expression:
.//atom[@key=../bond/@atomref1]

If you want to match @atomref2:
.//atom[@key=../bond/@atomref2]

If you want both <atom>:
.//atom[@key=../bond/@atomref1 or @key=../bond/@atomref2]

A: I don't think you can achieve this in pure xpath (finding the atoms that participate in this specific bond), because you don't have access to the outer context when you are inside the predicate on atom. If you were in XSLT you could use the current() function which provides a reference to the outer context:
../atom[@key = (current()/@atomref1| current()/@atomref2)]

but this is an XSLT specific function, not available in standard XPath.
Depending how you are executing your XPath expression you may be able to provide variable bindings. Since you state in a comment that you're working in Java, here is an example using javax.xml.xpath:
class MapVariableResolver extends HashMap<String, Object> implements XPathVariableResolver {
  public Object resolveVariable(QName name) {
    return get(name.getLocalPart());
  }
}

XPath xp = XPathFactory.newInstance().newXPath();
MapVariableResolver mvr = new MapVariableResolver();
xp.setXPathVariableResolver(mvr);

Node bond = // ... however you get the bond element
mvr.put("current", bond);
NodeList atoms = (NodeList)xp.evaluate(
    "../atom[@key = ($current/@atomref1| $current/@atomref2)]",
    bond,
    XPathConstants.NODESET);


text:
Q: Docker Container to Host Routing I need a better up-to-date solution the following problem:
Problem: I have to manually create an iptable rule in order to allow a route from a dynamically docker bridge to the host. Otherwise container a cannot connect to container b because there is by default no route from a docker network to the docker host itself.
I have the following setup:
container-nginx (docker)
|
|-container-jira (docker) (https://jira.example.com)
|-container-confluence (docker) (https://confluence.example.com)

In order to have properly functioning Atlassian application links between Jira and Confluence:

*

*Jira accesses Confluence over https://confluence.example.com

*Confluence accesses Jira over https://jira.example.com
I use docker-compose for the whole setup and all container are inside the same network. By default this will not work i will get "no route to host" in both containers for hosts confluence.example.com and jira.example.com. Because every container inside the docker network have no route to the docker host itself.
Currently, each time the setup is initialized I manually create an iptable rule from the dynamically created docker bridge with id "br-wejfiweji" to the host.
This is cumbersome, is there "a new way" or "better way" to do this in Docker 1.11.x?

A: docker-compose version 2 does create a network which allows all containers to see each other. See "Networking in Compose" (since docker 1.10)
If your containers are created with the right hostname, that is jira.example.com and confluence.example.com (see docker-compose.yml hostname directive), nginx can proxy-pass directly to jira.example.com and confluence.example.com.
Those two hostname will resolve to the right IP address within the network created by docker-compose for those 3 (nginx, jira and confluence) containers.
I suggest in the comment to use an alias in order for jira to see confluence as nginx (nginx being aliases to confluence), in order for jira to always use nginx when accessing confluence.
version: '2'

services:
  # HTTPS-ReverseProxy
  nginx:
    image: blacklabelops/nginx
    container_name: nginx
    networks:
      default:
        aliases:
          - 'crucible.example.com'
          - 'confluence.example.com'
          - 'crowd.example.com'
          - 'bitbucket.example.com'
          - 'jira.example.com'
    ports:
      - '443:443'


text:
Q: Purpose of Unity Application Block in Microsoft Enterprise Library? Can someone explain to me what is the purpose of the Unity Application Block?  I tried looking through the documentation but its all very abstract.
What are some practical uses for the Unity block?

A: The Unity Application Block is used for dependency injection. I think the best simple definition for DI is from this question

When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn't want you to have. You might even be looking for something we don't even have or which has expired.
What you should be doing is stating a need, "I need something to drink with lunch," and then we will make sure you have something when you sit down to eat.

So for an example,
IUnityContainer container = new UnityContainer();
ILunch lunch = container.Resolve<ILunch>();
Console.WriteLine(lunch.Drink);

This Outputs "Lemonade" because we defined Drink as a Dependency.
public class ILunch {
    [Dependency]
    public IDrink Drink { get; set; }
}

As far as practicality goes, Dependency Injection is really great when you have Dependencies on other objects and you don't want the developer to have to manually set them. It is that simple. It is also great for mocking. The most used example I can think of that I use is mocking a data layer. Sometimes the database isn't ready so instead of stopping development I have a fake layer that returns fake data. The data object is accessed via DI and can be configured to return objects which access the fake layer or the real layer. In this example I am almost using the DI Container as a configurable factory class. For more on Unity MSDN has some great resources http://msdn.microsoft.com/en-us/library/cc468366.aspx.
Other good DI Frameworks include Spring.NET and Ninject

A: Inversion of Control
A quick summation (lot more reading is available this topic, and I highly suggest reading more)...
Microsoft's Unity from the Enterprise Patterns and Practices team is an Inversion of Control container project, or IoC for short.   Just like Castle Windsor, StructureMap, etc.  This type of development is also referred in lamen's terms as Loosely Coupling your components.
IoC includes a pattern for Dependency Injection of your objects, in which you rely on an external component to wire up the dependencies within your objects.
For example, instead of accessing static managers (which are near impossible to unit test), you create an object that relies on an external dependency to act upon.  Let's take a Post service in which you want to access the DB to get a Post.
public class PostService : IPostService
{
  private IPostRepository _postRepo;

  public PostService(IPostRepository postRepo)
  {
    _postRepo = postRepo;
  }

  public IList<Post> GetPosts()
  {
    return _postRepo.GetAllPosts().ToList();
  }
}

This PostService object now has an external dependency on IPostRepository.  Notice how no concretes and no static manager classes are used?  Instead, you have a loose-coupling of a simple Interface - which gives you the power of wiring up all different kinds of concrete classes that implement IPostRepository.
Microsoft Unity's purpose is to wire up that IPostRepository for you, automatically.  So you never have to worry about doing:
// you never have to do this with Unity
IPostRepository repo = new PostRepository();
IPostService service = new PostService(repo); // dependency injection
IList<Post> posts = service.GetPosts();

The above shows where you have to implement two concrete classes, PostRepository() and PostService().  That is tightly-coupling your application to demand/require those exact instances, and leaves it very difficult to unit test.
Instead, you would use Unity in your end point (The controller in MVC, or code behind in ASPX pages):
IUnityContainer ioc = new UnityContainer();
IPostService postService = ioc.Resolve<IPostService>();
IList<Post> posts = postService.GetPosts();

Notice that there are no concretes used in this example (except UnityContainer and Post, obviously)!  No concretes of the services, and no repository.  That is loosely-coupling at its finest.
Here's the real kicker...
Unity (or any IoC container framework out there!) will inspect IPostService for any dependencies.  It will see that it wants (depends) on an instance of IPostRepository.  So, Unity will go into it's object map and look for the first object that implements IPostRepository that was registered with the container, and return it (i.e. a SqlPostRepository instance).  That is the real power behind IoC frameworks - the power to inspect services and wire up any of the dependencies automatically.
I need to finish my blog post about the comparisons of UNity vs Castle vs StructureMap.  I actually prefer Castle Windsor due to its configuration file options, and extensibility points personally.


text:
Q: Android webservices what to study I would like to Apologize if i am posting in the wrong section.
I am learning android app development. When it came using webservices , xml parsing its a bit confusing as

i have no knowledge  on working with any type of online data.

I would like some suggestions on what i could study to understand the concept better.
To explain this situation better
I am a c++ programmer who wroks on local applications.
Now with this study i am trying to obtain some data off a website, to display on the mobile in
a proper formatted manner.
really would appreciate any suggestions.

A: Probably,if you want to make things properly, the most difficult regarding to this task is building your own RestClient to consume the WebServices, here I provide you one with simple HttpMethods: GET, POST.


text:
Q: Switching to multi-row index in dataframe created form list of lists I have a function which creates DataFrame from list of lists:
def logs_reader():
    path = Path("C:\\Users\\" + getpass.getuser() + "\\DCBviz\\logs\\")

cols1 = ['Station ID', 'Reciever type', 'Satellite system', 'Date installed', 'Date removed']
cols2 = ['Station ID', 'Antenna type', 'Cable length', 'Date installed', 'Date removed']

file_list = [f for f in path.glob('**/*.log') if f.is_file()]
receivers_data = []
antennas_data = []
for file in file_list:
    with open(file, encoding='utf8') as f:
        contents = f.read()
        station_id = re.findall("Four Character ID\s*:\s*(.*?)\s*$", contents, re.MULTILINE)

        receiver_types = re.findall("Receiver Type\s*:\s*(.*?)\s*$", contents, re.MULTILINE)
        satellite_sys = re.findall("Satellite System\s*:\s*(.*?)\s*$", contents, re.MULTILINE)
        date_installed = re.findall("Date Installed\s*:\s*(.*?)T.*$", contents, re.MULTILINE)
        date_removed = re.findall("Date Removed\s*:\s*(.*?)T.*$", contents, re.MULTILINE)

        antenna_types = re.findall("Antenna Type\s*:\s*(.*?)\s.*$", contents, re.MULTILINE)
        cable_lengths = re.findall("Antenna Cable Length\s*:\s*([0-9]+\.*[0-9]*)\s.*$", contents, re.MULTILINE)
        antenna_date_installed = re.findall("Date Installed\s*:\s*(.*?)T.*$", contents, re.MULTILINE)
        antenna_date_removed = re.findall("Date Removed\s*:\s*(.*?)T.*$", contents, re.MULTILINE)

        receivers_data.append([station_id, receiver_types, satellite_sys, date_installed, date_removed])
        antennas_data.append([station_id, antenna_types, cable_lengths, antenna_date_installed, antenna_date_removed])

        d = []

        for l in receivers_data:
            d.append({'Station ID': l[0]*len(l[1]),
                  'Reciever type': l[1],
                  'Satellite system': l[2],
                  'Date installed': l[3][0:len(l[1])],
                  'Date removed': l[4][0:len(l[1])]})
        df = pd.DataFrame(d)
return df

df = logs_reader()

and as a return i have dataframe which looks like that:

and i want to split the lists from colums 2-6 and create single entries of pure stings with Station ID as multi-row index. How can I do that?
Desired output:

A: So you have your regexed data in lists
receiver_types
satellite_sys
date_installed
date_removed

antenna_types
cable_lengths
antenna_date_installed
antenna_date_removed

Now I am assuming that each file corresponds to ONE station_id, still the line station_id = re.findall(... will return a list.
Then you will have a station_id which is a list of length 1 and a bunch of other lists. If all the receiver lists are of the same lenght, you can create a df and collect it in receivers_data with the code below (please copy it again as I removed the brackets around station_id). And then do the same for antennae_data.
Notice your current code is discarding df on each iteration and only returning data from the last file that was read.

As I mentioned in the comments, if all lists in the same row are of same length, then the best option is to create a df from each file and concatenate them after the loop
You can replace the line
receivers_data.append([station_id, receiver_types, satellite_sys, date_installed, date_removed])

with
receivers_data.append(
    pd.DataFrame(
        [station_id * len(receiver_types), receiver_types, satellite_sys, date_installed, date_removed],
        columns=list_of_column_names
    )
)
# or instead of a list use a dict with file_name as keys

After you are done reading all files you can concatenate both lists with
df_receivers = pd.concat(receivers_data)
df_antennae = pd.concat(antennae_data)


text:
Q: Stacked Area Graph Using R and ggplot2 Has Holes I'm trying to create a stacked area graph with r and ggplot2. I'd like it to look
like this, but instead the areas overlap and have holes. I'm trying to ensure that the areas are stacked so that the area with the largest value in the most recent month (2016-05 in this case) are on the bottom.
Related posts like this one seem to have holes in the data, which doesn't seem to be the issue here.
Here's sample code to recreate the issue:
sample.data <- structure(
  list(
    rank = structure(
      c(34L, 34L, 34L, 35L, 35L, 35L, 34L, 34L, 34L, 34L, 35L, 35L, 35L, 35L, 35L, 34L),
      .Label = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35"),
      class = "factor"),
    vendor = structure(
      c(1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L),
      .Label = c("34", "35"),
      class = "factor"),
    year.month = c("2015-12", "2016-01", "2015-11", "2015-12", "2016-01", "2015-10", "2016-03", "2016-02", "2015-10", "2016-04", "2015-11", "2016-05", "2016-04", "2016-03", "2016-02", "2016-05"),
    value = c(431616L, 272224L, 229288L, 195284L, 155168L, 154194L, 149784L, 137302L, 126612L, 117408L, 94141L, 56161L, 54606L, 53173L, 49898L, 45348L)),
  .Names = c("rank", "vendor", "year.month", "value"),
  row.names = c(6L, 8L, 4L, 5L, 7L, 1L, 12L, 10L, 2L, 14L, 3L, 15L, 13L, 11L, 9L, 16L),
  class = "data.frame"
)

ggplot(data = sample.data, aes(x = year.month, y = value, group = vendor, color = vendor, reorder(-value), fill=vendor)) +
  geom_area()

Thanks in advance for your help.

A: Try: + geom_area(position="dodge",stat="identity")

A: The following works:
ggplot(data = sample.data[order(sample.data$vendor),],
       aes(x = year.month, y = value, group = vendor, color = vendor,
           reorder(-value), fill=vendor)) + geom_area()

You just had to order your data: sample.data[order(sample.data$vendor),].
If you want to change the order of the graph, you have to "relevel" the vendor variable which is stored as a factor:
sample.data$vendor <- relevel(sample.data$vendor, ref="35")

Here is some code to figure out what vendor to set as the base level according to your criterion:
with(sample.data, sample.data[year.month=="2016-05",
                        "vendor"][which.max(sample.data[year.month=="2016-05", "value"])])


text:
Q: Convert VBA Script to run as VBS file windows or some type of script on a linux box I wrote the below code to check if a webserver/application was running and then log the result to a file. I did this using Excel VBA with FSO Scripting Runtime.  I would like to convert this to a vbs script file to run on a windows server or to something different I can run on a linux server. No part of the code is excel dependant, I was just using the VBA code base.  I tried to copy the copy to a vbs text file and execute it but I kept getting errors. What do I have to do to get this to run outside of excel VBA?
Option Explicit

Public Sub IE_Check()
Dim i As Long
Dim g As Long
Dim x As Long
Dim IE As Object
Dim objElement As Object
Dim objElement2 As Object
Dim Colobj1 As Object
Dim Colobj2 As Object
Dim Colobj3 As Object
Dim FindText1 As String
Dim FindText2 As String
Dim FindText3 As String
Dim TTime As String

Dim fso As New FileSystemObject

' Declare a TextStream.
Dim stream As TextStream

' Create a TextStream.
Set stream = fso.OpenTextFile("C:\log.txt", 2, True)

TTime = Time

Set IE = CreateObject("InternetExplorer.Application")

IE.Visible = True

IE.Navigate "http://yahoo.com"

Do While IE.Busy
    Application.Wait DateAdd("s", 1, Now)
Loop

  FindText1 = InStr(1, IE.Document.body.innerhtml, "Internet Explorer cannot display the webpage")

       If FindText1 > 0 Then

stream.WriteLine ("Webserver_down;" & TTime)

       GoTo webserver_down
         End If

webserver_up:

Set Colobj2 = IE.Document.getElementsByTagName("input")

 g = 0
While g < Colobj2.Length

    If Colobj2(g).Name = "Uid" Then

        Colobj2(g).Value = "test"

    Else
        If Colobj2(g).Type = "submit" Then

            Set objElement = Colobj2(g)

        End If
    End If
 g = g + 1
 Wend

    objElement.Click

  Do While IE.Busy
    Application.Wait DateAdd("s", 1, Now)
 Loop

FindText3 = InStr(1, IE.Document.body.innerhtml, "mstrWebAdmin")

If FindText3 > 0 Then

    stream.WriteLine ("IServer_down;" & TTime)
    Else

stream.WriteLine ("All_GOOD;" & TTime)
End If

webserver_down:

IE.Quit

' Clean up
Set IE = Nothing
Set objElement = Nothing
Set Colobj1 = Nothing
Set objElement2 = Nothing
Set Colobj2 = Nothing
Set Colobj3 = Nothing

stream.Close

End Sub

A: At Ken's proding, I was able to plod through my error with google's help. Thanks Ken.
Here is my reworked code that works as a vbs script
Option Explicit

Public Sub IE_Check()
Dim i
Dim g
Dim x
Dim IE
Dim objElement
Dim objElement2
Dim Colobj1
Dim Colobj2
Dim Colobj3
Dim FindText1
Dim FindText2
Dim FindText3
Dim TTime

Dim dteWait
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
' Declare a TextStream.
Dim stream
' Create a TextStream.
Set stream = fso.OpenTextFile("C:\log.txt", 8, True)

TTime = Time

Set IE = CreateObject("InternetExplorer.Application")

IE.Visible = True

IE.Navigate "http://yahoo.com"

While IE.ReadyState < 4
   FindText1 = 0
Wend

FindText1 = InStr(1, IE.Document.body.innerhtml, "Internet Explorer cannot display the webpage")

    If FindText1 > 0 Then

stream.WriteLine ("Webserver_down;" & TTime)
 stream.Close
  IE.Quit
 Wscript.Quit
         End If

 Set Colobj2 = IE.Document.getElementsByTagName("input")

g = 0
 While g < Colobj2.Length

     If Colobj2(g).Name = "Uid" Then

        Colobj2(g).Value = "test"

    Else
        If Colobj2(g).Type = "submit" Then

            Set objElement = Colobj2(g)

        End If
     End If
 g = g + 1
 Wend

    objElement.Click

While IE.ReadyState < 4
   FindText1 = 0
Wend

FindText3 = InStr(1, IE.Document.body.innerhtml, "mstrWebAdmin")

If FindText3 > 0 Then

    stream.WriteLine ("IServer_down;" & TTime)
    Else

stream.WriteLine ("All_GOOD;" & TTime)
End If

IE.Quit

stream.Close

End sub
call IE_Check()


text:
Q: How Cut out an image and zoom it I would like to zoom in with openseadragon but for performance
 reasons i would like to have the opportunity to cut a
picture and zoom based on the zooming work find just we need this for performance.


text:
Q: Fractional power of the operator $\mathcal{L}_t[t f(t)](x)$ and equivalence of divergent integrals I wonder whether an expression for fractional power of operator $\mathcal{L}_t[t f(t)](x)$ that involves Laplace transform can be derived?
I am asking this because this operator preserves the area under the function:
$$\int_0^\infty f(x)dx=\int_0^\infty\mathcal{L}_t[t f(t)](x)dx=\int_0^\infty\frac1x\mathcal{L}^{-1}_t[ f(t)](x)dx$$
But more importantly, this still works well even with divergent integrals, thus allowing us to define equivalent classes of divergent integrals. For instance, the following divergent integrals are obtained by consecutive applying this transform, and as such, can be postulated to be equal  (the first one and the third one are similar up to a shift by the way):
$\int_0^\infty\frac{\theta (x-1)}{x}dx=\int_0^\infty\frac{e^{-x}}{x}dx=\int_0^\infty\frac{dx}{x+1}=\int_0^\infty\frac{e^x x \text{Ei}(-x)+1}{x}dx=\int_0^\infty\frac{x-\log (x)-1}{(x-1)^2}dx$
The following plot illustrates the comparison:

So, is there a way to express fractional powers of this transform?


text:
Q: Why is the TextChanged event not working in this Xamarin.Android code? In a Xamarin.Android app, following the example at https://developer.xamarin.com/videos/?v=Activities_and_Intents (19:55) I am trying to assign an event handler to the onclick event of a button, and smilarly to the video above, I'd like not to call a delegate or lambda but rather just call a method defined elsewhere. This is not working in my code, but if I use a delegate it does... Can you explain why?
Also, I am trying to do the same with an EditText, for which I'd like to add event for when text is changed. But this is not working too..
public class MainActivity : Activity

{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        Button button = FindViewById<Button>(Resource.Id.MyButton);
        button.Click += delegate { button.Text = "clicked!" };
        // this works

        Button searchButton = FindViewById<Button>(Resource.Id.searchButton);
        searchButton.Click += SearchButton_Click;

        EditText artistNameEditText = FindViewById<EditText>(Resource.Id.artistNameEditText);
        artistNameEditText.TextChanged += artistNameEditText_TextChanged;
    }

    private void SearchButton_Click(object sender, EventArgs e)
    {
        Console.WriteLine("button pressed!");
        // this is not working!
    }

    private void artistNameEditText_TextChanged(object sender, TextChangedEventArgs e)
    {
        Console.WriteLine("text has changed!");
        // this is not working!
    }
}

A: There is nothing wrong with my code.
The reason it was not working is... I was not uninstalling my app from the device before deploying the new version to it, so I was running the old version over and over again. I took for granted that the old version would be replaced by the new one, just like when you install a new version of the same APK again. It was a bit problematic to spot because I was not making any changes to the UI, but only experimenting with event handlers.
Well, lesson learned, hope this helps someone else...

A: This is an easy one first implement Android.Text.ITextWatcher in your MainActivity like this:
public class MainActivity : Activity, Android.Text.ITextWatcher
    {
        public void AfterTextChanged (Android.Text.IEditable s)
        {

        }

        public void BeforeTextChanged (Java.Lang.ICharSequence s, int start, int count, int after)
        {

        }

        public void OnTextChanged (Java.Lang.ICharSequence s, int start, int before, int count)
        {
            //were text is changed
        }
...
}

and suscribe the TextChangedListener to your element using this
EditText artistNameEditText = FindViewById<EditText>(Resource.Id.artistNameEditText);
artistNameEditText.AddTextChangedListener (this);

A: Its my much simpler to use the Xamarin version of it.
textfield.TextChanged += (sender, e) =>
        {
            var abc = 123;
        };

Hope that works for you :)

A: the problem is that you are using Console in android app, just look to the code below and adjast your code and make sure to remove Console statements (use something else such as Toast).
    private void SearchButton_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        btn.Text = "Search Button Clicked!";
        // Now it is working! :)
    }

    private void artistNameEditText_TextChanged(object sender, TextChangedEventArgs e)
    {
        Toast.MakeText(this, "Text has just changed!", ToastLength.Long).Show();
        // Now it is working! :)
    }


text:
Q: how to get all business listing nearby user in iphone sdk without using database? i want to create an application which allows user to get all only business listing in tableview by its current location. like you can see in Google Latitude
here you can see the business lists in check in page. the details can be seen in check in page i want to get that kind of all data in my application. i have also seen this API for Places get from Google places. i want to list out all business data. can i use this url in my application? it will directly give me all results? if anybody have any suggestions or SAMPLE than please provide me. my client prefers me to use this yellow API. you can get an sample code to use this API from here. please guide me.


text:
Q: How do I bind an Image dynamically in XAML? The following displays an image correctly in a silverlight usercontrol:
Image image = pagingManager.BaseApp.DatasourceManager.GetImage("helloWorld1");
ContentArea.Content = image;
...
<ContentControl x:Name="ContentArea"/>

However, I want to dynamically bind the image to XAML, e.g. like this:
#region ViewModelProperty: MainImage
private Image _mainImage;
public Image MainImage
{
    get
    {
        return _mainImage;
    }

    set
    {
        _mainImage = value;
        OnPropertyChanged("MainImage");
    }
}
#endregion
...
MainImage = pagingManager.BaseApp.DatasourceManager.GetImage("helloWorld1");

And my XAML is this but the result is that it shows nothing:
<Image Source="{Binding MainImage}"/>

What do I need to put in my XAML to make it display the image object I have in my ViewModelProperty?

A: The Image.Source property is of type ImageSource, so your ViewModel should expose an ImageSource. Image is a control, it has nothing to do in the ViewModel.
If you do expose an Image control in your ViewModel (which is definitely a bad idea), then you should display it in a ContentControl, not an Image control :
<ContentControl Content="{Binding MainImage}" />


text:
Q: How to stop Apache from crashing my entire server? I maintain a Gentoo server with a few services, including Apache. It's fairly low-end (2GB of RAM and a low-end CPU with 2 cores). My problem is that, despite my best efforts, an over-loaded Apache crashes the entire server. In fact, at this point I'm close to being convinced that Linux is a horrible operating system that isn't worth anyone's time looking for stability under load.
Things I tried:

*

*Adjusting oom_adj for the root Apache process (and thus all its children). That had close to no effect. When Apache was overloaded it would bring the system to a grind, as the system paged out everything else before it got to kill anything.

*Turning off swap. Didn't help, it would unload memory paged to binaries of processes and other files on /, thus causing the same effect.

*Putting it in a memory-limited cgroup (limited to 512 MB of RAM, 1/4th of the total). This "worked", at least in my own stress tests - except the server keeps crashing under load (basically stalling all other processes, inaccessible via SSH, etc.)

*Running it with idle I/O priority. This wasn't a very good idea in the end, because it just caused the system load to climb indefinitely (into the thousands) with almost no visible effect - until you tried to access an unbuffered part of the disk. This caused the task to freeze. (So much for good I/O scheduling, eh?)

*Limiting the number of concurrent connections to Apache. Setting the number too low caused web sites to become unresponsive due to most slots being occupied with long requests (file downloads).

*I tried various Apache MPMs without much success (prefork, event, itk).

*Switching from prefork/event+php-cgi+suphp to itk+mod_php. This improved performance, but didn't solve the actual problem.

*Switching I/O schedulers (cfq to deadline).

Just to stress this out: I don't care if Apache itself goes down under load, I just want the rest of my system to remain stable. Of course, having Apache recover quickly after a brief period of intensive load would be great to have, but one step at a time.
Right now I am mostly dumbfounded by how can humanity, in this day and age, design an operating system where such a seemingly simple task (don't allow one system component to crash the entire system) seems practically impossible - or at least, very hard to do.
Please don't suggest things like VMs or "BUY MORE RAM".

Some more information gathered with a friend's help:
The processes hang when the cgroup oom killer is invoked. Here's the call trace:

[<ffffffff8104b94b>] ? prepare_to_wait+0x70/0x7b
[<ffffffff810a9c73>] mem_cgroup_handle_oom+0xdf/0x180
[<ffffffff810a9559>] ? memcg_oom_wake_function+0x0/0x6d
[<ffffffff810aa041>] __mem_cgroup_try_charge+0x32d/0x478
[<ffffffff810aac67>] mem_cgroup_charge_common+0x48/0x73
[<ffffffff81081c98>] ? __lru_cache_add+0x60/0x62
[<ffffffff810aadc3>] mem_cgroup_newpage_charge+0x3b/0x4a
[<ffffffff8108ec38>] handle_mm_fault+0x305/0x8cf
[<ffffffff813c6276>] ? schedule+0x6ae/0x6fb
[<ffffffff8101f568>] do_page_fault+0x214/0x22b
[<ffffffff813c7e1f>] page_fault+0x1f/0x30

At this point, the apache memory cgroup is practically deadlocked, and burning CPU in syscalls (all with the above call trace). This seems like a problem in the cgroup implementation...

A: I hate to say it, but you appear to be asking the wrong question.
It's not about stopping Apache from bringing down your server, it's about having your webserver serve more queries per second - enough so that you don't have a problem.  A part of the answer to the reframed question is then limiting Apache so that it does not crash at high loads.
For the second part of that, Apache has some limits you can set - MaxClients being an important configuration. This limits how many children it's allowed to run. If you can take load off Apache for long-running processes (large files being downloaded for example), that's another slot in Apache to be able to serve PHP. If the file downloads have to be verified by the PHP layer, they can still do that, and pass back out to a more optimised webserver for the static content, such as with NginX sendfile
Meanwhile, forking Apache every on every single request for the slowest way to run PHP - as a CGI (whatever apache MPM you may be using) - is also having the machine spend large amounts of time not running your code. mod_php is significantly more optimised.
PHP can do huge amounts of traffic when Apache and the PHP layer are appropriately optimised.  Yesterday, 11th Dec 2010, for example, the pair of PHP servers that I run did almost 19 Million hits in the 24hr period, and most of that in the 7am-8pm time-period.
There are plenty of other questions here, and articles elsewhere about optimising Apache and PHP, I think you need to read them first, before blaming Linux/Apache & PHP.

A: When you are dealing with a production apache server, you MUST have an average process size, especially with php, I'll recommend you to:

*

*Check your process averages memory consumption

*Adjust MaxClients to AVERAGE_MEMORY / RAM_DEDICATED_TO_APACHE

Where RAM_DEDICATED_TO_APACHE it must be another estimation of the TOTAL_RAM minus the ram
that needs the rest of the machine (and be generous with the database if
you are running one in the same machine).
I really recommend you to use Varnish, you can easily run 2
servers on different ports on the save machine, and route the static files to an specialized file (media) server (lighthttpd, nginx) or an apache instance with worker and no extra modules. And of course catch the static content with varnish.
Split the load is important because you will be using
the same amount of ram to deliver any static file (which needs less than 1MB) if you don't
do it.
If you really need to make sure to never consume all the ram, you can
install a new cronjob running each 2 minutes (less or more as you consider)
with the following line, adjusting the  50 to any amount of the lowest ram, and keep this number above 30 at least; you'll need some ram to stop the server.
vmstat -S M | tail -n 1 | awk 'BEGIN{ "date" | getline date }{if($4 + $6 < 50){ system("/etc/init.d/httpd stop"); system("/etc/init.d/httpd start"); print "Rebooting apache  on " date >> "/var/log/apache-reboots.log"}}'

This is a very hakish (dirty) way of limit you ram, but it can be very helpful
when you are not really sure about your average memory per apache process,
and if you see several reboots in you log file ("/var/log/apache-reboots.log"),
the you should tune your apache MaxClients, MaxRequestsPerChild, ThreadsPerChild
to avoid futures hard-reboots, with the time and tunning, you will have the exact configuration for your server.

A: A few general things you can try:

*

*It is hard to tell from your description whether Apache/Linux is actually crashing or just becoming severely overloaded. I would suspect that you just have a server that has such a high load that the only effective course of action is cycling the power. I would approach the problem as an overloaded server unless there is specific evidence of an actual crash. If you optimize the server's performance but it still actually crashes then you can work to find and address that problem.

*You generally never want your server to get in a condition of it regularly hitting the swap, especially any Apache instances. You can quickly get into a run away load situation where the server is running fine but when the traffic increases a few percent it starts to use the swap and the load sky rockets causing the site to be slow or inaccessible. To prevent Apache from use the swap reduce the number of max clients/connections and/or reduce the memory use by disabling any modules that are not needed. See also the next point.

*You mention that connections in Apache are being used by long requests like file downloads. To help reduce this problem you can use a second web server (like lighttp) setup to serve just static content which Apache forwarding/redirecting requests to it. This frees up connections in Apache to do the heavy work and let you reduce the number of max clients/connections.

*If you need to prevent a DoS, whether on purpose or accidental, there are various Apache modules you can install and setup. I've used mod_evasive and mod_limitipconn for example which worked well enough to prevent the less malicious types of DoS.

*Don't dismiss optimizing Apache or other parts of the OS or application. Computers are very good at doing exactly what you tell them so if your Apache settings say "use more resources than this server has" then it will do exactly that. Like a lot of software, Apache is meant to work well with a huge range of hardware and applications but needs to be correctly setup for both. The default configuration only works well for a simple, low traffic web site.

*With a little tuning you should be able to find a balance where the server gets to a high load but is still responsive enough to log in and check on it. At this point your options are either to profile and optimize the application, including adding caching layers, or get better hardware. This step should be after getting Apache setup correctly.

A: Have you tried changing /proc/sys/vm/overcommit_memory to 2 ?
This means the kenel will not allocate morememory than swap + a configurable percentage (proc/sys/vm/overcommit_ratio) of available ram.
In the case Apache will just fail as it't can't allocate the ram but services already loaded such as openSSH will continue to function.
I should add I have never tried this and just discovered this setting now. I would love to hear from any one who knows more. Otherwise I will test this tomorrow as I have exactly the same problem as described in the question.

A: I found the problem...
Setting oom_adj to 15 for the whole memory-limited cgroup turned out to be very stupid. The adjusted score of all processes in the cgroup ended up all being 1000 - so when the cgroup ran out of memory, the system killed random processes and  generally misbehaved.
I haven't had any system crashes after simply removing the line that set oom_adj.

A: this may be a little bit late, but I can say that blaming the OS is simply not the way to go. the OS is designed to meet the expectations of several different use case scenarios, therefore, you MUST configure it to meet your requirements.
not only this, but if you are having so much load that the system is crashing, then you have to optimize your system, or expand your network.
while over-optimizing too early can make things painful later on, not optimizing anything at all from the very beginning can have the very same consequences. it's all about balance.
however, you claim your goal is to prevent the system from crashing.. but then go on to say your solutions did not work. but some of them did work, you just were not happy with the results.
when you run out of memory, you swap. or things crash. end of story. if you don't want to swap, you have to:

a) limit your incoming connections. this has the effect of either
  turning people away
b) send them to the backlog. which has the effect of causing the site
  to slow, or die.
c) buy more memory. which you did not want to do
d) scale your network. which you also did not want to do
e) load balance. which is much like 'D'

without careful optimization, fine tuning, and expansion.. you cannot prevent all these things from happening.
in my experience, I learned that by using a granular mix of all the above generally caused things to work out in the end.
first off, I use apache2 + mpm_event + mod_fcgid. i'd carefully configure just about every possible option apache has to configure. this might take one evening to do, and another to get right. but it will be worth it.
I'd ensure that there is always one pool of workers ready to handle incoming connections, and let it grow, but cap this pool at some reasonable limit. this may sacrifice some speed, but results in stability.
second, I use both CGroups and IO Priority / CPU Priotiy to schedule different groups of services for different priorities.
anything that is 100% critical, which I always need access to, they are reserved a block of memory, and is set a higher IO and CPU priority. i'd whip up a script that sets these priorities every hour or so, so that children will inherit these priorities if their parent changes.
next is DNS, then Web, then Mail. in this order. this way, if something is misbehaving, more critical elements are favoured.
using monitor software, check if things are online, and if not, restart them. if anything has been using more than X MB of memory, for X Cycles... and you cannot connect to the service (i.e. on http://...:80) kill the service, and restart it. if it restarts more than X times in X cycles, time out (and notify for manual inspection). you might drop a few users occasionally, but atleast your system remains stable!
third, if you have a dedicated server, id put all website services on a separate disk. keep IO operations mainly over a different controller.
fourth, check out apache modules like mod_bw and mod_qos. mod_bw can do more than just limit bandwidth per virtualhost, and mod_qos... this is a quality of service module that can help mitigate some issues.
besides what you would expect from a full fledges QoS module, it can help with things like DoS preventing slowdos, limit NULL connections, and it can even turn off keepalive when the server reach a certain threshold of concurrent connections.
finally, I would set-up some intelligent caching front ends, or a load balancer. for example: using a few VM Instances, maybe use Varnish or NGinx, cache static files upstream. this will offload all the open slots Apache requires for serving that static content.
I'm really not sure what you expect to happen when you get alot of traffic. you want it to both remain stable, but you don't want to loose any functionality under stress, and you don't want to optimize anything, and you don't want to upgrade or extend your network?
well, if you don't want to CHANGE anything, how do you expect the problem to go away?


text:
Q: Getting driving distance with Google maps API and SSIS package in C# UPDATE:  Found the Google distancematrix and tried to modify my code accordingly.  I am getting an invalid arguments error here:
return new GeoLocation(dstnc, uri.ToString());
            }
            catch
            {
                return new GeoLocation(0.0, "https://");
            }

Basically, I need to get the driving distance from two known lat/longs.  I am using an SSIS package and I found a fantastic tutorial online that comes very close to producing the results I need.
Tutorial: http://www.sqlmusings.com/2011/03/25/geocode-locations-using-google-maps-v3-api-and-ssis/
What they are doing is passing a known street address to Google and reading the lat/long from the returned XML.
What I need to do differently is pass two known lat/longs and read the returned distance.
Example: https://maps.googleapis.com/maps/api/distancematrix/xml?origins=32.1576780,%20-82.9070920&destinations=27.6536997,%20-81.5158944&mode=driving&units=imperial&sensor=false
They use C# which I am not good enough with to know how to make the modification.  I took a stab at it anyway and here is what I came up with:
 using System;
using System.Collections.Generic;
using System.Text;

//added these
using System.Data;
using System.Net;
using System.Web;
using System.Xml;

//  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF
//  ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
//  TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.

namespace sqlmusings
{

    public interface IGeoLocation
    {
        string geocodeurl { get; set; }
        float distance { get; set; }
    }

    public struct GeoLocation : IGeoLocation
    {
        private string _geocodeurl;
        private Double _distance;

        public GeoLocation(string geocodeurl, Double distance)
        {
            _geocodeurl = geocodeurl;
            _distance = distance;
        }

        public string geocodeurl
        {
            get { return _geocodeurl; }
            set { _geocodeurl = value; }
        }

        public Double distance
        {
            get { return _distance; }
            set { _distance = value; }
        }
    }

    public class GeoCode
    {
        const string _googleUri = "https://maps.googleapis.com/maps/api/distancematrix/xml?origins=";
        //sample
        //https://maps.googleapis.com/maps/api/distancematrix/xml?origins=32.1576780,-82.9070920&destinations=27.6536997,-81.5158944&mode=driving&units=imperial&sensor=false

        private static Uri GetGeoCodeURI(string origins)
        {
            origins = HttpUtility.UrlEncode(origins);
            string uri = String.Format("{0}{1}&sensor=false", _googleUri, origins);

            return new Uri(uri);

        public static GeoLocation GetCoordinates(string origins)
        {
            WebClient wc = new WebClient();
            Uri uri = GetGeoCodeURI(origins);

            try
            {
                string geoCodeInfo = wc.DownloadString(uri);
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(geoCodeInfo);

                string status = xmlDoc.DocumentElement.SelectSingleNode("status").InnerText;
                double dstnc = 0.0;
                XmlNodeList nodeCol = xmlDoc.DocumentElement.SelectNodes("result");
                foreach (XmlNode node in nodeCol)
                {

                    dstnc = Convert.ToDouble(node.SelectSingleNode("distance/text").InnerText, System.Globalization.CultureInfo.InvariantCulture);
                }
                return new GeoLocation(dstnc, uri.ToString());
            }
            catch
            {
                return new GeoLocation(0.0, "https://");
            }
        }

    }

}

I added the distance and _distance at the top of the code but Im not sure where to make the change to add a field for my second lat/long.
Just in case, here is the Main.cs (I have not modified it at all):
/* Microsoft SQL Server Integration Services Script Component
*  Write scripts using Microsoft Visual C# 2008.
*  ScriptMain is the entry point class of the script.*/

using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using SC_65a998228f6546ed965116b9f8b76953.csproj;

//  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF
//  ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
//  TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.

[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{

    public override void PreExecute()
    {
        base.PreExecute();
        /*
          Add your code here for preprocessing or remove if not needed
        */
    }

    public override void PostExecute()
    {
        base.PostExecute();
        /*
          Add your code here for postprocessing or remove if not needed
          You can set read/write variables here, for example:
          Variables.MyIntVar = 100
        */
    }

    public override void Input0_ProcessInputRow(Input0Buffer Row)
    {
        /*
          Add your code here
        */
        sqlmusings.GeoLocation geolocation = sqlmusings.GeoCode.GetCoordinates(Row.AddressLine1 + "," + Row.City + "," + Row.State + "," + Row.Country);
        Row.Latitude = Convert.ToDecimal(geolocation.latitude);
        Row.Longitude = Convert.ToDecimal(geolocation.longitude);
        Row.GeoCodeURL = geolocation.geocodeurl;
   }

}

Just a push in the right direction is all Im asking.

A: The trick with the String.Format function is that the numbers in braces (e.g. {0} and {1}) are the bits that will be replaced by the arguments you provide in respective order.
What you usually want to do is something like this:
double oLat = 32.1576780, oLng = -82.9070920;
double dLat = 27.6536997, dLng = -81.5158944;

String url = String.Format("https://maps.googleapis.com/maps/api/distancematrix/xml?origins={0},{1}&destinations={2},{3}&mode=driving&sensor=false", oLat, oLng, dLat, dLng);

One thing to keep in mind is that the Maps APIs have Terms & Conditions that require certain things in order to be able to use the API for free.  Make sure you read over them, as you may need a commercial license for your use case.


text:
Q: Data structures : Lists and Arrays If in Lists, data is stored in random memory locations with a pointer to the next location, how can we read the lists easily with an index?
In Array, it is a continuous chunk of memory so indexing is possible.
I read that reading from an array is efficient than reading from a list.
I'm confused.
I'm particularly concerned with Python.


text:
Q: MySql Join 3 Tables where two tables are joined and then a third after I have 3 tables I would like to join.
vm, ds and tp
vm joins with ds
ds joins with tp
I only want to match with the original query below that returns 8703 and return a single row from the other tables so I end up with 8703 rows in the end.
`SELECT *
FROM vm
WHERE date = (SELECT max(date) from vm)`

This returns 8703 results as expected.
I then want to use the above table and join it with another table to retrieve some more values.
Second Query to join
`SELECT *
FROM ds
WHERE date = (SELECT max(date) from ds)`

I want to join the above two on:
INNER JOIN ds ON vm.datastore = ds.DatastoreName
Third Query to join
`SELECT *
FROM tp
WHERE date = (SELECT max(date) from tp)`

I want to join tables ds and tp on:
`INNER JOIN tp ON ds.uid = tp.uid`

I have tried the following but it returns 30,000 thousand rows and I only want the 8703 from above.
Full Query:
`SELECT *
FROM vm
INNER JOIN ds ON vm.datastore = ds.DatastoreName
INNER JOIN tp ON ds.uid = tp.uid
WHERE vm.date = (SELECT MAX(date) from vm)
AND ds.date = (SELECT MAX(date) from ds)
AND tp.date = (SELECT MAX(date) from tp)`

I have also tried many versions of the above over the last 8 hours.
Is what I am trying to do possible?

A: Your INNER JOINs are expanding the result - from 8703 to 30,000 - because there are probably multiple DatastoreName in ds for each datastore in vm.
Have you tried GROUP BY vm.id?


text:
Q: Ansible root/password login I'm trying to use Ansible to provision a server and the first thing I want to do is test the ssh access. If I use ssh directly I can log in fine...
ssh root@server
root@backups's password:

If I use Ansible I can't...
user@ansible:~$ ansible backups -m ping --user root --ask-pass
SSH password:
backups | UNREACHABLE! => {
    "changed": false,
    "msg": "Invalid/incorrect password: Permission denied, please try again.",
    "unreachable": true
}

The password I'm using is correct - 100%.
Before anyone suggests using SSH keys - that's what part of what I'm looking to automate.

A: The issue was caused by the getting started documentation setting a trap.
It instructs you to create an inventory file with servers, use ansible all -m ping to ping those servers and to use the -u switch to change the remote user.
What it doesn't tell you is that if like me not all you servers have the same user, the advised way to specify a user per server is in the inventory file...
server1    ansible_connection=ssh    ansible_user=user1
server2    ansible_connection=ssh    ansible_user=user2
server3    ansible_connection=ssh    ansible_user=user3

I was provisioning a server, and the only user I had available to me at the time was root. But trying to do ansible server3 -user root --ask-pass failed to authenticate. After a couple of wasted hours I discovered the -user switch is only effective if the inventory file doesn't have a user. This is intended precedence behaviour. There are a few gripes about this in GitHub issues but a firm 'intended behaviour' mantra is the response you get if you challenge it. It seems to go against the grain to me.
I subsequently discovered that you can specify -e 'ansible_ssh_user=root' to override the inventory user - I will see about creating a pull request to improve the docs.
While you're here, I might be able to save you some time with some further gotchas. This behaviour is the same if you use playbooks. In there you can specify a remote_user but this isn't honoured - presumably also because of precedence. Again you can override the inventory user with -e 'ansible_ssh_user=root'
Finally, until I realised Linode could provision a server with an SSH key deployed, I was trying to specify the root password to an ad-hoc command. You have to encrypt the password and this gives you a long string and this is almost certainly going to include $ in it which bash will treat as substitutions. Make sure you escape these.
The lineinfile module behaviour isn't intuitive either.

A: Write your hosts file like this. It will work.
192.168.2.4
192.168.1.4

[all:vars]
ansible_user=azureuser

Then execute the following command: ansible-playbook --ask-pass -i hosts main.yml --check  to check before configuration.
Also create a ansible.cfg file. Then paste the following contents there:
[defaults]
inventory         = hosts
host_key_checking = False

Note: All the 3 files namely, main.yml,ansible.cfg & hosts must be in the same folder.
Also, the code is tested for devices connected to a private network using Private IPs. I haven't checked using Public IPs. If using Azure/AWS, create a test VM and connect it to the VPN of the other devices.
Note: You need to install the SSHPass package to be able to authenticate with Password.
For Ubuntu: apt-get install sshpass


text:
Q: Read file lines into one string seperated by \r\n I need to read a file that looks like
foo
bar
foobar
barfoo

in C and save it to a char buf[] that looks like "foo\r\nbar\r\nfoobar\r\nbarfoo\r\n"
Currently I am trying to use fgets() but im not sure how I can add the \r\n into the char[] that I have
void client(char* server_host) {
    int rc, client_socket;
    char buf[BUFFER_LEN];
    client_socket = connect_to_server(server_host, NON_RESERVED_PORT);
    printf("\nEnter a line of text to send to the server or EOF to exit\n");
    while(fgets(buf, BUFFER_LEN, stdin) != NULL) {
        send_msg(client_socket, buf, strlen(buf) + 1);
        rc = recv_msg(client_socket, buf);
        buf[rc] = '\0';
        printf("client received %d bytes  :%s: \n", rc, buf);
        printf("\nEnter a line of text to send to the server or EOF to exit\n");
    }
}

This is the way I'm trying to do this, but when I use the send_msg() I need the buf that I'm using to be seperated by the \r\n delimeter on each line that I read in.

A: Sounds like you're saying you have a buffer buf that contains something like
{ 'a', 'b', 'c', '\n', 0 }

{ 'a', 'b', 'c', 0 }            // In the case of a line that's longer than BUF_SIZE-1.

But you want a buffer that contains
{ 'a', 'b', 'c', '\r', '\n' }   // send_msg doesn't care about the NUL.

{ 'a', 'b', 'c' }

It's just a question of checking if the last character is a LF, and replacing the LF and NUL with CR and LF.
...
while (fgets(buf, BUFFER_LEN, stdin) != NULL) {
    size_t len = strlen(buf);
    if (buf[len-1] != '\n') {
       // The line didn't fit in the buffer.
       send_msg(client_socket, buf, len);
       continue;
    }

    buf[len-1] = '\r';
    buf[len] = '\n';
    ++len;
    send_msg(client_socket, buf, len);

    ...
}
...

This code doesn't handle NULs entered by the user well. It's GIGO situation as far as this answer is concerned.

A: A hacky, yet minimal code.
char buf[BUFFER_LEN];

// Read up to 2 less to be sure we have room for an added \r\n
while(fgets(buf, BUFFER_LEN - 2, stdin)) {

  // Use strcspn() to find offset of \n if it exists or the string length
  // Then write \r\n\ there
  strcpy(buf + strcspn(buf, "\n"), "\r\n");

  // send it
  send_msg(client_socket, buf, strlen(buf));
}

A: This may be total overkill for the task at hand, but I like to encapsulate data in structs and create support functions for those structs. It takes some time for all the boilerplate but it's usually nice when it's done.
Here I've made a struct and typedefined into String. It has a char* for the actual data, the size of the data and the capacity - which is how much data it's capable of currently holding.
typedef struct {
    char *data;
    size_t size;
    size_t capacity;
} String;

To deal with such a String, I'd start by creating these support functions - hopefully with self explanatory names and signatures:
String *String_create();
void String_destroy(String *s);
bool String_append(String *s, const char *rhs, size_t len);
bool String_getline(String *s, FILE *fp);

That's the minimal set of functions we need for this - but if anything else pops up, you can certainly add further String functions.
Example implementation:
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    char *data;
    size_t size;
    size_t capacity;
} String;

String* String_create() {
    String *s = malloc(sizeof *s);         // allocate a String struct
    if(s) {
        s->size = 0;                       // initialize its values
        s->capacity = 10;
        s->data = malloc(s->capacity + 1); // some initial capacity + '\0'
        if(s->data == NULL) {
            free(s);                       // deal with allocation problems
            return NULL;
        }
        s->data[0] = '\0';                 // null terminate
    }
    return s;
}

void String_destroy(String *s) {           // deallocates a String
    free(s->data);
    free(s);
}

// Append to an existing string
bool String_append(String *s, const char *rhs, size_t len) {
    if(s->size + len > s->capacity) {        // check capacity
        // not enough space in the String - need to increase it

        size_t nc = (s->size + len) * 5 / 3; // make it grow some
        char* ns = realloc(s->data, nc + 1); // allocate more space
        if(ns == NULL) return false;         // could not increase capacity
        s->capacity = nc;                    // set new capacity
        s->data = ns;                        // and the new data pointer
    }
    // append rhs to our String
    memcpy(s->data + s->size, rhs, len);
    s->size += len;
    s->data[s->size] = '\0';                 // ... and null terminate
    return true;
}

// Convenience wrappers for the String_append function
bool String_append_char(String *s, char ch) {
    return String_append(s, &ch, 1);
}

bool String_append_String(String *s, const String *rhs) {
    return String_append(s, rhs->data, rhs->size);
}

// Read a line into a String from a stream
bool String_getline(String *s, FILE *fp) {
    s->size = 0;                             // zero out this String
    int ch;
    while((ch = fgetc(fp)) != EOF) {         // read until EOF
        // call the above append function
        if(String_append_char(s, ch) == false) return false;
        if(ch == '\n') return true;          // newline, return success
    }
    return s->size != 0;                     // at EOF, did we get some data?
}

With that boilerplate, reading everything from the file into a String could be done like this:
int main() {
    String* str = String_create();      // The final String
    String* tmp = String_create();      // A temporary String to read lines

    while(String_getline(tmp, stdin)) { // Read lines until that fails
        // The String is at least one char long if String_getline succeeds so
        // this is safe:
        if(tmp->data[tmp->size-1] == '\n') { // got newline
            tmp->data[tmp->size-1] = '\r';   // replace it with \r
            String_append_char(tmp, '\n');   // and add \n
        }

        // Append this String to the final String
        if(String_append_String(str, tmp) == false) {
            printf("Could not append %s to %s\n", tmp->data, str->data);
            exit(1);
        }
    }
    String_destroy(tmp);               // not needed anymore

    send_msg(client_socket, str->data, str->size + 1);

    String_destroy(str);
}


text:
Q: Unable to install base64enc package in R This is the error message I get while trying to install base64enc as a dependencie of FastRweb:
> install.packages('base64enc',,'http://www.rforge.net/')
Aviso en install.packages("base64enc", , "http://www.rforge.net/") :
 argument 'lib' is missing: using '/usr/local/lib/R/site-library'
probando la URL 'http://www.rforge.net/src/contrib/base64enc_0.1-3.tar.gz'
Content type 'application/x-gzip' length 7186 bytes
URL abierta
==================================================
downloaded 7186 bytes

* installing *source* package 'base64enc' ...
** libs
gcc -I/usr/share/R/include      -fpic  -std=gnu99 -O3 -pipe  -g -c base64.c -o base64.o
gcc -I/usr/share/R/include      -fpic  -std=gnu99 -O3 -pipe  -g -c uriencode.c -o uriencode.o
gcc -I/usr/share/R/include      -fpic  -std=gnu99 -O3 -pipe  -g -c utf8.c -o utf8.o
utf8.c: In function 'utf8_check':
utf8.c:75: warning: implicit declaration of function 'XLENGTH'
gcc -shared -o base64enc.so base64.o uriencode.o utf8.o -L/usr/lib64/R/lib -lR
installing to /usr/local/lib/R/site-library/base64enc/libs
** R
** preparing package for lazy loading
** help
Aviso: ./man/dataURI.Rd:30: unknown macro '\href'
*** installing help indices
** building package indices ...
** testing if installed package can be loaded
Error in dyn.load(file, DLLpath = DLLpath, ...) :
  imposible cargar la biblioteca compartida '/usr/local/lib/R/site-library/base64enc/libs/base64enc.so':
  /usr/local/lib/R/site-library/base64enc/libs/base64enc.so: undefined symbol: XLENGTH
ERROR: loading failed
* removing '/usr/local/lib/R/site-library/base64enc'

The downloaded packages are in
        '/tmp/RtmpBfdYFV/downloaded_packages'
Mensajes de aviso perdidos
In install.packages("base64enc", , "http://www.rforge.net/") :
  installation of package 'base64enc' had non-zero exit status
>

Looks like the package is downloaded but something is broken in my config or in the installation script.
Thanks

A: If you are using linux, the easiest is to try to install it directly from the repository, e.g.
sudo apt-get install r-cran-base64enc
In this way, it will install as well any additional packages needed. R-CRAN packages are also available this way, at least in Debian and related distributions (Ubuntu, Mint).


text:
Q: Using Gensin Word2Vec to improve search I have a dataset off millions of arrays like follows:
  sentences=[
    [
     'query_foo bar',
     'split_query_foo',
     'split_query_bar',
     'sku_qwre',
     'brand_A B C',
     'split_brand_A',
     'split_brand_B',
     'split_brand_C',
     'color_black',
     'category_C1',
     'product_group_clothing',
     'silhouette_t_shirt_top',
  ],
  [...]
  ]

where you find a query, a sku that was acquired by the user doing the query and a few attributes of the SKU. My idea was to do a very basic model based on word2vec where I could find similar things together.
In a simple way, if I search for t-shirt on the model I would expect to have t-shirt SKUs near the query.
I try to use gensim (I'm new to this library) with different attributes to build a model:
from gensim.models.callbacks import CallbackAny2Vec

class callback(CallbackAny2Vec):
    '''Callback to print loss after each epoch.'''

    def __init__(self):
        self.epoch = 0
        self.loss_to_be_subed = 0

    def on_epoch_end(self, model):
        loss = model.get_latest_training_loss()
        loss_now = loss - self.loss_to_be_subed
        self.loss_to_be_subed = loss
        print('Loss after epoch {}: {}'.format(self.epoch, loss_now))
        self.epoch += 1

model = Word2Vec(
  sentences=sentences,
  vector_size=100,
  window=1000,
  min_count=2,
  workers=-1,
  epochs=10,
#   negative=5,
  compute_loss=True,
  callbacks=[callback()]
)

I got this output:
Loss after epoch 0: 0.0
Loss after epoch 1: 0.0
Loss after epoch 2: 0.0
Loss after epoch 3: 0.0
Loss after epoch 4: 0.0
Loss after epoch 5: 0.0
Loss after epoch 6: 0.0
Loss after epoch 7: 0.0
Loss after epoch 8: 0.0
Loss after epoch 9: 0.0

All losses of 0!!!
I start to get very suspicious at this point.
Note: Each element of sentences are independent, I hop the library don't try to mix different terms in different arrays.
For trying to test the model, I tried a very frequent query like model.wv.most_similar('query_t-shirt', topn=100) and the results are completely absurd.
Is my idea crazy or am I using incorrectly the library?

A: workers=-1 is not a valid parameter value. If there's an example suggesting that negative-count somewhere, it's a bad example. If you got the impression that would work from something in Gensim's official docs, please report that documentation as a bug to be fixed.
More generally: enabling logging at the INFO level will show a lot more detail about what's happening, and something like "misguided parameter that prevents any training from happening" may become more obvious when using such logging.
Separately:

*

*The Word2Vec loss-tracking of Gensim has a lot of open issues (including the failure to tally by epoch, which your Callback tries to correct). I'd suggest not futzing with loss-display unless/until you've already achieved some success without it.

*Such a low min_count=2 is usually a bad idea with the word2vec algorithm, at least in normal natural-language settings. Words with so few occurrences lack the variety of contrasting usage examples to achieve a generalizable word-vector, or, individually, to influence the model much compared to the far-more-numerous other words. But such rare words are, altogether, quite numerous - essentially serving as 'noise' worsening other words. Discarding more such rare words often improves the remaining words, and overall model, noticeably. So, if you have enough raw training data to make word2vec worth applying, it should be more common to increase this cutoff higher than the default min_count=5 than reduce it.

*For recommendation-like systems being fed by pseudotexts that aren't exactly natural-language-like, it may be especially worthwhile to experiment with the ns_exponent parameter. As per the research paper linked in the class docs, the original ns_exponent=0.75 value, which was an unchangeable constant in early word2vec implementations, might not be ideal for other applications like recommender systems.


text:
Q: Connection refused with mercurial through Kallithea I have been working on a server repository running through Centos 7, I installed mercurial and Kallithea and make the proper configuration to launch through apache and all correct, the problem is as follows, always I connect from Mac OS X, my machine, and execute a hg clone {url}\{repo_name} I get a nice abort: error: Connection refused first of all, this cannot be a problem of firewall or credentials because is properly configured and I try in another machine, specifically, a VM with Windows 8.1 and there's no problem of cloning/commit/pushing at all, in some way it must be a problem with mercurial (with git repos I have no problem of cloning) What could be wrong? I don't know where to search for an specific log for that matter and this error is driving me nuts all the week...
Regards!


text:
Q: Regex allow only one (possibly repeated) char from a given character class I need to check if a string contains only one distinct char from a given character class. Some simple examples:
"aa", "bbbbb", "c" match this regex [abc]+, but the regex matches also "abbb" or "abcbb" which are not valid in my case. Therfore i can't use it.
Sample code:
String[] input = {"a", "aaa", "ab", "b", "bbbb", "abc", "ccc"};
for(String str :input){
    if(str.matches("[abc]+")){
        System.out.println(str + ": valid");
    }
    else {
        System.out.println(str + ": not valid");
    }
}

The above will print valid for each string from the input array, which is not what I want. Valid inputs are only strings with distinct chars. I can achieve it with the following way , where i need to use multiple or in the if statement.
for(String str :input){
    if(str.matches("[a]+")||str.matches("[b]+")||str.matches("[c]+")){
        System.out.println(str + ": valid");
    }
    else {
        System.out.println(str + ": not valid");
    }
}

How can I achieve the same result as second aproach but write it compactly, because this will not be readable when the character class grows and there are changes in the character class I need to change the if condition?
Expected:
a: valid
aaa: valid
ab: not valid
b: valid
bbbb: valid
abc: not valid
ccc: valid

A: You can use \1 (escaped as \\1) to reference the first subgroup's match, so something like:
^([a-z])\1+$

.. would match a-z followed by itself at least once as the only characters in the string (the ^ and $ might be implicit with .matches, I'm not too familiar with Java specific issues with regexes).
You then need one additional check to see if the string has the length of 1 and contains a-z (if you want to avoid allowing 1, 2, etc. and other special characters).

A: See "Repeating Character Classes" in https://www.regular-expressions.info/charclass.html
TL;DR; ^([a-z])\1*$
Note: Thar be dragons, depending on quoting strength you may need to double escape the backslash: ^([a-z])\\1*$


text:
Q: Can't make populate in mongoose returning null Im trying to create a FoodItem Schema In which i kept measureUnit as an object reference from another page's model.
This is MeasureTypesSchema where the measureUnit is present. MeasureTypes is a embedded array document inside MetricsSchema. I am exporting both MeasureTypesSchema's model (MeasureTypes) and MetricsSchema's model (Metrics).
var mongoose = require('mongoose');
Schema = mongoose.Schema;

var MeasureTypesSchema = new mongoose.Schema({
measureUnit:{type:String,required:true},
code:{type:String,required:true}

});
var MeasureTypes = mongoose.model('MeasureTypes', MeasureTypesSchema);
module.exports = MeasureTypes;

var MetricsSchema = new mongoose.Schema({
organisation:{type: Schema.Types.ObjectId, ref: 'Organisation'},
MeasureTypes:[MeasureTypesSchema]

});
var Metrics = mongoose.model('Metrics', MetricsSchema);
module.exports = Metrics;

This is FoodItemSchema where i kept measureUnit as an object reference from MeasureTypes model present in another page
var mongoose = require('mongoose');
Schema = mongoose.Schema;

var FoodItemSchema = new mongoose.Schema({

measureUnit:{type: Schema.Types.ObjectId, ref:'MeasureTypes',required:true},

});

var  FoodItem = mongoose.model('FoodItem', FoodItemSchema);
module.exports =  FoodItem;

I need to get the details of measureUnit when i populate, how to populate so that i get the details of measureUnit.

A: I tried populating measureUnit from FoodItem and got a null.
FoodItem.findById(foodId).lean().populate({path:'measureUnit'}).exec(function (err, food)
{ console.log(food);}

The result i got for this populate is
{
"_id": "5440d008b9215ace25587835",

"measureUnit": null,

"__v": 0
}

A: It sounds as though your models are spread across different files. In principle this is fine, but the entire model should brought together so that the whole application has access to it.
In applications main file (typically app.js) you bring in your database connection and model
var db = require('./model/db')

In /model/db.js you can connect to your database and import a number of schema files:
// Bring Mongoose into the app
var mongoose = require( 'mongoose' );

// Build the connection string
var dbURI = 'mongodb://localhost/ConnectionTest';

// Create the database connection
mongoose.connect(dbURI);

// BRING IN YOUR SCHEMAS & MODELS
// For example
require('./metrics');
require('./fooditems');

In each of your schema files you require Mongoose, define your schemas and build model, for example:
var mongoose = require('mongoose');

var MeasureTypesSchema = new mongoose.Schema({
  measureUnit:{type:String,required:true},
  code:{type:String,required:true}
});

mongoose.model('MeasureTypes', MeasureTypesSchema);

I haven't tried defining referenced schemas in separate files; if this continues to cause problems I'd try putting them all into the same file.
Finally on pages you want to use your models, require Mongoose and import the model again.
var mongoose = require( 'mongoose' ),
    MeasureTypes = mongoose.model('MeasureTypes');

For more info and background take a look at my blog post on Mongoose connections and usage: http://theholmesoffice.com/mongoose-connection-best-practice/


text:
Q: Copy from one workbook to another with specified dates I'm attempting to input the dates, then filter the data based on these two dates. I was able to figure out how select the desired dates but no luck in filtering. Also, is there any chance I can clear all the filters before it filters for the date? This workbook is used by a lot of people and I want to make sure that the date is only thing that is filtered.
The error is: Run-Time error '1004' Autofilter method of Range class failed
My issue is with rngfull .Autofilter line
Here is my code:
  Public Sub CreateSubsetWorkbook(StartDate As String, EndDate As String)

        Dim wbkInput As Workbook, wbkOutput As Workbook
        Dim wksInput As Worksheet, wks As Worksheet, wksOutput As Worksheet
        Dim lngLastRow As Long, lngLastCol As Long, lngDateCol As Long
        Dim rngFull As Range, rngResult As Range, rngTarget As Range
        Dim Lastrow As Integer
        lngDateCol = 2
        Set wbkOutput = ThisWorkbook
        Set wbkInput = Workbooks.Open("f:\Sharta\red files\DBr\(NEW SERVER) with Macro.xlsm")
        Set wksInput = wbkInput.Sheets("Sheet1")

            With wksInput
                Set wksOutput = wbkOutput.Sheets("Data Dump")
                Set rngTarget = wksOutput.Cells(1, 1)

                lngLastRow = .Cells.Find(What:="*", LookIn:=xlFormulas, _
                                     SearchOrder:=xlByRows, _
                                     SearchDirection:=xlPrevious).Row
                lngLastCol = .Cells.Find(What:="*", LookIn:=xlFormulas, _
                                     SearchOrder:=xlByColumns, _
                                     SearchDirection:=xlPrevious).Column
                Set rngFull = .Range(.Cells(1, 1), .Cells(lngLastRow, lngLastCol))

                With rngFull
                    Range.AutoFilter Field:=lngDateCol, _
                                Criteria1:=">=" & StartDate, _
                                Criteria2:="<=" & EndDate

                    Set rngResult = rngFull.SpecialCells(xlCellTypeVisible)
                    rngResult.Copy Destination:=rngTarget
                End With

                .AutoFilterMode = False
                If .FilterMode = True Then
                    .ShowAllData
                End If
            End With

        wbkInput.Close Savechanges:=False
        wksOutput.Activate

    End Sub


text:
Q: Buffering in QGIS3 is returning giant circles I'm trying to buffer some lines in QGIS. However, the result I'm returning are giant circles. I've tried several different CRS and made sure the project and layer had the same CRS but the result is still the same. The CRS is also not decimal but meters. Not sure what I'm missing.
Any suggestions?


text:
Q: Can tsconfig.json be placed inside package.json? Just like babel.rc?
Or maybe its contents can be imported into webpack.config.js?
{
  "name": "Foo",
  "version": "1.0.0",
  "babel": {
    "presets": [
        "@babel/preset-env"
    ],
    "plugins": [
        ["@babel/plugin-proposal-decorators"]
  },
  "tsconfig": { ... },
}

A: No, there is no official support. However, there is github issue for this feature.


text:
Q: Group and aggregate a list of objects I have a list of data structured like this:
Field1  Field2  Field3
1   1   "abc"
1   1   "def"
1   2   "123"
1   2   "456"

I want to be able to merge this data so I end up with a single record per Field1 & Field2 and with the Field3 data concatenated. So in the above case I would get:
Field1  Field2  Field3
1   1   "abcdef"
1   2   "123456"

I would like to use linq/query expressions for this.

A: var query =
    from row in rows
    group row by new { row.Field1, row.Field2 } into g
    select new RowClass
    {
        Field1 = g.Key.Field1,
        Field2 = g.Key.Field2,
        Field3 = g.Aggregate(
                    new StringBuilder(),
                    (sb, grp_row) => sb.Append(grp_row.Field3))
                  .ToString()
    }