Q:

Finding a basis for the set of polynomials where f(1)=f(-1)=0

I have the vector space $V$ above that belongs to $\mathbb{F}$, and $V$ is the group of all polynomials that are of degree $3$.
$W= \{ p \in V | p(1)=p(-1)=0\}$
1.) Prove that W is a subspace of $V$.
A.) Ok let's prove that the space isn't empty.
Let's take $p(x)= 0$, and this satisfies the condition of $p(1)=p(-1)=0$
B.) Now that the sum of two vectors in $W$ belong in $V$
Let's take two polynomials that satisfy $W$ and show that their sum belongs in $W$. This is pretty trivial since you can't go increase your degree from addition.
Let's take $p_1(x)=x_1^3-x_1^2-x_1+1$ and $p_2(x)=x_2^3-x_2^2-x_2+1$.
Their sum belongs in $V$.
Let's check multiplication by a scalar $\lambda \in \mathbb{R} $(also pretty trivial):
$p(\lambda x)=\lambda x^3-\lambda x^2-\lambda x+1 = \lambda p(x)$
Now onto the basis:
My thought process is that I might need to find a basis that contains at least 4 components (since $\mathbb{R}_3[x]$ contains 4 components), which I don't think is correct.
So far I have two components:
B= $\{ (x^2-1),(x(x^2-1))\} $
This is where I'm stuck and can't find anymore polynomials that satisfy the requirement.
TL;DR
1.) Is my thought process for proving that $W$ is a subspace of $V$ correct?
2.) How can I find a basis for $W$? Is there a simpler way using a system of equations rather than brute force trial and error?

A:

$P(x)=ax^3+bx^2+cx+d$
$$\begin{aligned} p(1)&=a+b+c+d
  \\     p(-1)&=-a+b-c+d \end{aligned} $$
so $p(1)-p(-1)=0 $
$$ p(1)-p(-1)=a+b+c+d -(a+b-c+d)=2a+2c$$
2-d plane like x-y axis
your basis does work $\{x^2-1,x^3-x\}$
feel that grader would not like how you show it is a subspace. Do not use lambda it means to grader e-value. I seen a  peer get docked a whole letter grade for not using proper notation. Also, when closed under addition you used a particlar case this how I would do it
Closed add $p,g\in  W$ consider $h(x)=p(x)+g(x)$
$$
\begin{aligned} h(1)&=(p+g)(1)=p(1)+g(1)=0+0=0
              \\ h(-1)&=(p+g)(-1)=p(-1)+g(-1)=0+0=0
\end{aligned}$$
so $$ h(1)=h(-1)=0$$
closed under scalar mult $ap(1)=a(0)=0$and $ap(-1)=a*0=0$ so $ap(1)=ap(-1)=0$
lastly show $0\in W$ treating 0 like a poly $0(1)=0=0(-1)$


Q:

LINQ to Entities does not recognize the method group join

How to fix this error? And why it raising?

Additional information: LINQ to Entities does not recognize the method
  'System.Collections.Generic.List1[FRecipes.Models.Component]
  ToList[Component](System.Collections.Generic.IEnumerable1

public ActionResult ShowDishes(int id)
    {
        DishesWithCategory dish = new DishesWithCategory();
        dish.category = id;
        List<Item> Test = new List<Item>();
        var result1 = (
        from d in FRE.Dish
        join c in FRE.Component on d.DishID equals c.DishID into items
        select new Item { DishID = d.DishID, components = items.ToList() }
        ).ToList();

        return View();
    }

Models:
public class DishesWithCategory
{
    public List<Item> item { get; set; }
    public int category { get; set; }
}

public class Item
{
    public int DishID { get; set; }

    public string DishName { get; set; }

    public List<Component> components { get; set; }
}

public partial class Component
{
    public int ComponentID { get; set; }
    public int DishID { get; set; }
    public string AmountID { get; set; }
    public string NameID { get; set; }
}

A:

Try to replace this line:
select new Item { DishID = d.DishID, components = items.ToList() }

with this one:
select new Item { DishID = d.DishID, components = items }

The error is quite clear: ToList() function cannot be translated in that context.


Q:

C: Craps / Dice Game

Purpose of this code: simulate 100 games of CRAPS and record the # of first round losses, first round wins, second round losses PLUS points, and second round wins PLUS points.
Those of you not familiar with the rules of CRAPS; you basically roll two die, if the result is anyhting other than a total of 2, 3, or 12, you get to roll again (the number you rolled that turn is preserved and added to your points). If you roll a 7 or 11 you automatically win.
This is where i'm at so far:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

int main ()
{
int i,d1,d2,sumd,sumd2;
double winf = 0, lostf = 0, winp = 0, lostp = 0;
printf("This program will simulate the game of craps for 100 times.\n");

for (i=0; i<100; i++) {
    d1 = rand()%6+1;
    d2 = rand()%6+1;
    sumd = d1 + d2;

    if (sumd==7 || sumd==11) {
        printf("You rolled a 7 or an 11, you win.\n");
        winf++;
    }
    if (sumd==2 || sumd==3 || sumd==12) {
        printf("You rolled a 12, a 3, or a 2, you lose.\n");
        lostf++;
    }
    if (sumd==4 || sumd==5 || sumd==6 || sumd==8 || sumd==9 || sumd==10) {
        while (1) {
            d1 = rand()%6+1;
            d2 = rand()%6+1;
            sumd2 = d1 + d2;

            if (sumd2==sumd){
                printf("You rolled your points, you win.\n");
                winp++;
            break;}
            if (sumd==7){
                printf("You rolled a 7, you lose.\n");
                lostp++;
            break;}
        }
    }
}

printf("First roll wins: %lf, First roll loses: %lf, Second roll wins: %lf, Second roll loses: %lf. ", winf, lostf, winp, lostp);
}

All i ask of you is that you give me options on how i can preserve those points to be printed at the end??
Moreover, i feel my code could be written better and less redundantly, suggestions?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

int main ()
{
int i,d1,d2,sumd,sumd2;
double winf = 0, lostf = 0, winp = 0, lostp = 0;

printf("This program will simulate the game of craps for 100 times. Press any key to continue.\n");
//getchar();

for (i=0; i<100; i++) {
    d1 = rand()%6+1;
    d2 = rand()%6+1;
    sumd = d1 + d2;

switch(sumd){
    case 7:
    case 11:
        printf("You rolled %d, you win.\n", sumd);
        winf++;
        break;
    case 2:
    case 3:
    case 12:
        printf("You rolled %d, you lose.\n", sumd);
        lostf++;
        break;
    default:
        while (1) {
            d1 = rand()%6+1;
            d2 = rand()%6+1;
            sumd2 = d1 + d2;

            if (sumd2==sumd){
                printf("You rolled your points(%d), you win.\n",sumd);
                winp++;
            break;}
            if (sumd2==7){
                printf("You rolled a 7, you lose.\n");
                lostp++;
            break;}
        }
}

}
printf("First roll wins: %lf, First roll loses: %lf, Second roll wins: %lf, Second roll loses: %lf. \n", winf, lostf, winp, lostp);
}

A:

Your solution of putting the results in ints to print at the end looks reasonable.  If I'm understanding the question right, it seems winp and lostp should add sumd2 instead of just incrementing.  Or is it already working ok and I'm misreading the question?
You might also want to look at the switch statement:
switch(sumd){
    case 7:
    case 11:
        //existing code goes here
        break;

    case 2:
    case 3:
    case 12:
        //more existing code
        break;

    default:
        //code for games that don't end on the first turn
        break;
}


Q:

GPU reduction for billion-element array

I am trying to perform reduction with GPU, that is, to find a maximum value from all the elements of an array. There is a tutorial from Nvidia here, let's say slide 7 for the simplest method
The only problem I have is my array is huge! it can reach 4 billion elements. From the sample code in slide 7, there is a need to copy back-and-forth between block shared memory and global memory and the use of global memory to store all elements cannot be avoided in my current understanding. This storage exceeds 2GB of graphics card memory.
Is there any way to do this reduction with such huge arrays or is it current limits of graphics hardware?
PS: In future extended version, I also plan with much more than 4 billion elements

A:

Reduction is an operation which you can do in chunks.
The simplest solution would be to allocate two data buffers and two result buffers on the GPU, and then overlap transfer to the GPU with execution of the reduction kernel. Your CPU can reduce the output of successive GPU reductions while the GPU is busy. That way you can amortise most of the cost of data transfer, and the processing of the partial reduction results.
You can do all of this with the standard reduction kernel NVIDIA supply with the CUDA examples.


Q:

$_GET value in PHP script called by AJAX has previous value

I am developing a very simple shopping cart where each of the items (courts) in the store has a button next to it, a + if the item is not in the cart and an x if the item is in the cart.  When you click on the button I am submitting jQuery/AJAX/PHP to update the cart information and totals as well as change the button in the product list to an x, and vice versa.
Here is the product line in the store
<div id="courtline" class="courtline<?php echo $row_Courts['systemID']; ?>">
<a href="#" func="add" stateName="<?php echo $_SESSION['state'];?>" systemID="<?php echo $row_Courts['systemID'];?>" courtSystemID="<?php echo $row_Courts['courtSystem_SystemID']; ?>" userID="<?php echo $_SESSION['userid']; ?>" id="addCourtLinkADD" class="addCourtLinkADD" >

And here is my jQuery.  It makes 3 AJAX calls...

Update the database by adding or removing a product from the shopping cart...
Update the product list by changing the button to a + or x depending on whether the product is in the cart... it also changes the 'func' parameter to match the button.
update a totals div in the cart.

.
$(" #courtline" ).on( "click","a",function( e ) {
    e.preventDefault();
    var func = $(this).attr("func");
    var stateName =  $(this).attr("stateName");
    var courtID = $(this).attr("systemID");
    var userID = $(this).attr("userID");
    var courtSystemID = $(this).attr("courtSystemID");
    var stateID = $(this).attr("systemID");

    // update the court list in the cart
    $.ajax({

        type: "GET",
        url: "http://subscribe.docketlaw.com/ajaxphp/modifyCourt.php",
        data: "user= " + userID + "& court= " + courtID + "& courtsystem= " + courtSystemID + "& func=" + func,
        timeout: 6000,
        success: function (data)
            {
                $(document).ready(
                    function() {
                        courtList = data;

                        $('div.cartcourtlist').html(courtList);
    // now update the Court Line
        $.ajax({

            type: "GET",
            url: "http://subscribe.docketlaw.com/ajaxphp/refreshCourtLine.php",
            data: "user= " + userID + "& court= " + courtID + "& courtsystem= " + courtSystemID + "& statename=" + stateName + "& func=" + func,
            timeout: 6000,
            success: function (data)
                {
                    $(document).ready(
                        function() {

                            courtlinediv = data;

                            $('div.courtline'+courtID).html(courtlinediv);
            // now update the Totals
            $.ajax({

                type: "GET",
                url: "http://subscribe.docketlaw.com/ajaxphp/refreshTotal.php",
                data: "user=" + userID + "& court=" + stateID + "& statename=" + stateName,
                timeout: 6000,
                success: function (data)
                    {
                        $(document).ready(
                            function() {
                                totaldiv = data;

                                $('div.recurringtotal').html(totaldiv);
                            }
                        );
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert("Status refreshTotal: " + textStatus); alert("Error: " + errorThrown);
                    }
            });
                        }
                    );
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("Status refreshCourtLine: " + textStatus); alert("Error: " + errorThrown);
                }
        });

                    }
                );
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert("Status modifyCourt: " + textStatus); alert("Error: " + errorThrown);
            }
    });
});

The relevant code in modifyCourt.php.  It updates the cart information by adding or removing a product from the cart.
if ($_GET['func'] == 'add') {

// insert the court into the cart
$insertSQL = sprintf("INSERT INTO cart (sessionid, systemid, courttype) VALUES (%s, %s, %s)",
                       GetSQLValueString($row_Result['sessionID'], "text"),
                       GetSQLValueString($_GET['court'], "int"),
                       GetSQLValueString($_GET['courtsystem'], "int"));

mysql_select_db($database_docketData, $docketData);
$Result1 = mysql_query($insertSQL, $docketData) or die(mysql_error());

} else {

$deleteSQL = sprintf("DELETE FROM cart WHERE systemid=%s AND sessionid = %s",
                       GetSQLValueString($_GET['court'], "int"),
                       GetSQLValueString($row_Result['sessionID'], "text"));

  mysql_select_db($database_docketData, $docketData);
  $Result1 = mysql_query($deleteSQL, $docketData) or die(mysql_error());
}

Here is the relevant code from refreshCourtLine.php, which updates the button and the func attribute on the button.
refreshCourtLine.php
if ($_GET['func'] == 'add') {
    ?>  <a href="#" func="delete" stateName="<?php echo $_GET['statename'];?>" systemID="<?php echo $_GET['court'];?>" courtSystemID="<?php echo $_GET['courtsystem']; ?>" userID="<?php echo $_GET['user']; ?>" id="removeCourtLinkREMOVE" class="removeCourtLinkREMOVE" >

     <?php } else {
    ?>
    <a href="#" func="add" stateName="<?php echo $_GET['statename'];?>" systemID="<?php echo $_GET['court'];?>" courtSystemID="<?php echo $_GET['courtsystem']; ?>" userID="<?php echo $_GET['user']; ?>" id="addCourtLinkADD" class="addCourtLinkADD" >

    <?php }

So... when I click the add button, the product appears in the cart, the button changes to an x and the func attribute is changed to "delete", which is as expected.  However, if I click the new x button to remove that same product from the cart, it successfully removes the product from the cart, but it does not change the button back to a plus and does not change the func attribute.  Through investigation I've determined that when clicking the button that was generated through jQuery, the value for $_GET['func'] in modifyCourt.php is correct (which explains why the product is correctly removed from the cart) but in refreshCourtLine.php, the value of $_GET['func'] is the OLD value.
I've used alert throughout the jQuery and it always shows the value that is currently in the func attribute on the button, but once it goes into refreshCourtLine.php it goes back to the old value.
If I refresh the page, the buttons work as normal again.
I have a feeling it's an issue of scope, but I am confused as to why the first AJAX call to modifyCourt.php uses the new value of the func attribute but the second AJAX call to refreshCourtLine.php uses the old value.
sorry for being long-widnded and for the ugly code, but I would appreciate any help.

A:

Inside jQuery's AJAX success event, you don't have to wrap the rest inside $(document).ready(), since that event has already been fired when the top most parent document was ready.. So maybe that's the issue.
From the partial code it's unclear if there might be a problem around the $_GET['func'] retrieval in refreshCourtLine.php. You can try to 'vardump()' the $_GET['func'] before the if to see what state it is in (is it set? what value? etc)
Furthermore, you use courtline as the ID of the div and a customized coutline[ID] as the class name. Why not switch those? So each item has a unique ID and a general class name. In this way, the items are easy to tell apart for the script.
So: id="courtline" class="courtline<?php echo $row_Courts['systemID']; ?>" should become class="courtline" id="courtline<?php echo $row_Courts['systemID']; ?>" and the jQuery selectors in your AJAX function should be changed as well. ( $('#courtline' + courtID ) )
Also, use data- attributes instead of custom ones in your HTML. Browser can handle them better. And us jQuery's .data('attributename') to get the values.
Be aware that your click event binding refers to the anchor inside the DIV, so when you want to replace the link, use jQuery's .replaceWith( '' ) to replace it's HTML with the new link. (Because .html( .. ) replaces the HTML inside the element, so not the A-tag itself.)
Important: please use PHP's MySQLi functions instead of the deprecated mysql_query etc. Have a look at the PHP documentation in that.
Also use mysqli's prepared statements for safety :)
Example for a working front-end part: https://jsfiddle.net/PhilQ/v3ng3ejt/2/


Q:

How large is the number of all phonetic entities across all spoken languages?

Based on scientific (calculations in) literature, how many different "sounds" are there to be found across all languages of which the pronunciation is known?
I think tones, and a fortiori dialects, will further complicate the matter. The need for systematics and standards in language and their phonetics thus becomes apparent, when embarking on a counting endeavour.
Perhaps even the possible amount of sounds which can be produced by the structural make-up of our body, has been systematically analysed in a biological-linguistic inquiry?

A:

The answer depends foremost on what exactly you mean by "a sound", which could be counted. For example, the consonant [ʕ] is found in Arabic, Tigre, Somali, Chechen and a number of other languages. However, the exact pronunciation differs, so that [ʕ] in Moroccan Arabic isn't phonetically the same as it is in Levantine Arabic. Aspirated stops differ quite considerably in how much aspiration there is (e.g. in Navaho they are very aspirated but in (related) Apache, not so much. If you are looking for fine-grained phonetic differences, the answer would be along the lines of "unlimited" (or at least unknowably huge).
On the other hand, if you are looking at phonemes, the answer is more computable. Although English phonetically has alveolar t (the regular case) and dental [t̪] (in "width"), this is an automatic feature of English pronunciation (or possibly universally required). However, [t] versus [t̪] is a phonemic choice in some languages (Ekoti). The IPA is a conventional system for writing all such phonemic distinctions in languages. You can start calculating from a chart like this (I warn you however that that is an unofficial homebrew version, and one should always consult the official version. In fact, the Wiki page for IPA is on the verge of being offensively misrepresentative). So for plain voiceless stops, you have [p t̪ t ʈ c k q]. Any of these can have rounding as a secondary articulation (notated in IPA as ʷ), and many can have palatalization (ʲ). Additionally, you can have differences between plain, aspirated, and ejective stops (p, pʰ, p') – so you have 7x2x3 i.e. 42 kind of voiceless stops (there are other properties that have to be considered, and a question of whether there is such a difference as [kʲ] versus [c], or [qʲ] at all). You can basically triple that number to include voiced and nasal consonants, and then there are fricatives and so on.
IPA has 28 vowel symbols (this is a proper vowel chart). Any one of these can be modified by diacritically-indicated additional properties, such as nasalization, or creakiness vs. breathiness (the former can theoretically combine with either of the latter but the last two are mutually exclusive), which gives 28x2x3 vowels; then we can add length (2 or maybe 3 categories) and tone (errrm, that's a big number).
One problem you run into is the attestation gap. For example as far as I know, no language has [ʏ̤] (breathy lax [y]), which probably means we just haven't found it, since breathiness is not a very common phonetic feature. A related problem is that some of the odd sounds have an unclear phonetic and phonemic status. Clicks are a good example: some of the Khoisan languages like Taa have a huge number of click distinctions, so [kʘ kʘʰ* ɡʘ ɡʘh ɡʘqʼ kʘʼqʼ ɡʘx ...]. Some of these clearly fall within the purview of normal voicing / aspiration / nasalization distinctions, but there seem to be inconveniently more kinds. The "velar fricative release" click [ɡʘx] might be a consonant cluster of [ɡʘ] plus [x], and there isn't any clear way to determine if that is correct / wrong.
This at any rate gives one an initial basis for computing "possibilities". The biggest impediment to giving a concrete number is that there are many rare phonetic properties attested especially in languages with few speakers (under 100,000), but not a lot of clear, probative data as to what distinctive properties there are. As for the question of a theory of such oppositions, starting with Roman Jakobson at the end of the 1940's and at least until 1995-ish, sounds have been analysed into a system of independent features, where (in one standard system - the last standard), [p] is [+consonantal, -sonorant, -syllabic, -voice, -continuant, +anterior, -coronal...]. That system (Sound Pattern of English) has about 24 features (it does not actually say explicity which things are or are not features, and it proposes distinctions that nobody adopted). That gives a mathematical upper limit (around 16 million) which is certainly vastly more than anyone has actually observed. The underlying theory is that these specific properties are part of our biological faculty of language.
An alternative approach is that the biological faculty of language has simply the notion "feature", and a general relationship between "feature" and aspect of language (i.e. rule or phonemic distinction – rules operate in terms of feature values, sounds are distinguished in terms of features), but there is no actual substance of the features (i.e. nothing in the theory of grammar requires you to know that the sounds participating in a rule are produced by lowering the velum, or protruding the lips).


Q:

How can I have 2 different images seamlessly tile with each other?

If I Google for "seamless tile" I can find many great answers to create a single image that will seamlessly tile with itself. GIMP even has a filter that will automatically make an image seamless in 1 click, and it works surprisingly well.
But for my game, I would like not only 1 image to tile with itself. But I would like to have different variations of that tile, so the whole texture looks less boring. I want, for example, 10 different grass textures, 10 different dirt textures. Not only should grass01 tile seamlessly with grass01. But grass01 should tile seamlessly with grass02 and dirt08.
One great example of a game that does this is Starcraft. Even the original Starcraft from 1998 has this system where they have multiple grass textures that all seamlessly tile with each other. How do they do that?

A:

Basically, I think what you do is first of all create a tile for each of your terrain types that seamlessly tiles with itself. As you said there are many tutorials available on how to do this.
Once you have those tiles, you can draw variants as well as transitions between different types of terrain by modifying copies of them. The only thing you need to make sure to avoid is changing the borders of the image, since you need those to seamlessly connect to neighbouring tiles.
Of course, when you're drawing transition tiles, you may start with a tile that has half of it filled with each type of terrain and then you need to make it look good. In this process you'll often end up modifying the edges a bit anyway where the terrains meet up. However, transition tiles are quite specific cases so you only need to make sure these sides still connect seamlessly to only a handful of other tiles.


Q:

WAMP: Apache refusing connections outside the network

I have wamp installed. I ran the server, everything is running fine from localhost and my local ip address. I forwarded port 80 on my router. Whenever I try to access the server from the outside, using my real ip, it doesn't work and timeouts.
I though port forwarding is not working, forwarded another port for different service and it went through, so the problem is with apache. I checked the error log, didn't find any errors. Skype is off. Any tips what could be causing this? Thanks!

A:

Did you check windows firewall to see if it allows access to port 80? Also, can you try from another machine on the same subnet behind the same router?


Q:

Android get value of any column from any cursor giving the corresponding id

I have created Cursor from any database table. It consists value of _id and corresponding name. For further operation, I need the value of "name" for any specific "_id". How it is possible using the Cursor.

A:

String selecttSqlStr2 = "SELECT * FROM Tablename  WHERE TRIM(QST_Id) = '" + _id;

Cursor c = datasource.execSelectSQL(selecttSqlStr);//datasource is object for opening database
c.moveToFirst();
String name=c.getString(c.getColumnIndex("name"));


Q:

Sharepoint Hosted Permission (SP 2013)

I am developing a test REST app currently, the app is sharepoint hosted and is being developed and deployed to the SP site without Sharepoint installed on my Machine.
The app is meant to take in a query param that is a title of a list or a guid and search the SP site for the list and return the contents of the list.  Is set up the query call and generated the URLs correctly but when I requested Search permission within the App Manifest to be set to "QueryAsUserIgnoreAppPrincipal", upon deployment to the site I receive a prompt to trust the app with the error Sorry, only tennant administrators can add or give access to this app.
The "Trust it" option cannot be selected, can anyone shed some light on this issue as to why I am getting this error?
-Thanks

A:

For some of the permissions like Search , User Profile Service, Social Capabilities etc, you need to be tenant admin and not just site collection admin.
For more details on this topic please check the following msdn articles
App Permissions in SP 2013
Search apps in SP 2013
So basically, you need to login from tenant admin account and then "Trust" the app.


Q:

Get CSS property values from a component's "style" prop

I'm writing a React Native component for a library and I want users to be able to style it using the style property, just like React.View and other built-in components.
However, since my component is actually made up of a few nested views, I need to do some calculations to figure out what styling to put on the inner ones. For example, I might need to adjust the sizing of an image based upon the thickness of a border around it, or adjust a highlight color based upon the given text color, or in some other way infer some piece of styling from another piece of styling.
To do this, I need to be able to extract the actual CSS properties (like borderWidth: 2 or backgroundColor: 'pink') out of whatever gets passed as the style prop. This is fine as long as it comes as a plain object, but it may also be the result of a call to React.StyleSheet.create. This seems to be an opaque object with all selectors simply mapped to numeric IDs.
How can I resolve these and get the actual CSS properties, in order to do anything more complicated with them than simply passing them straight on to a View?

A:

The built-in StyleSheet.flatten function (or the identical flattenStyle function) can turn anything that can legitimately be passed to the style prop into an object mapping CSS property names to values. It works on plain objects, IDs returned by StyleSheet.create(), and arrays.
Example usage to check the width specified in the style prop from within a Component definition:
import { StyleSheet } from 'react-native'

// ... then, later, e.g. in a component's .render() method:

let width = StyleSheet.flatten(this.props.style).width;


Q:

linux C server - identifying / naming the client

By hostname, I mean the name of the PC of the client.
I'm trying to identify each of the connected client of the server.
Like client -> server. Server says: client hostname has connected.
then all the process by that client will be tagged with the hostname.
And I don't really know how to.
My client code:
char hostname[1024];

gethostname(hostname, 1023);
send(sock, hostname, hostname, 0);
//now we are done sending the hostname of the client.

My server code (the loop):
void clients (int sock)
{
    int n, p;
    char buffer[256];
    char request;
    FILE *file;
    file = fopen("process.log","a+");

    //the stuff i added for the identification
    char hostbuf[256];
    bzero(hostbuf,256);
    n = read(sock,hostbuf,255);
            printf("%s has connected.\n",buffer);

    //after the client has been identified then we tag all communications from that client as its hostname/identification.

    do
    {
    bzero(buffer,256);
    p = read(sock,buffer,255);
    if (p < 0) error("ERROR reading from socket");

    //the output i modified
    printf("%s sent: %s\n",hostbuf,buffer);

    n = write(sock,buffer,sizeof(buffer));

    if (n < 0) error("ERROR writing to socket");
    fprintf(file,"%s\n",buffer); /*writes*/

    }while(p == 11);

    fclose(file);
}

----------- edit -----------
Used both suggestions together
Added to code:
socklen_t len;
struct sockaddr_storage addr;
char ipstr[INET_ADDRSTRLEN];
int port;

   len = sizeof addr;
   getpeername(sock, (struct sockaddr*)&addr, &len);

   // deal with both IPv4 and IPv6:
if (addr.ss_family == AF_INET) {
  struct sockaddr_in *s = (struct sockaddr_in *)&addr;
  port = ntohs(s->sin_port);
  inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof ipstr);
} else { // AF_INET6
  struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addr;
  port = ntohs(s->sin6_port);
 inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof ipstr);
}

char host[1024];

   getnameinfo(&addr, sizeof addr, host, sizeof host, NULL, NULL, 0);

tried to display it:
printf("%s has connected from %s.", host,ipstr);
    //returned 'myip.myisp.net has connected from *.*.*.*.'
    //i want it to return my PC name.
    //my pc name is SashaGre-PC :))

It works but it doesn't return my PC name but rather the 'ip.ispdomain.net'.

A:

Additionally, if you want the host name of the client, use getnameinfo from the server each time you get a new client connection in accept. There are examples here:
https://beej.us/guide/bgnet/html/multi/getnameinfoman.html
For windows: http://msdn.microsoft.com/en-us/library/windows/desktop/ms738532(v=vs.85).aspx


Q:

Ruby's :yields:

I was looking through some tab-completions that were automatically set up for my editor, and I found one where y was mapped to:
:yields: arguments

What is this syntax called, when, where, how and for what  is this used?

A:

This is one of the many directives supported by the RDoc documentation tool. It is used to document the arguments that get passed to a block.


Q:

Migrating database from rails to django app in heroku

I need to migrate my database from rails to django in heroku... Its a postgresql database for both on heroku. The issue is that the table names and field names are different on both databases for rails and django. Is there any plugin on heroku to help do this?

A:

Since the models are not pre-defined in frameworks, I can not imagine how can there be any generic plugin to migrate data from one to another automatically.
Tthe migration problem between frameworks is quite different from, say, joomla to wordpress migration, where you have to deal with pre-defined tables.
in a FrameworkA > FrameworkB migration, what you need to do is to write custom code (in sql or python) to fetch data from your RoR project and insert into your Django project.


Q:

iOS 7 Change Carrier name/logo without Jailbreak

I know it was possible in iOS 6 to change the carrier name (or logo) displayed in the status-bar.
Is there any way to do so in iOS 7, without jailbreaking the phone?

A:

You can use Carrier Editor

CarrierEditor allows you to customise your iOS device’s carrier logo
Works on Mac OS X 10.6 or greater on any iOS without a jailbreak, but limited to devices that support a carrier.

CarrierEditor generates a modified version of a carrier update onto your desktop and you simply use iTunes to install it.


Q:

Apache 2.4 php 7.2 Apache ( php module) increase max connections to handle 10000

I have project with apache(2.4) and php(7.2), which apache uses mpm_fork
how can I increase max connections in apache to handle 10,000 cocurrent connections
?
I'm testing with https://loader.io , It just can handle max to 5000 concurrent connections ( in 15 s ).
this is my current apache config :
DefaultRuntimeDir ${APACHE_RUN_DIR}
Timeout             300
<IfModule prefork.c>
    StartServers            100
    MinSpareServers         100
    MaxSpareServers         100
    ServerLimit             10000
    MaxClients              10000
    MaxRequestWorkers       10000
    MaxRequestsPerChild     4000
</IfModule>
PidFile ${APACHE_PID_FILE}
KeepAlive On
MaxKeepAliveRequests 1000
KeepAliveTimeout 5
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
HostnameLookups Off
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf
Include ports.conf
<Directory />
        Options FollowSymLinks
        AllowOverride None
        Require all denied
</Directory>
<Directory /usr/share>
        AllowOverride None
        Require all granted
</Directory>
<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

AccessFileName .htaccess
<FilesMatch "^\.ht">
        Require all denied
</FilesMatch>

LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

IncludeOptional conf-enabled/*.conf
IncludeOptional sites-enabled/*.conf
ServerName localhost

consider, there is no problem with my hardware,
I checked my resource usage, I never passed 20 % usage of cpu and memory during my tests.

A:

The best tuning I found for Apache which already working on my server perfectly is this part :
<IfModule prefork.c>
    StartServers            20
    MinSpareServers         20
    MaxSpareServers         50
    ServerLimit             5000
    MaxRequestWorkers       5000
    MaxRequestsPerChild     10000
</IfModule>

I belive this config is good for high traffic servers.


Q:

Ruby Variation with repeating buggy method

I need a method written in Ruby, which computes Variations. I have already written it in Java, but as I'm new to Ruby, there's just something I'm missing about the Ruby implementation.
The method is suposed to do this:
method(1, "01") => ["0", "1"]
method(2, "01") => ["00", "01", "10", "11"] ...so you get the idea.
note: in the Ruby impl, i give paralms like this : method(2, ["0", 1"]), but that's not an issue.
My Java impl :
public static List<String> Variations(int strength, String usableChars) {
    List<String> list =
        new ArrayList<String>((int) Math.pow(usableChars.length(), strength));

    if (strength == 0) {
        list.add("");
    } else {
        List<String> l = Variations(strength - 1, usableChars);
        for (char c : usableChars.toCharArray()) {
            for (String s : l) {
                list.add(c + s);
            }
        }
    }
    return list;
}

And it's working fine. But this is my Ruby implementation:
def Variation (strength, arrayOfString)
    array = Array.new(arrayOfString.size**strength)

    if strength == 0
        array << ""
    else
        a = Variation(strength-1, arrayOfString)
        for i in arrayOfString do
            for j in a do
                array << (i + j)
            end
        end
    end
    return array
end

In this i keep getting error message test.rb:10:in `Variation': can't convert nil into String (TypeError).

A:

In Ruby, arrays grow automatically as needed.  So change your array initialization from:
array = Array.new(arrayOfString.size**strength)

to
array = []

To enumerate over each character in a string, instead of
for i in arrayOfString do

do this:
arrayOfString.each_char do |i|

The final result:
#!/usr/bin/ruby1.8

def Variation (strength, arrayOfString)
  array = []
  if strength == 0
    array << ""
  else
    a = Variation(strength - 1, arrayOfString)
    arrayOfString.each_char do |i|
      for j in a do
        array << (i + j)
      end
    end
  end
  return array
end

p Variation(2, '01')    # => ["00", "01", "10", "11"]

each_char is in Ruby >= 1.8.7, or you can get it from the backports gem.


Q:

Can functions be default parameter values?

Kotlin docs states that "functions are first-class". I'm trying to use a function as a default value of a function extension. However the compiler isn't having any of it:
fun <T> identity(x: T): T = x
fun <T, P> Channel<T>.dedupe(by: (T) -> P = ::identity): ReceiveChannel<T>
{
    ...
}

The error is Function invocation 'identity(...)' expected which kinda indicates Kotlin isn't really understanding what I want to do at all.
Is there a way?

A:

I don't know why you get this error message, but the problem is type mismatch: the default value must make sense for any type parameters (subject to bounds). I.e. you need a (T) -> P, but ::identity can give you (T) -> T or (P) -> P.
Proof: if you change to
fun <T, P> identity(x: T): P = throw Exception()
fun <T, P> List<T>.dedupe(by: (T) -> P = ::identity): Unit {}

it compiles.
Answer (which came out in comments below):
If P is changed to Any?, we should be able to use ::identity because (T) -> T is a subtype of (T) -> Any?. Unfortunately, it doesn't work, but using a lambda instead of a function reference does:
fun <T> identity(x: T): T = x
fun <T> Channel<T>.dedupe(by: (T) -> Any? = { it }): ReceiveChannel<T>
{
    ...
}


Q:

Msg 102, Level 15, State 1, Line 2 Incorrect syntax near ','

whats wrong with following query?
insert into table values (
(1001749039, 2010-10-29, 6, 1015583, 'B-1002-PYA-001-CM',
 1062514, 2001422, 'y', 15.49, 2010-11-03, 'e', 2010-11-10, 3, 2010-11-10 )

A:

To start with you have an extra (.
You might want to use [Table] instead of table in your query(if your table name is "Table") as "Table" it is a sql keyword.
And, it wouldn't throw an error but you might want to enclose your date fields in quotes i.e. use '2010-10-29' instead of 2010-10-29 as SQL would interpret 2010-10-29 as 1971 if not enclosed in single quotes.

A:

You have 2 opening parenthesis and only 1 closing one, for starters.


Q:

Select difícil com data

Não estou conseguindo fazer o seguinte:como retornar o tempo em minutos ou horas que um determinado VALOR ocorreu na tabela abaixo? Exemplo: quanto tempo ocorreu o  VALOR maior que "23" no dia 01/05/2017? e se tiver intervalo entre os registros? por exemplo 5 minutos com valor 23 de manhã e 3 minutos com valor 23 a tarde? Tem como retornar separado isso, ou só o total?
 VALOR       HORA
23.77   2017-05-01 21:40:10
23.77   2017-05-01 21:40:11
23.77   2017-05-01 21:40:12
23.93   2017-05-01 21:40:13
23.87   2017-05-01 21:40:14
24.07   2017-05-01 21:40:15
24.07   2017-05-01 21:40:16
23.82   2017-05-01 21:40:18
23.87   2017-05-01 21:40:19
23.94   2017-05-01 21:40:20
23.85   2017-05-01 21:40:21
23.85   2017-05-01 21:40:22
23.78   2017-05-01 21:40:23
24.15   2017-05-01 21:40:24
23.73   2017-05-01 21:40:25
23.73   2017-05-01 21:40:26
23.68   2017-05-01 21:40:27
7.36    2017-05-01 18:40:28
7.34    2017-05-01 18:40:29
7.34    2017-05-01 18:40:31
7.32    2017-05-01 18:40:32
7.39    2017-05-01 18:40:33
7.4     2017-05-01 18:40:34
7.4     2017-05-01 18:40:35
7.41    2017-05-01 18:40:36
7.38    2017-05-01 18:40:37
7.11    2017-05-01 18:40:38
7.11    2017-05-01 18:40:39
7.34    2017-05-01 18:40:40
7.47    2017-05-01 18:40:56
7.54    2017-05-01 18:41:23

A:

Veja se é este o resultado esperado:
1- Encontrar a menor data depois que o valor é alterado. Ex:

23.77   2017-05-01 21:40:12
  23.93   2017-05-01 21:40:13
  houve alteração do valor, então a data seguinte ao valor 23.77 é 2017-05-01 21:40:13

Código:
  (select top 1
       x.data
   from medicoes x
   where x.valor != m.valor
   and x.data > m.data
   order by x.data)

2- Encontrar a menor data em que ocorreu aquele valor, agrupando pela última data conseguida anteriormente, e já calculando a duração em segundos entre a primeira e última data.
Código:
         select
             y.dia,
             min(y.data) as primeira_data,
             y.valor,
             y.ultima_data,
             datediff(second,  min(y.data),y.ultima_data) as duracao
          from
             (select
                  cast(m.data as date) as dia,
                  m.data,
                  m.valor,
                  (select top 1
                       x.data
                   from medicoes x
                   where x.valor != m.valor
                   and x.data > m.data
                   order by x.data) as ultima_data
              from medicoes m) y
              group by y.dia, y.valor, y.ultima_data

3- Listar cada dia, e somar as durações ocorridas por cada valor, tendo assim o resultado esperado.
Código:
select
    x.dia,
    x.valor,
    sum(coalesce(x.duracao,0)) as duracao_total_segundos
from
    (select
         y.dia,
         min(y.data) as primeira_data,
         y.valor,
         y.ultima_data,
         datediff(second,  min(y.data),y.ultima_data) as duracao
      from
         (select
              cast(m.data as date) as dia,
              m.data,
              m.valor,
              (select top 1
                   x.data
               from medicoes x
               where x.valor != m.valor
               and x.data > m.data
               order by x.data) as ultima_data
          from medicoes m) y
          group by y.dia, y.valor, y.ultima_data) x
group by x.dia, x.valor
order by x.dia, x.valor

Obs.: Coloquei um Coalesce na soma da duração, pois se não houver nenhuma data maior que a data do registro, o retorno da duração será null, fazendo com que a soma retorne null também. Logo, o último registro da tabela (por ordem de data) sempre terá duração 0 pois não é possível determinar quando aquele valor mudou.

Veja no SqlFiddle:
http://sqlfiddle.com/#!6/d5edb/46
Resultado:
dia         valor   duracao_total_segundos
2017-05-01  7.11    2
2017-05-01  7.32    1
2017-05-01  7.34    19
2017-05-01  7.36    1
2017-05-01  7.38    1
2017-05-01  7.39    1
2017-05-01  7.4     2
2017-05-01  7.41    1
2017-05-01  7.47    27
2017-05-01  7.54    10727
2017-05-01  23.68   0
2017-05-01  23.73   2
2017-05-01  23.77   3
2017-05-01  23.78   1
2017-05-01  23.82   1
2017-05-01  23.85   2
2017-05-01  23.87   2
2017-05-01  23.93   1
2017-05-01  23.94   1
2017-05-01  24.07   3
2017-05-01  24.15   1

Edit: Reparei depois que você pediu alguns filtros e outras opções, tipo: mostrar o turno, e o tempo em minutos ou horas, então...
Código atualizado e alterado para MYSQL:
select
x.dia,
x.valor,
x.turno,
sum(coalesce(x.duracao,0)) as duracao_total_segundos,
sum(coalesce(x.duracao,0))/60.0 as duracao_total_minutos,
sum(coalesce(x.duracao,0))/60.0/60.0 as duracao_total_horas
from
    (select
         y.dia,
         min(y.data) as primeira_data,
         y.valor,
         y.ultima_data,
         (UNIX_TIMESTAMP(y.ultima_data) - UNIX_TIMESTAMP(min(y.data))) as duracao,
         y.turno
      from
         (select
              cast(m.data as date) as dia,
              m.data,
              m.valor,
              (select
                   min(x.data)
               from medicoes x
               where x.valor != m.valor
               and x.data > m.data
               ) as ultima_data,
                (case
                  when hour(m.DATA)<12 then 'Manhã'
                  when hour(m.DATA)<18 then 'Tarde'
                  else 'Noite'
                  end ) as turno
                from medicoes m) y
          group by y.dia, y.valor, y.ultima_data,y.turno) x
group by x.dia, x.valor, x.turno
order by x.dia, x.valor;

Atualizei no SQLFiddle: http://sqlfiddle.com/#!9/705f6/12 (Obs. O Resultado é o da última query

A parte do Where, deixo com você.
Coloquei alguns dados a mais no fiddle para ter resultados com turnos diferentes.

Resultado:
dia         valor   turno   duracao_total_segundos  duracao_total_minutos   duracao_total_horas
2017-05-01  0       Manhã   10797   179.95      2.9991666666
2017-05-01  0       Tarde   17942   299.033333  4.9838888833
2017-05-01  7.11    Manhã   3       0.05        0.0008333333
2017-05-01  7.11    Noite   2       0.033333    0.00055555
2017-05-01  7.11    Tarde   3       0.05        0.0008333333
2017-05-01  7.32    Noite   1       0.016666    0.0002777666
2017-05-01  7.34    Noite   19      0.316666    0.0052777666
2017-05-01  7.36    Noite   1       0.016666    0.0002777666
2017-05-01  7.38    Noite   1       0.016666    0.0002777666
2017-05-01  7.39    Noite   1       0.016666    0.0002777666
2017-05-01  7.4     Noite   2       0.033333    0.00055555
2017-05-01  7.41    Noite   1       0.016666    0.0002777666
2017-05-01  7.47    Noite   27      0.45        0.0075
2017-05-01  7.54    Noite   10727   178.783333  2.9797222166
2017-05-01  23.68   Noite   0       0           0
2017-05-01  23.73   Noite   2       0.033333    0.00055555
2017-05-01  23.77   Noite   3       0.05        0.0008333333
2017-05-01  23.78   Noite   1       0.016666    0.0002777666
2017-05-01  23.82   Noite   1       0.016666    0.0002777666
2017-05-01  23.85   Noite   2       0.033333    0.00055555
2017-05-01  23.87   Noite   2       0.033333    0.00055555
2017-05-01  23.93   Noite   1       0.016666    0.0002777666
2017-05-01  23.94   Noite   1       0.016666    0.0002777666
2017-05-01  24.07   Noite   3       0.05        0.0008333333
2017-05-01  24.15   Noite   1       0.016666    0.0002777666


Q:

Filtering Comma Separated Data

My site has a bunch of widgets and i'm trying to filter them based on the url which is passed in. Say a Widget has the following structure:
public class Widget {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Urls { get; set; }
}

Where Urls is a comma separated list for the urls where the widget should be displayed, e.g.:

/, /Blog/, /Blog/123, /News/*

The asterisk after News indicates the Widget will be selected whenever the passed in url starts with /News/.
How could i modify the following method to filter the widgets based on my conditions above?
public IList<Widget> GetWidgets(string url) {
    return _session
        .Where(w => w.Urls.Contains(url))
        .ToList();
}

Ideally i'd like to use a linq query and it must only hit the database once. I'd appreciate the help. Thanks

A:

I managed to solve this by adding my own wild card match generator. See http://sentinel101.wordpress.com/2010/12/30/extend-nhibernate-linq-for-regex-matching/ for example of how to register the generator. Here's the generator incase anyone is interested:
public class WildCardMatchGenerator : BaseHqlGeneratorForMethod {
    public WildCardMatchGenerator() {
        var methodDefinition = ReflectionHelper.GetMethodDefinition(() => WildCardMatchExtensions.WildCardMatch(null, null, ','));
        SupportedMethods = new[] { methodDefinition };
    }

    public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) {
        return treeBuilder.Equality(treeBuilder.MethodCall("[dbo].[WildCardMatch]", new[] {
            visitor.Visit(arguments[0]).AsExpression(),
            visitor.Visit(arguments[1]).AsExpression(),
            visitor.Visit(arguments[2]).AsExpression()
        }), treeBuilder.Constant(1));
    }
}

And here is the WildCardMatch UDF:
CREATE FUNCTION [dbo].[WildCardMatch] (
    @Pattern NVARCHAR(MAX),
    @Input NVARCHAR(MAX),
    @Separator NVARCHAR(5)
)
RETURNS BIT
AS
BEGIN
    SET @Pattern = REPLACE(@Pattern, '*', '%')

    DECLARE @RtnValue BIT
    SELECT @RtnValue = CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END FROM [dbo].[Split](@Pattern, @Separator) WHERE @Input LIKE [Data]

    RETURN @RtnValue
END

And the Split function it calls (from http://blogs.microsoft.co.il/blogs/itai/archive/2009/02/01/t-sql-split-function.aspx):
CREATE FUNCTION [dbo].[Split]
(
    @RowData NVARCHAR(MAX),
    @Separator NVARCHAR(MAX)
)
RETURNS @RtnValue TABLE
(
    [Id] INT IDENTITY(1,1),
    [Data] NVARCHAR(MAX)
)
AS
BEGIN
    DECLARE @Iterator INT
    SET @Iterator = 1

    DECLARE @FoundIndex INT
    SET @FoundIndex = CHARINDEX(@Separator, @RowData)

    WHILE (@FoundIndex > 0)
    BEGIN
        INSERT INTO @RtnValue ([Data])
        SELECT Data = LTRIM(RTRIM(SUBSTRING(@RowData, 1, @FoundIndex - 1)))

        SET @RowData = SUBSTRING(@RowData, @FoundIndex + DATALENGTH(@Separator) / 2, LEN(@RowData))
        SET @Iterator = @Iterator + 1
        SET @FoundIndex = CHARINDEX(@Separator, @RowData)
    END

    INSERT INTO @RtnValue ([Data])
    SELECT Data = LTRIM(RTRIM(@RowData))

    RETURN
END

Lastly you'll need the C# implementation of the above UDF:
public static class WildCardMatchExtensions {
    public static bool WildCardMatch(this string pattern, string input, char separator = ',') {
        foreach (var str in pattern.Split(new char[] { separator }, StringSplitOptions.RemoveEmptyEntries)) {
            if (Regex.IsMatch(input, Regex.Escape(str.Trim()).Replace("\\*", ".*")))
                return true;
        }

        return false;
    }
}

Hope this helps.


Q:

Jquery: How to create a plain object with dynamic names?

I found in the docs that you can create an plain object like this:
var y = {
  name: "Pete",
  age: 15
};

However, I would like to add name and value dynamically to it, for example if we have something like:
<input type="text" name="$dynamicName" id="myinput">

That I can create an object like this:
var y = {
  name: "Pete",
  $('#myinput).attr('name'): $('#myinput).val(),
};

But this will throw an error:

SyntaxError: missing : after property id

How can I use $('#myinput).attr('name') as a name of a plain object?

A:

I think this is what you are wanting to do it will add the age item to the array and then set its value to whatever is in the textbox onclick.

var y = {
  name: "Pete"
 };
function go(){
 y[$('#myinput').attr("name")] = $('#myinput').val();
console.log(y)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"name="age" id="myinput">
<input type="button"  onclick="go(); return false;">

A:

Try using as an Array.
Like:
y[$('#myinput').attr('name')] = $('#myinput').val();
then you can access it as a simple object.


Q:

Why does heap sort have a space complexity of O(1)?

I understand that both quick sort and merge sort need O(n) auxiliary space for the temporary sub-arrays that are constructed, and in-place quick sort requires O(log n) auxiliary space for the recursive stack frames. But for heap sort, it seems like it also has a worst case of O(n) auxiliary space to build the temporary heap, even if the nodes are just pointers to the actual elements.
I came across this explanation :

Only O(1) additional space is required because the heap is built inside the array to be sorted.

But I think this means the original array necessarily already had to be implemented as some sort of tree? If the original array was just a vector, it seems memory for a heap would still have to be allocated.

A:

Data in an array can be rearranged into a heap, in place.  The algorithm for this is actually surprisingly simple., but I won't go into it here.
For a heap sort, you arrange the data so that it forms a heap in place, with the smallest element at the back  (std::make_heap).  Then you swap the last item in the array (smallest item in the heap), with the first item in the array (a largish number), and then shuffle that large element down the heap until it's in a new proper position and the heap is again a new min heap, with the smallest remaining element in the last element of the array. (std::pop_heap)
data:         1 4 7 2 5 8 9 3 6 0

make_heap:   [8 7 9 3 4 5 6 2 1 0] <- this is a min-heap, smallest on right

pop_heap(1): [0 7 9 3 4 5 6 2 1 8] <- swap first and last elements
pop_heap(2): 0 [7 9 3 4 8 6 2 5 1] <- shuffle the 8 down the heap

pop_heap(1): 0 1 [9 3 4 8 6 2 5 7] <- swap first and last elements
pop_heap(2): 0 1 [9 7 4 8 6 3 5 2] <- shuffle the 7 down the heap

etc

So no data actually needs to be stored anywhere else, except maybe during the swap step.
For visualization, here's that original heap shown in a standard form
make_heap
           0
     2           1
  3     4     5     6
               8   7 9
pop_heap
           8                           1                           1
     2           1               2           8               2           5
  3     4     5     6    ->   3     4     5     6    ->   3     4     8     6
                   7 9                         7 9                         7 9


Q:

Angular: How to avoid duplicate entries in localstorage

When I click on the heart button the data from that row gets stored in local storage but I want the data stored in local storage to be unique because when I click on the same row twice duplicate entry gets created in local storage.
I have attached a screenshot of local storage here you can see duplicate entries of a branch are stored in local storage.
here is the link to my code
https://stackblitz.com/edit/angular-ofvnz3?file=src%2Fapp%2Fhome%2Fhome.component.html
but you can't run this because of some import error. please solve it if possible.

A:

In your activeskill function... you're pushing the element (which is passed to the function) in value array without checking if it was already there... hence the duplication; to resolve this, check to see if the value already exists in the value array before you push;
relevant TS:
myFavArray: PeriodicElement[] = [];

  constructor() {
    if (localStorage.getItem('fav') == '' || localStorage.getItem('fav') == null) {
    } else {
      this.myFavArray = JSON.parse(localStorage.getItem('fav'));
      console.log('from localStorage', this.myFavArray);
    }
  }
  activeSkill(element) {
    let checkExists: boolean = false;
    for (var i = 0; i < this.myFavArray.length; i++) {
      if (element.position == this.myFavArray[i].position) {
        checkExists = true;
      }
    }
    if (checkExists == false) {
      this.myFavArray.push(element);
    }
    localStorage.setItem('fav', JSON.stringify(this.myFavArray));
  }

relevant HTML:

    <ng-container matColumnDef="position">
         No.

            <button  (click)="activeSkill(element)" mat-icon-button>
    <mat-icon aria-label="Heart">favorite</mat-icon>
 </button>

      {{element.position}}
  </ng-container>

  <ng-container matColumnDef="name">
     Name
     {{element.name}}
  </ng-container>

  <ng-container matColumnDef="weight">
     Weight
     {{element.weight}}
  </ng-container>

  <ng-container matColumnDef="symbol">
     Symbol
     {{element.symbol}}
  </ng-container>

minimal verifiable complete stackblitz here


Q:

No master volume in the new iPod Touch 5?

I used to have an iPod Touch 3, then I upgraded to the latest iPod Touch 5 a few weeks ago. I noticed that there is no master volume. For instance, now, when I am just browsing Safari, and I change the volume, it changes the volume for "sound effects" (background noises from notification). But when I open a game or listen to music, and I change the volume, this is for "games/music". So the two volume sliders are different.
This is new to me, but I'm sure that some of you have experienced this before. Perhaps it even existed in the iPod Touch 4 that I skipped? Anyway, is there a way to get back the master volume method that used to exist, where one slider would control the volume for everything?

A:

This separation of "sound effects" and "games/music" exists in iPod Touch 4 as well. There is no way for tuning a master volume on these devices. But you can set the "sound effects" volume as constant (Settings - Sounds - turn off Change with buttons) and pressing volume buttons will only change the "games/music" volume.


Q:

Create a new ec2 instance with ec2-classic option in VPC

I have machine in a VPC .
I ahve 2 question regarding this .
1) I want to move this machine from VPC to ec2-classic .
I read it somewhere its not possible . If thats correct then
2) I want to create a replicate a new instance with ec2-classic option but sad part is thats not coming even though some of my instances are configured witht hat option .

A:

OK. New accounts created in 2014 or later can only have EC2 VPC, that is why EC2 Classic is greyed out for you. So you cannot launch an instance in EC2 classic.
And you cannot move an instance from anywhere to anywhere once it is launched. You can take an AMI of an instance and launch a new instance out of the AMI in the desired VPC/subnet.


Q:

AutoLayout Understanding Multiplier

I have a problem with multiplier and cannot understand how this feature works. For example i have view has 6:1 multiplier(To SuperView.Leading) as below.

   When i change the multiplier to 2:1 it seems like below picture.

My question is in the 6:1 relation what does 6 and 1 mean. And also in 2:1 relation what does 2 and 1 mean. Similar consider you have three view like the picture below. Totally there 4 blank areas between subViews and superView. How can i say every blank area must be the SuperView.Width / 6 (and every blank width must be equal)

Thanks in advance.

A:

When working with autolayout, especially when you are working with proportional layouts, you have to use multiplier.
I have to explain here some mathematics.
We know straight line equation.
Y = Mx + C
In above equation. Assume M is your multiplier and C is your Constant.
Thus suppose you have superview (in case of iphone 6s plus) of
414(width) x 736(height) size. On that view suppose you created subview.
Now if you want subview size exacly half of superview size, then just drag two constraints from subview to superview. (i.e. Equal Width and Equal Height)
See this Image

Obviously now you will get an error. just like I'm getting. (See below Image)

Now click on both of the constraints one by one, and use multiplier as 0.5. Then use above straight line equation.
Here 0.5 means you want width of subview = superviewWidth / 2.0 i.e. 207 px.
In other words you can provide multiplier as 207:414 also.
Y i.e. subviewWidth = ((M i.e. 0.5) * (x i.e. 414 i.e. superviewWidth)) + (Constant i.e. Zero)
Finally you get subviewWidth = 207 px
Similarly do for height of subview. Provide multiplier 0.5 or 368:736.
When done all things, don't forget to click on subview and update frames.
This way constants and multiplier will works.

A:

In my example multiplier is 1:2 = 0.5
height red view is 0.5 times greater than the superview

A:

When it comes to the multiplier it depends on what constraints you are dealing with. You have the views leading constraint connected to the superview leading margin. When the constant is 0 that gives you an 8 points gap. When you change the multiplier you will be effecting that gap. That's why when you do 2:1 you see it go to the right 8 points. Essentially multiplying the original 8 point gap by 2. If you do 1:2 it will go from 8 points to 4 points, essentially dividing the original 8 point margin by 2.
Now when you look at Adrians example, he only multiplied it by 1:2 so how did that make it half of the entire screen? That's because he did that on the height constraint. The view was originally the full size of the superview, but when he multiplied it by 1:2, he indicated that he wanted it to be 1/2 of its original height. Giving you that end result.
So the important thing to understand is that multiplier may seem to act different depending on the situation but that's because it depends on what constraints you are dealing with.
here is a good answer that goes into this more:
Understanding multiplier in auto layout to use relative positioning
the link details how if you wanted to make the leading edge 10% and trailing edge 90% you would need to set both constraints in relation to the trailing edge.
Multiplying the trailing constraint by 0.9 and the leading constraints by 0.1.
In regards to your question about the equally separated views, you should use a stack view. They were made for situations like this so you didn't have to deal with all the constraints. You just need to set constraints for the stack view and configure it accordingly.


Q:

how to keep element open on jQuery accordion

I'm adapting the Responsly accordion from this site :http://dmmalam.github.io/Responsly.js/
This is working fine except that this automatically closes the preceding element when the next one is clicked. I want to keep each element open after the next one is clicked, unless the user specifically closes that preceding element.
(function( $ ){

$.fn.accordy = function( options ) {
var settings = $.extend({}, $.fn.accordy.defaults, options);

return this.each(function(index, container) {
  //Add callback to (un)collpase
  $(container).find('section hgroup').click(function(e) {
    $(this).parent().siblings('section').removeClass('accordion_current');
    $(this).parent().toggleClass('accordion_current');
    e.preventDefault();
  });

A:

after trial and error, this worked by taking out accordion_content from the line
    $(this).parent().siblings('section').removeClass('accordion_content');


Q:

pod's name from an environment variables defined in yaml

how can I create a yaml file for pod that get its name from a environment variables defined in yaml file.
I have tried this but it is not allowed.
metadata:
  generateName: $(HOSTNAME)
.
.
.

env:
  - name: HOSTNAME
            valueFrom:
              fieldRef:
                fieldPath: spec.nodeName

A:

Kubernetes allows you to set environment variables using the values of other fields in the Pod definition that are only available at the time the Pod is initiated.
In your example you tried to set spec.nodeName instead of metadata.name. You config should look something like this:
  env:
    - name: MY_POD_NAME
      valueFrom:
        fieldRef:
          fieldPath: metadata.name

Here you can find an official example of how to set it up.
Please let me know if that helped.


Q:

What happens to PHP file lock if the script times out or is terminated while the lock was on?

My question is best illustrated with this PHP code sample:
$file = fopen($filePath, "wb");
if($file !== false)
{
    //Obtain exclusive lock
    if(flock($file, LOCK_EX))
    {
        //Script times out or is terminated here
        //say, due to it using too much RAM, etc.
        //...

        //Release exclusive lock
        flock($file, LOCK_UN);
    }

    fclose($file);
}

What would happen to the lock?

A:

I just made a couple of tests on the following shared server:
PHP Version 5.4.34
Linux 3.12.35.1418868052 #1 SMP x86_64

And my conclusion is that file locks are released automatically once the script finishes running, even in case of a fatal error, a timeout or out-of-memory fault that terminates the script, or if I comment out flock($file, LOCK_UN); function.


Q:

What is the name of this springy type oscilloscope probe accessory?

Exactly what it says on the tin.

How is this pictured accessory called? The obvious place to look for a name would be the probe manual, but it looks like they decided to add the accessory to the package after making the manual, since it's not on the component list.

A:

It's a "Probe tip ground clip" (or something very similar like the examples below)
An example of it being named as such is here. It's called "Probe tip ground" here. It is also called a "Probe tip spring adapter" here.
Whatever it's exact name, I think the main thing is to have "tip" in there, as it differentiates from the standard ground clip by implying the clip is used at the probe tip.
Basically, it's function is to shorten the ground lead, as this lowers inductance and enables higher frequency signals to be displayed accurately.
Try it with a very fast rising signal, and compare it to using the normal ground clip and you will see the difference. A common mistake is using the wrong setup to probe a signal and then assume the fault is with the signal, when it's really issues caused by the setup.
The way to use it is like the following picture, touch the ground wire to the IC ground pin, and the probe tip touches the pin you wish to probe:

When designing your board, you can add dedicated test points to make getting to the signals easier. You can even add on board probe tip adapters (available from any decent distributor) if you have enough space.
For a detailed discussion of scope probes the Tektronix ABCs of Probes is good reading.
Here is a diagram from the above link showing the effects of different ground lead lengths on a fast rising signal:

A:

It is what it looks like - a ground spring*.

At least that's what Agilent call it.

A:

I have always known those to be "Ground Clips" or "Ground Spring Clips". Another seller refers to them as "Tip Grounds". Notice the different sizes with various arm lengths in the clip.
On more than one occasion, when trying to make a difficult single handed measurement, I've had to resort to making a similar type of temporary clip out of a piece of bus wire.
http://www.caltestelectronics.com/ctitem/35-35mm-probe-accessories/CT3672


Q:

Buttons in re-usable user controls

I have a UserControl which I want to re-use multiple times within a page. I found a post about a similar problem, but here comes the twist: If I have a TextBox in my control, I can make single properties public, like this:
public string FirstName
{
   get { return privateTextBox.Text; }
   set { privateTextBox.Text = value; }
}

From my main view (which has a view model) I access that property, like such:
MyUserControl personUserControl= new MyUserControl();
personUserControl.FirstName = viewModel.FirstName;

Here is my issue: What if I have a button in the custom user control, which I want to access. I can access its properties, just like the textbox, but what about events (mainly the Click event)?
Currently, my best solution is invoking a delegate event, which is caught by the view model (of the main view) which then invokes another event, but this seems like a quite bad design.
Is it not possible to access events from user controls, in a manner similar of the property access?
P.S. No it is not a mistake that I mixed MVVM and WinForms. This is intended (clever or not).
Edit: The issue is not so much related to WinForms (from what I can tell) as it is related to using multiple layers of UserControls. This rises the question: Should I pass the ViewModel from the top and down through the multiple layers of UserControls, or should I pass the properties of the UserControls upwards?

A:

You can expose events almost the same way you handle other properties:
private Button myButton;

public event EventHandler MyButtonClick
{
    add { myButton.Click += value; }
    remove { myButton.Click -= value; }
}


Q:

Link two Scatter charts in Bokeh

Based on the Bokeh docs, it is possible to link two scatter plots created using the plotting interface:
s1 = figure(plot_width=400, plot_height=400, title=None, tools=TOOLS)
s1.circle(x='Elevation', y='Aspect', source=src)

s2 = figure(plot_width=400, plot_height=400, title=None, tools=TOOLS)
s2.circle(x='Elevation', y='Slope', source=src)

However, I'd like to do this with the Scatter chart, so that I can take advantage of automatic styling (e.g. colouring by a 3rd column). Is this possible? What I have right now, which doesn't work, is:
s1 = Scatter(df_samp, x='Elevation', y='Horizontal_Distance_To_Roadways', color='Cover_Type', plot_height=400, plot_width=400, source=src, tools=TOOLS)
s2 = Scatter(df_samp, x='Elevation', y='Aspect', color='Cover_Type', plot_height=400, plot_width=400, source=src, tools=TOOLS)

A:

The bokeh.charts API, including Scatter has been deprecated and removed. The first code above, using the stable and supported bokeh.plotting API is the correct way to proceed in all cases now and in the future.
If you want to colormap based on additional columns, this is possible using various transforms:
https://docs.bokeh.org/en/latest/docs/user_guide/data.html#transforming-data


Q:

Specific name of this faucet / sink type

I'm having a heck of a time finding a replacement faucet for this sink. I was hoping someone could enlighten me as to if there's a specific name for this type of sink/faucet that might help me locate one easier.
Notice the the raised area the faucet sits on the sink at, also the pieces from left to right are what looks like maybe a broken soap dispenser, a pull/push drain control for the left basin, then the faucet, then another drain control for the right basin, and on the furthest right is the hose sprayer thing (not sure of the correct verbiage for any of this).
The Sink is a 3 basin porcelain sink. The (I'll just call it a "cap") that the faucet and stuff sits on seems very unique. I understand I'll likely try to have to re-use this "cap" piece along with the original pull/pull drain plug controls for the basins, but I have no idea what you would call the rest of this setup. Everywhere I've looked I only seem to find the contemporary standard ones that sit on top of a flat surface as one piece but can't find a setup to replace this for the life of me.
So any insight would be appreciated! Thanks.

A:

I don't know the name of this type of sink or faucet configuration.
If you are already expecting to re-use the cap, you may be able to find another faucet that will work with it.  There are a number of one-handle kitchen faucets that are now designed to be installed with or without a wide base.  For example, the Moen Essie faucet

You may be able to take a faucet like this and mount it on top of the existing cap.


Q:

cut-off line of asp.net treeview

I have an ASP.NET TreeView and need set ShowLine "true" when I define its style.
However, the treeview's lines will be cut-off.
I tried this tutorial, but it didn't help.
.tree
{
      font-size: 40px;
      height: 40px !important;
 }

<asp:TreeView ID="TreeView1" runat="server" ShowLines="True" CssClass="tree">
    <Nodes>
            <asp:TreeNode Text="test1" Value="1">
                <asp:TreeNode Text="test1.1" Value="11"></asp:TreeNode>
            </asp:TreeNode>
            <asp:TreeNode Text="test2" Value="2">
                <asp:TreeNode Text="test2.1" Value="21"></asp:TreeNode>
            </asp:TreeNode>
        </Nodes>
    </asp:TreeView>

A:

Did you try the styles mentioned in the example itself? you are missing td div in the style
.tree td div {
   height: 20px !important
}

That will work. Note that setting 40px is not going to work directly as it seems the vertical line image used within the div is of 20px height; hence you will need to implement your own ways if you want to change that. This would also affect the expand/collapse icon on the tree nodes.
.tree td div {
       height: 40px !important
    }

EDIT
The default images used are 20 x 20 pixels in size. to set your own set of images, you need to set LineImagesFolder property of the tree view (by doing this you will be providing your own set of images). Have a look at this MSDN Link


Q:

Mixing data types results in heart output

I was fooling around with one of the sample programs in the K&R, and found that this
#include <stdio.h>

main()
{
    double nc;

    for (nc = 0; getchar() != EOF; ++nc)
        ;
    printf("%lf\n", nc );
    putchar(nc);
}

produces output that is 3.000000 (which I totally expected) then a new line with a heart on it (which I totally did not expect).  Why would it output a new line with a heart on it?
I assume it has something to do with me mixing data types.

A:

You're calling putchar() with a double as an argument.  It's going to get implicitly typecast to int, and then that character will be output.  You get the heart because for some reason your character set has a heart as character number 3.  If you run it and type a bunch more characters before the EOF, you'll get a different character.  On my machine, your program doesn't make a heart, but if I type more characters, I can get whatever I want on that next line.  ASCII character 3 is ETX, end of text, so I don't know why you would get the heart in your case - are you using some weird locale or character set?  What does this program output on your machine:
#include <stdio.h>

int main(int argc, char *argv[])
{
    putchar(3);
    putchar('\n');
    return 0;
}

Edit:
You're getting the heart because that's what's in your character set at position 3.  From wikipedia:

In Code page 437, the original character set of the IBM PC, the value of 3 (hexadecimal 03) represents the heart symbol. This value is shared with the non-printing ETX control character, which overrides it in many contexts.


Q:

JQuery: Showing an image when loaded succesfully and conflict with onload

I want to show images only when they are loaded successfully (some paths give 404).
Have following code, which works fine.
<script>
    $(document).ready(function() {
      $(".complex-image").load(function(){
          $(this).show();
      });
    });
</script>

Now, one of the pages shows a google map, which sets:
onload = initMap
onunload = GUnload

On this page in IE8 and Chrome, image does not show up even when available. But shows up fine in Firefox 4. A sample page having image+map from my site is this
I have tried the inverse approach as well: hide images when there is error in loading. Using code below:
<script>
    $(document).ready(function() {
      $(".complex-image").ready(function(){
          $(this).hide();
      });
    });
</script>

This does not hide images on IE8 both on map and non-map containing pages.
What is a cross-browser way to show images when loaded successfully, when there is a body onload defined?
Edit: Used Elzo's solution and to get img.load() fired even when image is getting read from cache, used this:
jQuery callback on image load (even when the image is cached)

A:

Here is how to do it. I put also a demo.


Q:

Does the Codex Sinaiticus contain the Hebrew Tetragrammaton or Greek LORD (KURIOS)?

The New King James Version uses the Tetragrammaton in the New Testament (written as +LORD [CAPS-smallcaps]) apparently it uses a Tetragrammaton source material, or it arbitrarily implies it while the KJV does not.
So, how does the Codex Sinaiticus refer to the Tetragrammaton within the Epistles of Paul?  Specifically, an example is at Romans chapter 10 verse 13.  [Paul is referencing Sacred Scripture]
[NKJV]

For “whoever calls on the name of the +LORD shall be saved.”

+[Lord in [CAP-small-caps], indicating the Tetragrammaton was used as it's source]
[RSV] other translations treat our subject this way

For, “every one who calls upon the name of the ++Lord will be saved.”

++[Lord in [CAP-lowercase], indicating the Greek word "Kyrios" (meaning master or lord) is being used]
Roman's 10:13 quotes Joel 2:32, through Paul's letter
Here is Joel chapter 2 verse 32...
[NKJV]

And it shall come to pass That whoever calls on the name of the +LORD
  Shall be saved. For in Mount Zion and in Jerusalem there shall be
  deliverance, As the +LORD has said, Among the remnant whom the +LORD
  calls.

[RSV]

And it shall come to pass that all who call upon the name of the
  +LORD shall be delivered; for in Mount Zion and in Jerusalem there shall be those who escape, as the +LORD has said, and among the
  survivors shall be those whom the +LORD calls.

[ASV]

And it shall come to pass, that whosoever shall call on the name of
  Jehovah shall be delivered; for in mount Zion and in Jerusalem there
  shall be those that escape, as Jehovah hath said, and among the
  remnant those whom Jehovah doth call.

[NOG]

Then whoever calls on the name of Yahweh will be saved.
      Those who escape will be on Mount Zion and in Jerusalem.
      Among the survivors will be those whom Yahweh calls,
          as Yahweh has promised.

[GNV]

But whosoever shall call on the Name of the Lord, shall be saved:
  for in mount Zion, and in Jerusalem shall be deliverance as the Lord
  hath said, and in the remnant, whom the Lord shall call.

So, the Question is how does the Codex Sinaiticus deal with the Tetragrammaton.  Instead of trying to determine all cases, lets focus on Romans 10 verse 13.  I suspect that it simply uses the Greek word "Kyrios" and in Greek letters.  There was speculation that some early Greek Codex might have the Hebrew word which looks like the Greek Symbols Pi-Pi, and therefore it might possibly use two Greek Pi Pi letters, but not likely.

A:

OP asks several questions, which I will summarize and address.
How does Codex Sinaiticus handle the word translated "LORD/lord" in Romans 10:13?
We can answer this definitively due to the amazing technology of 2018 and the good will of the folks at the British Library and their collaborators.

The word κυριος ("lord") is in the red box. As in many early manuscripts, it is abbreviated using the first and last letter. Because it appears here in the genitive case, the full word would be κυριου; the abbreviation uses the first and last letters. It is written in majuscule script, like the rest of the manuscript, so ΚΥ. The line over the letters indicates that this is an abbreviation (due to the nomina sacra status).
Second, the title question, which is more broad:
Does the Codex Sinaiticus contain the Hebrew Tetragrammaton or Greek LORD (KURIOS)?
The Greek κυριος (kurios) is used consistently, abbreviated using the first and last letters in order to show the case. This can be seen at the Codex Sinaiticus website. This is almost a non-question for the NT, as there are no known manuscripts that transliterate or otherwise represent the Tetragrammaton in full form apart from this word, which is almost certainly original. The more interesting case is the LXX portion of Sinaiticus, since there are known LXX manuscripts containing representation of the Hebrew Tetragram. Dr. Pietersma's article summarizes this evidence; Sinaiticus is not one such manuscript.
Finally, the OP seems to be motivated by a question brought up in the comments:
Why does NKJV use the Tetragrammaton (written as LORD [CAPS-smallcaps]) when the KJV did not[?]
The NKJV is using the capital letters in instances where the NT κυριος is quoting a passage from the Hebrew Scriptures where the divine name was used. The preface to the edition says as much and acknowledges that this is a departure from the KJV tradition. I don't think any further information about their rationale is available.


Q:

Trouble Capturing URLs With Campaign Tracking Parameters in Redshift

I am trying to capture URLs that have tracking parameters in a query to a website's homepage. There are cases where the parameter can have a forward slash before the query begins. Here are two examples that should match:
https://test.com/?utm_campaign=email
https://test.com?utm_campaign=email

Here are two examples that should not match:
 https://test.com/blog
 https://test.com/blog?utm_campaign=email

Here is an example query:
SELECT t.url,COUNT(t.id) AS pageviews
FROM db.table AS t
WHERE t.url ~ '^https*:\\/\\/test\\.com\\?'
GROUP BY 1
ORDER BY 2 DESC

Note that Redshift documentation states:

To search for strings that include metacharacters, such as ‘. * | ? ‘,
  and so on, escape the character using two backslashes (' \\ ')

I have tried both single and double slashes. The single slash returns a lot more than I expect, whereas the double slash does not return any results. I'm more accustomed to writing regex in Javascript, and as such I assume I'm having trouble translating between the two; any help is much appreciated.

A:

The / symbol is not a special regex metacharacter, you should not escape it. Besides, in order to avoid issues with escaping . or ?, you may put them into bracket expressions:
WHERE t.url ~ '^https?://test[.]com[?]'

It will match:

^ - start of string
https?://test[.]com[?] - http://test.com? or https://test.com?.


Q:

How to select data of a built-in AnyLogic-database within an AnyLogic-class?

in my anylogic-model i want to query some data from the build-in-database. Within a function in an agent-type that's no problem. For better encapsulating i want to put my code into a class.
I already searched the AnyLogic-help, but i couldn't find the correct way to access the database from within a class.
The provided examples only work within the agent-type (https://help.anylogic.com/nav/0_15_10), since the function is provided by the abstract class Utilities which every agent is inherited from (https://help.anylogic.com/topic/com.anylogic.help/html/javadoc/com/anylogic/engine/Utilities.html).
Tuple item = selectFrom( team_knowledge ).
                        where( team_knowledge.idteam_social.eq( idmember ) ).
                        where( team_knowledge.idteam_technology.eq( idtechnology ) ).
                        firstResult(team_knowledge.id, team_knowledge.idteam_social,
                            team_knowledge.idteam_technology, team_knowledge.is_skill,
                            team_knowledge.necessary_skill);

Error: The method selectFrom(Qteam_knowledge) is undefined for the type TeamKnowledgeModel

Do you can name the correct class to use for this problem?

A:

Just have the class accept an instance of any Agent in the model within its constructor. Then it has to use that to do any queries (e.g., agent.selectFrom).
That is, the class stores an instance of an Agent which it delegates queries to.


Q:

Removing a sequence of characters from a large binary file using python

I would like to trim long sequences of the same value from a binary file in python. A simple way of doing it is simply reading in the file and using re.sub to replace the unwanted sequence. This will of course not work on large binary files. Can it be done in something like numpy?

A:

If you don't have the memory to do open("big.file").read(), then numpy wont really help.. It uses the same memory as python variables do (if you have 1GB of RAM, you can only load 1GB of data into numpy)
The solution is simple - read the file in chunks.. f = open("big.file", "rb"), then do a series of f.read(500), remove the sequence and write it back out to another file object. Pretty much how you do file reading/writing in C..
The problem then is if you miss the pattern you are replacing.. For example:
target_seq = "567"
input_file = "1234567890"

target_seq.read(5) # reads 12345, doesn't contain 567
target_seq.read(5) # reads 67890, doesn't contain 567

The obvious solution is to start at the first character in the file, check len(target_seq) characters, then go forward one character, check forward again.
For example (pseudo code!):
while cur_data != "":
    seek_start = 0
    chunk_size = len(target_seq)

    input_file.seek(offset = seek_start, whence = 1) #whence=1 means seek from start of file (0 + offset)
    cur_data = input_file.read(chunk_size) # reads 123
    if target_seq == cur_data:
        # Found it!
        out_file.write("replacement_string")
    else:
        # not it, shove it in the new file
        out_file.write(cur_data)
    seek_start += 1

It's not exactly the most efficient way, but it will work, and not require keeping a copy of the file in memory (or two).


Q:

cannot install tensorflow on anaconda

i am trying to install tensorflow on anaconda
i tried conda install -c conda-forge tensorflow
but the installation stuck on Solving environment:
looked for a solution so someone suggested to install with debug
   conda install --debug -c conda-forge tensorflow

but it stopped on
DEBUG conda.resolve:filter_group(277): tensorboard: pruned from 47 -> 0

how to fix this?

A:

For python version 3.7, you need to first downgrade to 3.6 using conda install python=3.6. After that, the installation should work. I had a similar problem recently.


Q:

Citation Alias within Full Citation

I have a reference in one of my papers which I cite several times. So I abbreviate it after full citation the first time round and then I use the abbreviated version of the citation in rest of the paper. Here is what I do:

Fernandez-Villaverde, Guerron-Quintana, Kuester and Rubio-Ramirez (2015) (FGKR now on) look at ...

Courtesy of inputs I received here, I succeeded in hyperlinking every instance of abbreviated citation ('FGKR' in this case). Here is how my PDF output looks:

Now I want to change how I use the key 'FGKR' the first time around. Instead of using it for the first time like the above example, I want to write it like this:

Fernandez-Villaverde, Guerron-Quintana, Kuester and Rubio-Ramirez (2015, FGKR hereafter) show that ...

In this example, 'FGKR' is inside the first full citation. I want it to work just like it did before with hyperlink. I just want it to appear within the braces when I use the full citation the first time. How can I do this?
Here is my MWE:
\documentclass[12pt,a4paper]{article}
\usepackage[english]{babel}
\usepackage{natbib}
\bibliographystyle{ecta}
\usepackage[colorlinks,citecolor=red]{hyperref}
\title{A Paper}

\usepackage{filecontents}

\begin{filecontents}{\jobname.bib}
@article{fernandez2015fiscal,
title={Fiscal Volatility Shocks and Economic Activity},
author={Fern{\'a}ndez-Villaverde, Jes{\'u}s and Guerr{\'o}n-Quintana, Pablo
and Kuester, Keith and Rubio-Ram{\'\i}rez, Juan},
journal={The American Economic Review},
volume={105},
number={11},
pages={3352--3384},
year={2015},
publisher={American Economic Association}
}
\end{filecontents}
\defcitealias{fernandez2015fiscal}{FGKR}

\begin{document}
\maketitle

\section{Introduction}
\citet*{fernandez2015fiscal} (\citetalias{fernandez2015fiscal} now on) look
 at \ldots

\bibliographystyle{ecta}
\bibliography{\jobname}

\end{document}

A:

The natbib package allows its main user macros -- \citet and \citep -- to take up to two optional arguments; these arguments will be placed after (in the case of 1 optional argument) or before and after (in the case of two optional arguments) the main citation call-out.
You may also want to load the natbib package with the option longnamesfirst. That way, the list of authors won't be truncated the first time a piece with three or more authors is cited.
Incidentally, nothing good will every come from providing two or more \bibliographystyle instructions per document.

\RequirePackage{filecontents}
\begin{filecontents}{mybib.bib}
@article{fernandez2015fiscal,
  title  = {Fiscal Volatility Shocks and Economic Activity},
  author = {Fern{\'a}ndez-Villaverde, Jes{\'u}s and
            Guerr{\'o}n-Quintana, Pablo and
            Kuester, Keith and
            Rubio-Ram{\'i}rez, Juan},
  journal= {American Economic Review},
  volume = {105},
  number = {11},
  pages  = {3352--3384},
  year   = {2015},
  publisher={American Economic Association}
}
\end{filecontents}

\documentclass[12pt,a4paper]{article}
\usepackage[T1]{fontenc} % new
\usepackage[english]{babel}

\usepackage[longnamesfirst]{natbib}
\defcitealias{fernandez2015fiscal}{FGKR}
\bibliographystyle{ecta}

\usepackage{xurl} % for arbitrary line breaks in URL strings
\usepackage[colorlinks,citecolor=red]{hyperref}

\begin{document}

\section{Introduction}
\citet[\citetalias{fernandez2015fiscal} hereafter]{fernandez2015fiscal} look at

%\bibliographystyle{ecta} % don't run this command twice!
\bibliography{mybib}
\end{document}


Q:

Counting Number of Words in a delimited String in Linux

I am Very new to Linux.
I have a delimited String and I want to find out numbers of words in it.
line=100|Surender|Linux

echo $line '|' | wc -w

The above code gives me 2 . But the expected count is 3 .
Could somebody help me on this

A:

Build it up step by step.
wc expects white space between words
You could use tr to replace '|' to spaces
eg
~/tmp$ line="100|Surender|Linux"
~/tmp$ echo $line |tr "|" " "
100 Surender Linux

Great, so now push this through a pipe to wc
~/tmp$ echo $line |tr "|" " " |wc
      1       3      19


Q:

Sharepoint default list item detail view

I have a webpart that renders random list items (from any list and list type) in a specified format.  I want the items that are being displayed in the webpart to link to their ListItem detail views.  However, I don't see a property on the list itself that would tell me what view is the default DETAIL view for the list (ie. blog list detail is Post.aspx).  Does this come from the list definition?  How would I get that information programmatically?  I'm trying to avoid hard-coding any list information based on list type.

A:

Have a look at SPList.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url.
I think this is what you're looking for.  You'll need to append the the SPListItem.ID on the querystring so that it knows which list item to display.
using (SPWeb myWeb = GetMyWeb()) // GetMyWeb gets a reference to a SPWeb object
{
    SPList myList = GetMyList(myWeb); // GetMyList gets a reference to a SPList object
    SPListItem myItem = GetMyListItem(myList); // GetMyListItem gets a reference to a SPListItem object
    string url = String.Format("{0}/{1}?ID={2}",
        myWeb.Url,
        myList.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url,
        myItem.ID);
}

It's also a good practice to append &Source=/url/to/current/page to the querystring so that users will be redirected back to the page they left when they click the Cancel/Close buttons on the Edit or Display forms.


Q:

OGC WFS CQL Filter XML

Does WFS (specifically we are using geoserver) allow for a 'CQL Filter' to be specified when making a XML request?
All the examples that I'm finding are for KVP requests.
I don't see why you couldn't do something like below yet I can't find it anywhere.
<CQL_FILTER>INCLUDE FILTER HERE</CQL_FILTER>

A:

As Ian already reported, there is no way to use CQL in a POST request, its usage is currently limited to GET request, and it's a vendor extension to the base protocol.
The POST request could be extended to process it of course, it's a matter of finding the development resources to make it happen.
See here:
https://github.com/geoserver/geoserver/wiki/Successfully-requesting-and-integrating-new-features-and-improvements-in-GeoServer


Q:

how do I split array and show specific element

below is my array output
 [0] => Array
[OrderDetails] => Array
(

  [Options] => [Nicotine Level:12mg Nicotine][Sampler Item 1:Krankberry][Sampler Item 2:Unicorn Blood][Sampler Item 3:WaterFelons]
)
)

I want to show only Nicotine level from options field and, the options may vary,please help me.I have lot of options.
I have used below code
$explode_var = explode('[','[Nicotine Level:12mg Nicotine][Sampler Item 1:Krankberry][Sampler Item 2:Unicorn Blood][Sampler Item 3:WaterFelons]');

echo '
';
print_r($explode_var);
echo '
';

A:

This is one way to do it read the comments on the code:
<?php
$data = array(array('OrderDetails' => array('Options' => '[Nicotine Level:12mg Nicotine][Sampler Item 1:Krankberry][Sampler Item 2:Unicorn Blood][Sampler Item 3:WaterFelons]')));

$options = $data[0]['OrderDetails']['Options'];
$options = str_replace(']', '', $options);
$old_var = array_filter(explode('[',$options));
$result = array();
foreach ($old_var as $items)
{
    $item = explode(':', $items);
    $result[$item[0]] = $item[1];
}

foreach ($result as $key=>$value)
{
    echo $key, " => ", $value, "
\n";
}

Live DEMO.


Q:

how to use an arbitrary function in a wrapper function in Python

I want to create a wrapper function something like the following:
def functionWrapper(function, **kwargs):
    """
        This function requires as input a function and a dictionary of named arguments for that function.
    """
    results=function(**kwargs)
        print results

def multiply(multiplicand1=0, multiplicand2=0):
    return multiplicand1*multiplicand2

def main():
    functionWrapper(
        multiply,
        {
            'multiplicand1': 3,
            'multiplicand2': 4,
        }
    )

if __name__ == "__main__":
    main()

I am running into difficulties with this implementation:
TypeError: functionWrapper() takes exactly 1 argument (2 given)

How should I address this problem? Is my use of the arbitrary function in the wrapper function function(**kwargs) reasonable? Thanks for your help.
EDIT: fixed error in specification of dictionary

A:

Use ** when passing the dict items to that function;
**{
   'multiplicand1': 3,
   'multiplicand2': 4,
  }

Output:
12

As pointed out by @svk in comments, functionWrapper's doctstring says:

This function requires as input a function and a dictionary of named
  arguments for that function.

So in that case you need to change the function definition to:
def functionWrapper(function, kwargs):

and also fix the typo in the dict otherwise you'll get 0 as answer:
'multiplicand1': 3,
'multiplicand1': 4,  #Change this to 'multiplicand2

'


Q:

How to get rid of the extra spacing?

You can find the staging environment over here:
http://axces-staging.houston-1.hybridmedia.be/
I have a lot of unnecessary spacing above the title "Onze aanpak".
I only have this issue on Firefox. It looks fine on chrome and safari.

Cannot find what causes this. Does someone have any idea?
Thanks.

A:

It's due to two values in the elements above that space:
1.) The top: -30rem in homepage-middle__wrapper
2.) The margin-top: 30rem in section--products homepage-middle background--primary
Erase both to eliminate that space.


Q:

Smooth folded cylinder with tikz

How can I draw the following folded cylinder with tikz?

The main problem is the curved lines. What I have done so far is this:
\begin{tikzpicture}
%\draw [help lines] grid (5,5);
%\draw (0,.8) rectangle (5,4.4);
\draw (1,.3) arc (210:180:4cm and .5cm);
\draw[densely dashed] (.47,.54) arc (180:150:4cm and .5cm);
\draw (1,.3)--(1,3.9) arc (210:150:4cm and .5cm);
\draw (.47,.5)--(.47,4.2);
\draw (1,.8)--(4,.8);
\draw (1,4.4)--(4,4.4);
\end{tikzpicture}

I have also another request. Is it better to write tikz codes directly in tex file or convert it to ps or pdf then import it?
Any help would be appreciated.

A:

If you want a cartoon, maybe something along these lines may do? When patching together different paths it is usually advantageous to make sure that the slope does not jump.
\documentclass[tikz,border=3.14mm]{standalone}
\begin{document}
\begin{tikzpicture}
\draw[densely dashed] (-1,2) coordinate (TL) -| ++(-1,-4) -- ++(1,0)
coordinate (HL);
\draw (TL) arc(90:270:0.5 and 0.3) -- ++ (0,-4)
arc(270:180:0.5 and 0.3) coordinate (BL)-- ++ (0,4);
\draw[densely dashed] (BL) arc (180:90:0.5 and 0.3);
\draw[densely dashed] (1,2) coordinate (TR) -| ++(1,-4) -- ++(-1,0)
coordinate (HR);
\draw (TR) arc(90:-90:0.5 and 0.3) -- ++ (0,-4)
arc(-90:0:0.5 and 0.3) coordinate (BR)-- ++ (0,4);
\draw[densely dashed] (BR) arc (0:90:0.5 and 0.3);
\draw (TL) -- (TR) (HL) -- (HR) ;
\end{tikzpicture}
\end{document}


Q:

Visible lines but no idea where in the html or css

I've a small problem by creating my website. Some div or text element show some lines by moving the mouse over it.
they get invisible by clicking somewhere else. But I haven't define a border.
I do not know how to continue, may someone has a idea what that could be?
My website use bootstrap 4.0
example Picture

A:

Did you try
text-decoration: none;

It is hard to guess the problem from your description.
You can also try inspecting that perticular div. Right click that div and select inspect element. There the browser will show you the css applied to that div or text.


Q:

Node.js unique folder for each upload with multer and shortid

I'm using shortid for a unique id each upload and multer for the post handler.
I'm uploading some input aswell as an image. I'd like for each upload to be stored inside "upload/XXXXX"
I'm generating the unique id on app.post(...) and would like to know how to send this id to multer.
Using a global variable would have it's problems if 2 posts were done at the same time correct?
var Storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, path.join(__dirname, 'uploads', XXXXX)); //Unique id for file is the same as Folder
  },
  filename: function (req, file, callback) {
    callback(null, XXXXX); //Unique id
  }
});

var upload = multer({
  storage: Storage
}).single('pic');

//tell express what to do when the route is requested
app.post('/fbshare', function (req, res, next) {
  let ui = shortid();
  upload(req, res, function (err) {
    if (err) {
      return res.end("Something went wrong!");
    }
    return res.end("File uploaded sucessfully!.");
  });
});

How can i passthrough ui to Storage from app.post() ? Or if you have a better solution I'm all ears.
Thank you

Final Solution
var Storage = multer.diskStorage({
  destination: function (req, file, callback) {
    fs.mkdir(path.join(__dirname, 'uploads', req.ui), function(){
       callback(null, path.join(__dirname, 'uploads', req.ui));
    });
  },
  filename: function (req, file, callback) {
    callback(null, req.ui + file.originalname.substring(file.originalname.indexOf('.'), file.originalname.length));
  }
});

var upload = multer({
  storage: Storage
}).single('pic');

//tell express what to do when the route is requested
app.post('/fbshare', function (req, res, next) {
  req.ui = shortid();
  upload(req, res, function (err) {
    if (err) {
      return res.end("Something went wrong!");
    }
    return res.end("File uploaded sucessfully!.");
  });

});

A:

How about this?
app.post('/fbshare', function (req, res, next) {
  req.ui = shortid(); // create the id in the request
....

then in the multer
var Storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, path.join(__dirname, 'uploads', req.ui)); //Unique id for
....

the same with filename