text:
Q: assigned ips to my custom nameservers, however still the nameservers showing with "No IP" I went to  Main >> Server Configuration >> Basic cPanel & WHM Setup and correctly assigned the IPs to my 2 custom nameservers. After that (on same screen) I created A records also for the nameservers, and finally clicked on "Save Changes".
However when I go to Main >> Networking Setup >> Nameserver IPs, the 2 nameservers are shown, but under IP Address field, the value shown is "No IP".
What do I do to ensure that IPs are correctly assigned to my nameservers?

A: You will need to register your name servers with the domain registrar. This creates so-called "glue records", which will then show up in your domain registration details. Some domain registrars will require a working DNS setup for the domain before they activate the glue records, so all your preparations so far are correct, you just need to make the final step.
Once the domain updates have propagated around the world, name resolution for your domain should work.

A: You should edit the following file:
/etc/nameserverips

Once you have added the correct entries, which are in the format
1.2.3.4=ns1.domain.com
1.2.3.5=ns2.domain.com

you should then load the Nameserver IPs option in WHM, these should then show up with IPs.


text:
Q: Creating and setting of labels to 'blink' at different timing interval in visual basic 6 As my title mentioned, I need help to solve this problem. Just some additional info, I don't intend to use any command button. I just want to solely rely on the timer. I also want the labels to stop 'blinking' and be visible after 20 sec. I have provided my code. I definitely know there are problems in my coding as I'm new to VB and am still learning. Hope anyone here is able to help. Thank you very much.(By the way, please pardon me and let me know if I make any mistake in creating a thread as I'm a new user.)
Private Sub tmrBlink_Timer()
Dim i%
i = i + 1

Do
    lblBlink1Sec.Visible = Not lblBlink1Sec.Visible
    Do
        tmrBlink.Interval = 2000
        lblBlink2Sec.Visible = Not lblBlink2Sec.Visible
    Loop Until i <= 10
        Do
            tmrBlink.Interval = 5000
            lblBlink5Sec.Visible = Not lblBlink5Sec.Visible
        Loop Until i <= 4
Loop Until i <= 20

End Sub

A: Well i would like you to look at the following piece of code.
Private Sub Timer1_Timer()
Static a As Integer 'A counter which will not be reinitialized
If a Mod 2 = 0 Then  'Check whether the value of the counter is odd or even?
    Label1.Visible = True
Else: Label1.Visible = False
End If
a = a + 1            'Increment the counter
If a = 20 Then
     Timer1.Enabled = False 'code to stop your blikning after 20 seconds
     label1.visible=false
end if
End Sub

There is a variable a associated with your every timer interval. after every timer interval, it will be incremented and will toggle between odd and even values.

A: Thank you Thomas, Jac and Anish for the advice and feedback. Just that my answer is halfway answered. Maybe my question wasn't clear enough. I need to make 3 labels 'blink' at 1 sec, 2 sec and 5 sec respectively and stop 'blinking' but be visible after 20 seconds.
If a Mod 2 = 0 Then  'Check whether the value of the counter is odd or even?
    Label1.Visible = True
    Label2.Visible = Not Label2.Visible
    Label5.visible = True
    Elseif a Mod 5 = 0 Then
        Label1.Visible = True
        Label2.Visible = True
        Label5.Visible = Not Label5.Visible
            Else
                Label1.Visible = Not Label1.Visible
                Label2.Visible = True
                Label5.Visible = True
End If
a = a + 1            'Increment the counter
If a = 20 Then
   Timer1.Enabled = False 'code to stop your blinking after 20 seconds
   label1.Visible = True
   Label2.Visible = True
   Label5.Visible = True
End if
End Sub

I have modified the code a bit and used label1,2,5 to represent the timing I need it to 'blink'. Please give me some feedback on the coding. Thank you very much. :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding text and using its location in Marathon Testing Tool/JRuby Using Marathon to test a java application, I have a handful of rows and I want to commit some operations on a specific row that has certain text in one of its fields.
How would I go about searching for it and then selecting it to use it in Marathon or JRuby?
For example, I want to find the text "HERE" in a row, right click that row, and click one of the options provided.

A: There are two ways you can do this.

*

*You can fall back to WebDriver interfaces and use find_elements.
table = get_component('oscarTable')
cells = table.find_elements(:css, '.::all-cells[text="102 Dalmatians"]')
cells.each { |c| puts c.text }

*Use text property and access the cell directly
cell = get_component('oscarTable', { :text => '102 Dalmatians' })
puts cell.text

In (2) you can use select instead of get_component to set the value of the cell (if the cell is editable etc.)


text:
Q: Subplots on figure not filling Canvas Im using pyQT and want to plot an image on a GUI I create.
I use:
 # a figure instance to plot on
     self.figure = plt.figure()
     self.figure.suptitle('My Test Figure')
     self.figure.set_facecolor('k')

    # this is the Canvas Widget that displays the `figure`
    # it takes the `figure` instance as a parameter to __init__
    self.canvas = FigureCanvas(self.figure)

    #I use GridLayout
    layout = QtGui.QGridLayout()

    #Make equal size columns
    layout.setColumnStretch(0,1)
    layout.setColumnStretch(1,1)
    layout.setColumnStretch(2,1)
    layout.setColumnStretch(3,1)
    layout.setColumnStretch(4,1)
    layout.setColumnStretch(5,1)
    layout.setColumnStretch(6,1)

    #Add a toolbar and the canvas widget
    layout.addWidget(self.toolbar,0,0,1,2)  #spans 1 row, 3 columns
    layout.addWidget(self.canvas,1,0,4,4)

..in a function I plot an image to the canvas using
    ax2=plt.subplot(1,1,1)

    ''' Load Image from File '''

    M=plt.imread('c:\Image01.tif')
    ax2.hold(False)
    plt.imshow(M,cmap='gray')
    plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
    plt.show()

but the image doesn't fill the canvas (coloured black), it only partially fills is even though Im using subplot (1,1,1).
Can anyone help me with being able to fill the canvas area that I have declared in the gridlayout.
enter image description here


text:
Q: Find combinations in multiple data sets I'm currently working on the project where I have about multiple CSV files need to match all combinations of events people attended by matching their customer id. They have been to multiple events. I need the events matched in a new column separated by comma. There is multiple data sets that need to be compared. Vlookup in excel was freezing due to the amount of data. How can I do this in R?  I have tidyverse already installed. Any suggestions?
 List 1   (one CSV file)                          List 2 (second CSV file)
LastName FirstName     CustID  Event         LastName FirstName CustID Event
Robson     Jonson       23019   NP5          Robson   Jonson    23019   GRT2
Robson     Jonson       23019   RTE3

Result Needed
LastName  FirstName      CustID     Matched Events
Rob       Jonson         23019      NPS, GRT2, RTE3

A: Your datasets are identically-structured, so they can be combined row-wise with rbind:
lst1 <- read.table(header=TRUE, stringsAsFactors=FALSE, text='
LastName FirstName     CustID  Event
Robson     Jonson       23019   NP5
Robson     Jonson       23019   RTE3')

lst2 <- read.table(header=TRUE, stringsAsFactors=FALSE, text='
LastName FirstName CustID Event
Robson   Jonson    23019   GRT2')

lst <- rbind(lst1, lst2)

Then you need an aggregation:
aggregate(lst$Event,
          list(LastName = lst$LastName, FirstName = lst$FirstName, CustID = lst$CustID),
          paste, collapse=", ")
#   LastName FirstName CustID               x
# 1   Robson    Jonson  23019 NP5, RTE3, GRT2


text:
Q: Latitude from initial conditions I'm a programmer trying to model satellite orbits. What formula can I use to determine the latitude of a satellite after a quarter orbit, given the initial launch latitude and inclination? For example, given a start of [30,0] and an initial inclination of 60 degrees, what would be [x,90]?
Update:
Here's the code in action if it helps to clarify things.
http://bl.ocks.org/flyinactor91/80b1a540aa9d7a55f3b8
The graphics library takes care of the map projection, which is why I only need to get the latitude. The crux of it are these lines here. It's a very VERY rough approx that doesn't model itself on sinusoidal motion but the mathematician in me knows that it's total bunk.
//The launch latitude
var start = 30;
//The launch direction
var degree = 60;
//The degree as a percentage from vertical
var degPerc = Math.abs(degree) / 90;
//Whether the launch is oriented North or South
var direction = (degree >= 0) ? 1 : -1;
//The latitude encountered after a quarter orbit
var mid = (start + ((90-start) * 2 * degPerc)) * degPerc * direction;

A: The trajectory will not be sinusoidal.
Depending on the initial speed it will be one of elliptical , parabolic and will "reach" infinity with zero speed or hyperbolic and will "reach" infinity with a finite speed.  So the trajectory will very much depend on the initial speed of the satellite.
So how have you set up the computation?


text:
Q: Find parent rows that have identical sets of child rows Suppose I have a structure like this:
Recipes table
RecipeID
Name
Description

RecipeIngredients table
RecipeID
IngredientID
Quantity
UOM

The key on RecipeIngredients is (RecipeID, IngredientID).
What are some good ways for finding duplicate recipes? A duplicate recipe is defined as having the exact same set of ingredients and quantities for each ingredient.
I've thought of using FOR XML PATH to combine the ingredients into a single column. I haven't fully explored this but it should work if I make sure the ingredients/UOMs/quantities are sorted in the same sequence and have a proper separator. Are there better approaches?
There are 48K recipes and 200K ingredient rows.

A: For the following assumed schema and example data
CREATE TABLE dbo.RecipeIngredients
    (
      RecipeId INT NOT NULL ,
      IngredientID INT NOT NULL ,
      Quantity INT NOT NULL ,
      UOM INT NOT NULL ,
      CONSTRAINT RecipeIngredients_PK
          PRIMARY KEY ( RecipeId, IngredientID ) WITH (IGNORE_DUP_KEY = ON)
    ) ;

INSERT INTO dbo.RecipeIngredients
SELECT TOP (210000) ABS(CRYPT_GEN_RANDOM(8)/50000),
                     ABS(CRYPT_GEN_RANDOM(8) % 100),
                     ABS(CRYPT_GEN_RANDOM(8) % 10),
                     ABS(CRYPT_GEN_RANDOM(8) % 5)
FROM master..spt_values v1,
     master..spt_values v2

SELECT DISTINCT RecipeId, 'X' AS Name
INTO Recipes
FROM  dbo.RecipeIngredients

This populated 205,009 ingredient rows and 42,613 recipes. This will be slightly different each time due to the random element.
It assumes relatively few dupes (output after an example run was 217 duplicate recipe groups with two or three recipes per group). The most pathological case based on the figures in the OP would be 48,000 exact duplicates.
A script to set that up is
DROP TABLE dbo.RecipeIngredients,Recipes
GO

CREATE TABLE Recipes(
RecipeId INT IDENTITY,
Name VARCHAR(1))

INSERT INTO Recipes
SELECT TOP 48000 'X'
FROM master..spt_values v1,
     master..spt_values v2

CREATE TABLE dbo.RecipeIngredients
    (
      RecipeId INT NOT NULL ,
      IngredientID INT NOT NULL ,
      Quantity INT NOT NULL ,
      UOM INT NOT NULL ,
      CONSTRAINT RecipeIngredients_PK
          PRIMARY KEY ( RecipeId, IngredientID )) ;

INSERT INTO dbo.RecipeIngredients
SELECT RecipeId,IngredientID,Quantity,UOM
FROM Recipes
CROSS JOIN (SELECT 1,1,1 UNION ALL SELECT 2,2,2 UNION ALL  SELECT 3,3,3 UNION ALL SELECT 4,4,4) I(IngredientID,Quantity,UOM)

The following completed in less than a second on my machine for both cases.
CREATE TABLE #Concat
  (
     RecipeId     INT,
     concatenated VARCHAR(8000),
     PRIMARY KEY (concatenated, RecipeId)
  )

INSERT INTO #Concat
SELECT R.RecipeId,
       ISNULL(concatenated, '')
FROM   Recipes R
       CROSS APPLY (SELECT CAST(IngredientID AS VARCHAR(10)) + ',' + CAST(Quantity AS VARCHAR(10)) + ',' + CAST(UOM AS VARCHAR(10)) + ','
                    FROM   dbo.RecipeIngredients RI
                    WHERE  R.RecipeId = RecipeId
                    ORDER  BY IngredientID
                    FOR XML PATH('')) X (concatenated);

WITH C1
     AS (SELECT DISTINCT concatenated
         FROM   #Concat)
SELECT STUFF(Recipes, 1, 1, '')
FROM   C1
       CROSS APPLY (SELECT ',' + CAST(RecipeId AS VARCHAR(10))
                    FROM   #Concat C2
                    WHERE  C1.concatenated = C2.concatenated
                    ORDER  BY RecipeId
                    FOR XML PATH('')) R(Recipes)
WHERE  Recipes LIKE '%,%,%'

DROP TABLE #Concat

One caveat
I assumed that the length of the concatenated string will not exceed 896 bytes. If it does this will raise an error at run time rather than silently failing. You will need to remove the primary key (and implicitly created index) from the #temp table. The maximum length of the concatenated string in my test setup was 125 characters.
If the concatenated string is too long to index then performance of the final XML PATH query consolidating the identical recipes could well be poor. Installing and using a custom CLR string aggregation would be one solution as that could do the concatenation with one pass of the data rather than a non indexed self join.
SELECT YourClrAggregate(RecipeId)
FROM #Concat
GROUP BY concatenated

I also tried
WITH Agg
     AS (SELECT RecipeId,
                MAX(IngredientID)          AS MaxIngredientID,
                MIN(IngredientID)          AS MinIngredientID,
                SUM(IngredientID)          AS SumIngredientID,
                COUNT(IngredientID)        AS CountIngredientID,
                CHECKSUM_AGG(IngredientID) AS ChkIngredientID,
                MAX(Quantity)              AS MaxQuantity,
                MIN(Quantity)              AS MinQuantity,
                SUM(Quantity)              AS SumQuantity,
                COUNT(Quantity)            AS CountQuantity,
                CHECKSUM_AGG(Quantity)     AS ChkQuantity,
                MAX(UOM)                   AS MaxUOM,
                MIN(UOM)                   AS MinUOM,
                SUM(UOM)                   AS SumUOM,
                COUNT(UOM)                 AS CountUOM,
                CHECKSUM_AGG(UOM)          AS ChkUOM
         FROM   dbo.RecipeIngredients
         GROUP  BY RecipeId)
SELECT  A1.RecipeId AS RecipeId1,
        A2.RecipeId AS RecipeId2
FROM   Agg A1
       JOIN Agg A2
         ON A1.MaxIngredientID = A2.MaxIngredientID
            AND A1.MinIngredientID = A2.MinIngredientID
            AND A1.SumIngredientID = A2.SumIngredientID
            AND A1.CountIngredientID = A2.CountIngredientID
            AND A1.ChkIngredientID = A2.ChkIngredientID
            AND A1.MaxQuantity = A2.MaxQuantity
            AND A1.MinQuantity = A2.MinQuantity
            AND A1.SumQuantity = A2.SumQuantity
            AND A1.CountQuantity = A2.CountQuantity
            AND A1.ChkQuantity = A2.ChkQuantity
            AND A1.MaxUOM = A2.MaxUOM
            AND A1.MinUOM = A2.MinUOM
            AND A1.SumUOM = A2.SumUOM
            AND A1.CountUOM = A2.CountUOM
            AND A1.ChkUOM = A2.ChkUOM
            AND A1.RecipeId <> A2.RecipeId
WHERE  NOT EXISTS (SELECT *
                   FROM   (SELECT *
                           FROM   RecipeIngredients
                           WHERE  RecipeId = A1.RecipeId) R1
                          FULL OUTER JOIN (SELECT *
                                           FROM   RecipeIngredients
                                           WHERE  RecipeId = A2.RecipeId) R2
                            ON R1.IngredientID = R2.IngredientID
                               AND R1.Quantity = R2.Quantity
                               AND R1.UOM = R2.UOM
                   WHERE  R1.RecipeId IS NULL
                           OR R2.RecipeId IS NULL)

This works acceptably when there are relatively few duplicates (less than a second for the first example data) but performs badly in the pathological case as the initial aggregation returns exactly the same results for every RecipeID and so doesn't manage to cut down the number of comparisons at all.

A: This is a generalization of the relational division problem. No idea how efficient this will be:
; WITH cte AS
( SELECT RecipeID_1 = r1.RecipeID, Name_1 = r1.Name,
         RecipeID_2 = r2.RecipeID, Name_2 = r2.Name
  FROM Recipes AS r1
    JOIN Recipes AS r2
      ON r1.RecipeID <> r2.RecipeID
  WHERE NOT EXISTS
        ( SELECT 1
          FROM RecipeIngredients AS ri1
          WHERE ri1.RecipeID = r1.RecipeID
            AND NOT EXISTS
                ( SELECT 1
                  FROM RecipeIngredients AS ri2
                  WHERE ri2.RecipeID = r2.RecipeID
                    AND ri1.IngredientID = ri2.IngredientID
                    AND ri1.Quantity = ri2.Quantity
                    AND ri1.UOM = ri2.UOM
                )
         )
)
SELECT c1.*
FROM cte AS c1
  JOIN cte AS c2
    ON  c1.RecipeID_1 = c2.RecipeID_2
    AND c1.RecipeID_2 = c2.RecipeID_1
    AND c1.RecipeID_1 < c1.RecipeID_2;

Another (similar) approach:
SELECT RecipeID_1 = r1.RecipeID, Name_1 = r1.Name,
       RecipeID_2 = r2.RecipeID, Name_2 = r2.Name
FROM Recipes AS r1
  JOIN Recipes AS r2
    ON  r1.RecipeID < r2.RecipeID
    AND NOT EXISTS
        ( SELECT IngredientID, Quantity, UOM
          FROM RecipeIngredients AS ri1
          WHERE ri1.RecipeID = r1.RecipeID
        EXCEPT
          SELECT IngredientID, Quantity, UOM
          FROM RecipeIngredients AS ri2
          WHERE ri2.RecipeID = r2.RecipeID
        )
    AND NOT EXISTS
        ( SELECT IngredientID, Quantity, UOM
          FROM RecipeIngredients AS ri2
          WHERE ri2.RecipeID = r2.RecipeID
        EXCEPT
          SELECT IngredientID, Quantity, UOM
          FROM RecipeIngredients AS ri1
          WHERE ri1.RecipeID = r1.RecipeID
        ) ;

And another, different one:
; WITH cte AS
( SELECT RecipeID_1 = r.RecipeID, RecipeID_2 = ri.RecipeID,
          ri.IngredientID, ri.Quantity, ri.UOM
  FROM Recipes AS r
    CROSS JOIN RecipeIngredients AS ri
)
, cte2 AS
( SELECT RecipeID_1, RecipeID_2,
         IngredientID, Quantity, UOM
  FROM cte
EXCEPT
  SELECT RecipeID_2, RecipeID_1,
         IngredientID, Quantity, UOM
  FROM cte
)

  SELECT RecipeID_1 = r1.RecipeID, RecipeID_2 = r2.RecipeID
  FROM Recipes AS r1
    JOIN Recipes AS r2
      ON r1.RecipeID < r2.RecipeID
EXCEPT
  SELECT RecipeID_1, RecipeID_2
  FROM cte2
EXCEPT
  SELECT RecipeID_2, RecipeID_1
  FROM cte2 ;

Tested at SQL-Fiddle

Using the CHECKSUM() and CHECKSUM_AGG() functions, test at SQL-Fiddle-2:
(ignore this as it may give false positives)

ALTER TABLE RecipeIngredients
  ADD ck AS CHECKSUM( IngredientID, Quantity, UOM )
    PERSISTED ;

CREATE INDEX ckecksum_IX
  ON RecipeIngredients
    ( RecipeID, ck ) ;

; WITH cte AS
( SELECT RecipeID,
         cka = CHECKSUM_AGG(ck)
  FROM RecipeIngredients AS ri
  GROUP BY RecipeID
)
SELECT RecipeID_1 = c1.RecipeID, RecipeID_2 = c2.RecipeID
FROM cte AS c1
  JOIN cte AS c2
    ON  c1.cka = c2.cka
    AND c1.RecipeID < c2.RecipeID  ;


text:
Q: Проблема с реализацией регистрации/авторизации на домене второго и третьего уровней Регистрацию/Авторизацию осуществляю с помощью суперглобального массива $_SESSION данные отправляю асинхронно ajax на домен второго уровня example.ru, там выполняется php-скрипт регистрации и авторизации. По такому же принципу реализована корзина. Сайт имеет поддомен sub.example.ru.
в .htaccess прописано php_value session.cookie_domain ".example.ru"
сессию начинаю в обоих контроллерах(контроллер 1 - .example.ru, контроллер 2 - sub.example.ru) таким образом:
if (!session_id()) {
    ini_set('session.use_cookies', 'On');
    ini_set('session.use_trans_sid', 'Off');
    ini_set('session.cookie_domain', '.example.ru');
    session_set_cookie_params(0, '/', '.example.ru');
    session_start();
}
Кука PHPSESSID с идентификатором передаётся между доменом о поддоменом и обратно. Проблема 1: если осуществлять регистрацию и авторизацию находясь на sub.example.ru (напомню - ajax отправляет данные на .example.ru) то $_SESSION['auth'] создаётся, но после обновления страницы пропадает.
Проблема 2: если осуществлять регистрацию и авторизацию находясь на sub.example.ru (напомню - ajax отправляет данные на .example.ru) и при этом существует $_SESSION['cart'], то $_SESSION['auth'] создаётся вне сессии, в которой создана $_SESSION['cart'], после обновления страницы $_SESSION['auth'] также  пропадает. НО! Если осуществлять регистрацию/авторизацию с .example.ru и при этом существует $_SESSION['cart'], то $_SESSION['auth']создаётся в этой же сессии, после обновления никуда не пропадает и сохраняется на sub.example.ru. В чём проблема?


text:
Q: change order of variables for plots in effects package- prob easy but can't figure it out I made a plot using the effects package in R, which I think draws on lattice for plotting, but can't figure out how to change the order of the variables. Here is the plot:

And here is the code:
c <- glm(abundance ~ month*site*habitat+sg_biomass+mac_biomass,
         data=epifauna, family=poisson)
e <- effect(c("month","site","habitat"), c)
plot(e)

What I want is for the habitat to be on the x axis, and for there to be 3 columns and two rows, the top row month "J" and the bottom row month "A", and the 3 sites to be 3 seperate plots, hence the 3 columns.
Thanks for any help you can provide.

A: I think this should work for changing the x-variable:
plot(e,"habitat"), or
plot(e,x.var="habitat")


text:
Q: ValidationAttribute Redux Ref to:Creating a ValidationAttribute to ensure unique column values.
Ok... Let's try reframing the question:
from here I have ripped this code:
    static TEntity Get<TEntity, TKey>(this DataContext ctx, TKey key) where TEntity : class
    {
        var table = ctx.GetTable<TEntity>();
        var pkProp = (from member in ctx.Mapping.GetMetaType(typeof(TEntity)).DataMembers
                      where member.IsPrimaryKey
                      select member.Member).Single();
        ParameterExpression param = Expression.Parameter(typeof(TEntity), "x");
        MemberExpression memberExp;
        switch (pkProp.MemberType)
        {
            case MemberTypes.Field: memberExp = Expression.Field(param, (FieldInfo)pkProp); break;
            case MemberTypes.Property: memberExp = Expression.Property(param, (PropertyInfo)pkProp); break;
            default: throw new NotSupportedException("Invalid primary key member: " + pkProp.Name);
        }
        Expression body = Expression.Equal(
        memberExp, Expression.Constant(key, typeof(TKey)));
        var predicate = Expression.Lambda<Func<TEntity, bool>>(body, param);
        return table.Single(predicate);
    }

It's a DataContext Extension Method that has stuff I need. However, it requires generic parms I don't have available - attributes don't allow generic subcalsses, so....
I have hacked the code to this point:
    public override bool IsValid(object value)
        SomeDataContext context = SomeDataContext.GetNewDataContext();
        var table = context.GetTable(_EntityType);
        var codeProp = (from member in context.Mapping.GetMetaType(_EntityType).DataMembers
                        where member.Name == _PropertyName
                        select member.Member).Single();
        ParameterExpression param = Expression.Parameter(_EntityType, "x");
        MemberExpression memberExp = Expression.Property(param, (PropertyInfo)codeProp);
        Expression body = Expression.Equal(memberExp, Expression.Constant(value, typeof(char)));
        Type lambdaType = typeof(Func<,>).MakeGenericType(_EntityType, typeof(bool));
        var predicate = Expression.Lambda(lambdaType, body, param);
        object code = table.FirstOrDefault(predicate);
        if (code != null)
        {
            return false;
        }
        return true;
    }

This line is bad:
        object code = table.FirstOrDefault(predicate);

as I stated here the answers to which don't help.

*

*var enumerator =
((IEnumerable)table).GetEnumerator();object
code = enumerator.MoveNext() ?
enumerator.Value : null;
is not useful in my attempt to build the expression tree.

*IEnumerable<object> tableGeneric =
((IEnumerable)table).OfType<object>();
has issues when I try:
object code = tableGeneric.FirstOrDefault(predicate);
So, I am pretty stuck. Any ideas out there?
Thanks.

A: The end-run you may be looking for is that as far as I can tell you really want a method like:
public bool IsValid<TEntity>()
{
    // validation logic goes here
}

So that you can perform the check(s) that you need, but you need to implement it in a method that only has the run-time-type available to it:
public bool IsValid(Type entityType)
{
    // ???
}

If that is the case, then you implement the first code-block with the logic you need, and you implement the second method as:
public bool IsValidWrapper(Type entityType)
{
    // You may want to be stricter than this, but the essence is to
    // get a handle to the generic method first...
    MethodInfo genMethod = GetType().GetMethod("IsValid");

    // Bind it to the type you want to operate on...
    MethodInfo method = genMethod.MakeGenericMethod(entityType);

    // And invoke it...
    return (bool) method.Invoke(this, null);
}

It won't win any beauty contests or performance crowns, but it will get you what you need. And note that if performance is a concern, you could keep a lookup from Type to a delegate with the signature bool delegate() so that you do not have to use slow reflection for a given type more than once to perform the type binding.


text:
Q: 3 Drop downs list to populate a search bar I am trying to make a drop down list which populates a search bar from 3 different drop down lists..  I am trying to have it update the search bar after each selection and keep the prior selections,  so it would read 175/55/17 in the search bar. Yes I am a complete noob, please help!  Here's what I have so far:
Here's my updated code, still doesn't populate the search field on the site or on http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_regexp_i
What am I doing wrong?
    <!DOCTYPE html>
<html>
<head>
<script language= "javascript" stype="text/javascript" type:"text/javascript">
$(document).ready(function() { $('select').change(function () {
$('#_shop_itemsearch_query').val($('#Width').val() + '/' + $('#height').val() + '/' +
$('#size').val()); }); }); </script>
</head>
<body>
 <input type="text" name="_shop_itemsearch_query" id="_shop_itemsearch_query" class="v2_shop_form_input">

<form action=""> <select name="Width" id="width">
<option value="175"selected>175</option>
<option value="185">185</option>
<option value="195">195</option>
<option value="205">205</option>
<option value="215">215</option>
<option value="225">225</option>
<option value="235">235</option>
<option value="245">245</option>
<option value="255">255</option>
<option value="265">265</option>
<option value="275">275</option>
<option value="285">285</option>
<option value="295">295</option>
<option value="305">305</option>
<option value="315">315</option>
<option value="325">325</option>
<option value="335">335</option>
<option value="345">345</option>
</select>
<form action="">
<select name="Height" id="height">
<option value="20"selected>20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
<option value="40">40</option>
<option value="45">45</option>
<option value="50">50</option>
<option value="55">55</option>
<option value="60">60</option>
<option value="65">65</option>
<option value="70">70</option>
<option value="75">75</option>
<option value="80">80</option>
<option value="85">85</option>
</select>
<form action="">
<select name="Size" id="size">
<option value="15"selected>15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="24">24</option>
<option value="25">25</option>
</select>
</body>
</html>

A: $(document).ready(function() {
    $('select').change(function () {
        $('#_shop_itemsearch_query').val($('#Width').val() + '/' + $('#height').val() + '/' + $('#size').val());
    });
});

jsFiddle example

A: $('select').change(function(){
    var str = "";

    $('select').each(function(index){
        str += $(this).val();
        if(index != $('select').length - 1)str += '/';
    })

    $('#_shop_itemsearch_query').val(str)
})

Not tested but should work.


text:
Q: Rotating a plane relative to a camera I am trying to make a child 2d plane rotate a little more (about 20 to 30 degrees) to the left or right on its y axis when a camera is looking directly at the left or right edge of the plane, so the plane never 'disappears'. I use unity 3d and Js
This is my attempt
var checks : float[];
var myRots : float[];
if(Mathf.Clamp(cam.transform.eulerAngles.y, checks[i]-5, checks[i] + 25) == cam.transform.eulerAngles.y)
transform.localEulerAngles.y = transform.parent.transform.rotation.y * myRots[i];

Here i manually input a camera degree in checks and rotate the character a certain amount with myrot. The thing is when the parent rotates, the child plane set rotations become off. What am i missing to allow the plane to behave this way no matter what the parent object's rotation is?


text:
Q: How do I use trig functions correctly? Given a direction in degrees and a distance, I am attempting to use the functions math.sin and math.cos to calculate the x and y distance a user would have to travel over a 5x5 grid.
A) Can someone tell me why my code is experiencing logic errors? It all checks out to me.
Please input the angle in degrees of the fire quickly!90
Please input the distance of the fire ~VERY~ quickly (input a number between 1 and 5)5
The fire is 1.000000 streets to the west of the firehouse!
The fire is 5 streets to the south of the firehouse!

It returns the wrong direction to go (south instead of north), and it instructs the user to go west 1 block. This is dreadful.
My second question is this:
How would I make it so the turtle would draw a blue line along the grid from the center point to whichever block was closest to the grid coordinates the user input.
CODE:
import turtle
import math
NUMBER_OF_LICENSES=10

def goodbyeMessage():
    print("Thank you for using the program!")

def getInfo():
    fire_Direction=math.degrees(float(input("Please input the angle in degrees of the fire quickly!")))
    fire_Distance=float(input("Please input the distance of the fire ~VERY~ quickly (input a number between 1 and 5)"))
    return fire_Direction,fire_Distance

def announceDirections(horizontolDirection,verticalDirection):

    if horizontolDirection < 0:
        print("The fire is %f streets to the west of the firehouse!" %abs(int(horizontolDirection)))
    elif horizontolDirection > 0:
        print("The fire is %f streets to the east of the firehouse!" %abs(int(horizontolDirection)))
    else:
        pass

    if verticalDirection < 0:
        print("The fire is %d streets to the south of the firehouse!" %abs(int(verticalDirection)))
    elif verticalDirection > 0:
        print("The fire is %d streets to the north of the firehouse!" %abs(int(verticalDirection)))
    else:
        pass

    if verticalDirection == 0 and horizontolDirection == 0:
        print("The firehouse is on fire!")

def giveDirection(fire_Direction,fire_Distance):
    horizontolDirection = round(fire_Distance * (math.cos(fire_Direction)))
    verticalDirection = round(fire_Distance * (math.sin(fire_Direction)))
    announceDirections(horizontolDirection,verticalDirection)

    return horizontolDirection, verticalDirection

def reportFire():

    fire_Direction,fire_Distance=getInfo()
    horizontolDirection,verticalDirection = giveDirection(fire_Direction,fire_Distance)

def drawHorizontal():
    turtle.speed(0)
    turtle.penup()
    turtle.forward(-300)
    turtle.left(90)
    turtle.forward(300)
    turtle.right(90)
    turtle.pendown()
    for i in range(5):
        turtle.forward(500)
        turtle.forward(-500)
        turtle.right(90)
        turtle.forward(100)
        turtle.left(90)

    turtle.forward(500)
    turtle.left(90)
    turtle.forward(500)
    turtle.left(90)
    turtle.forward(500)
    turtle.left(180)

def drawVertical():
    for i in range(5):
            turtle.forward(100)
            turtle.right(90)
            turtle.forward(500)
            turtle.forward(-500)
            turtle.left(90)
    turtle.forward(-500) #Back to upper left corner which will be main drawing control point

def drawFireStation():
    #From main drawing control point
    turtle.penup()
    #225 instead of 250 so firestation circle is centered in middle of grid
    turtle.forward(225)
    turtle.right(90)
    turtle.forward(250)
    turtle.pendown()
    turtle.circle(25)
    turtle.penup()
    turtle.forward(-250)
    turtle.left(90)
    turtle.forward(-225)
def drawGrid():
    turtle.showturtle()
    turtle.speed(0)
    drawHorizontal()
    drawVertical()
    drawFireStation()

def main():
    drawGrid()
    for i in range(NUMBER_OF_LICENSES):
        reportFire()
    goodbyeMessage()

if __name__ == "__main__":
    main()

A: The trig functions expect their arguments to be in radians
You can use the math.radians() function to convert degrees to radians
eg:
fire_Direction = math.radians(fire_Direction)
horizontolDirection = round(fire_Distance * (math.cos(fire_Direction)))
verticalDirection = round(fire_Distance * (math.sin(fire_Direction)))

EDIT:
I noticed you are using math.degrees incorrectly here:
fire_Direction=math.degrees(float(input("Please input the angle in degrees of the fire quickly!")))

You should probably just change that one to math.radians(...) (which is the inverse of math.degrees)


text:
Q: Increasing Docker partition size on Google Cloud Compute instance running container image I have an Apache server in production that is running in a Docker container, which I've deployed to a Google Compute instance using the "gcloud compute instances create-with-container" command. The /var/www/html folder is mounted onto the container from the boot disk of the computer instance to make it persistent, using the --container-mount-host-path flag:
gcloud compute instances create-with-container $INSTANCE_NAME \
    --zone=europe-north1-a \
    --container-image gcr.io/my-project/my-image:latest \
    --container-mount-host-path mount-path=/var/www/html,host-path=/var/www/html,mode=rw \
    --machine-type="$MACHINE_TYPE"

But now I've ran into the problem that the size of the Docker partition is only 5.7G!
Output of df -h:
...
/dev/sda1       5.7G  3.6G  2.2G  62% /mnt/stateful_partition
overlay         5.7G  3.6G  2.2G  62% /var/lib/docker/overlay2/4f223d8157033ce937a79af741df3eadf79a02d2d003f01a085301ff66884bf2/merged
overlay         5.7G  3.6G  2.2G  62% /var/lib/docker/overlay2/86316491e2bb20bc300c1cc55c9f9254001ed77d6ec7f05f716af1e52fe15f53/merged
...

I had assumed that the partition size would increase automatically, but I ran into the problem where the website couldn't write files onto disk anymore because the partition was full. As a quick fix, I ran "docker prune -a" (there were a bunch of old images hanging around) on the host machine to make some more space on the docker partition.
So my question is, what is the proper way of increasing the size of the partition?

A: You can resize the boot disk in the Google Cloud Console GUI. However, since this is a container host, I recommend deleting the virtual machine instance and creating a new instance with the correct configuration.
The default disk size is usually 10 GB. To create a virtual machine instance with a larger disk, specify that when creating the instance.
Add the following to your CLI command:
--boot-disk-size=32GB

Optionally specify the type of persistent disk to control costs:
--boot-disk-type=pd-standard

gcloud compute instances create-with-container


text:
Q: Retrofit 2 return List from Json is empty I have been fighting with Retrofit 2.3 for about 2 weeks now. The List always comes back as empty for me. It simply makes a call and gets the JSON information yet it won't process the list.
Json appears like this:
{
"users": [
    {
        "id": 2,
        "name": "Users Name",
        "username": "myusername",
        "facebook_id": null,
        "level": "1",
        "birthdate": "1999-09-09T00:00:00+00:00",
        "email": "user@gmail.com",
        "activated": "",
        "created": "2017-12-07T04:18:30+00:00",
        "answers": [
            {
                "id": 31,
                "question_id": 2,
                "user_id": 2,
                "answer": "School",
                "questions": [
                    {
                        "id": 2,
                        "question": "Where did you meet your best friend?"
                    }
                ]
            },
            {
                "id": 32,
                "question_id": 3,
                "user_id": 2,
                "answer": "Dog",
                "questions": [
                    {
                        "id": 3,
                        "question": "What was your first pet's name?"
                    }
                ]
            }
        ]
    }
],
"message": "Success"
}

Retrofit Interface class:
public interface RestInterface {

String url = "http://myurl.com";

/**
 * Login
 *
 * @param username  Username
 * @param password  Password
 *
 */

@FormUrlEncoded
@Headers("User-Agent:My-Application")
@POST("login")
Call<userlogin> Login(@Field("username") String username,
                      @Field("password") String password);
}

Userlogin class:
public class userlogin {

@SerializedName("users")
@Expose
private List<users> users;
@SerializedName("message")
@Expose
private Object message;

public List<users> getUsers() {
    return users;
}

public void setUsers(List<users> users) {
    this.users = users;
}

public Object getMessage() {
    return message;
}

public void setMessage(Object message) {
    this.message = message;
}

}

users class:
public class users {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("username")
    @Expose
    private String username;
    @SerializedName("facebook_id")
    @Expose
    private String facebookId;
    @SerializedName("level")
    @Expose
    private String level;
    @SerializedName("birthdate")
    @Expose
    private String birthdate;
    @SerializedName("email")
    @Expose
    private String email;
    @SerializedName("activated")
    @Expose
    private String activated;
    @SerializedName("created")
    @Expose
    private String created;

    @SerializedName("answers")
    @Expose
    private List<Answer> answers = null;

    public users(){

    }

    public Integer getId() {
            return id;
    }

    public void setId(Integer id) {
            this.id = id;
    }

    public String getName() {
            return name;
    }

    public void setName(String name) {
            this.name = name;
    }

    public String getUsername() {
            return username;
    }

    public void setUsername(String username) {
            this.username = username;
    }

    public String getFacebookId() {
            return facebookId;
    }

    public void setFacebookId(String facebookId) {
            this.facebookId = facebookId;
    }

    public String getLevel() {
            return level;
    }

    public void setLevel(String level) {
            this.level = level;
    }

    public String getBirthdate() {
            return birthdate;
    }

    public void setBirthdate(String birthdate) {
            this.birthdate = birthdate;
    }

    public String getEmail() {
            return email;
    }

    public void setEmail(String email) {
            this.email = email;
    }

    public String getActivated() {
            return activated;
    }

    public void setActivated(String activated) {
            this.activated = activated;
    }

    public String getCreated() {
            return created;
    }

    public void setCreated(String created) {
            this.created = created;
    }

    public List<Answer> getAnswers() {
            return answers;
    }

    public void setAnswers(List<Answer> answers) {
            this.answers = answers;
    }

}

Basically what happens is when it is called my "message" part comes back "Successful" which on my PHP side basically just states there were no errors. If there were any then it would return the error for display.
When trying to get the users information it always comes back with an empty List.
My response is always the same:
03-14 20:06:26.698 30995-30995/com.josh.testapp D/Response: {"message":"Success","users":[]}
03-14 20:06:26.699 30995-30995/com.josh.testapp I/System.out: Users:: []
03-14 20:06:26.699 30995-30995/com.josh.testapp D/Message: Success
I'm not sure what it is I'm missing. The users should be coming back as a list containing user information, in this case just the information of the user logging in. But in other parts, this will display sub-users information as well which is why it is in List form in the first place.
Please help or guide me in the right direction.
login.java (where the call is made)
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RestInterface.url)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        RestInterface restInterface = retrofit.create(RestInterface.class);

        Call<userlogin> call = restInterface.Login(
                username.getText().toString(),                            // username
                pass.getText().toString()                                 // password
        );

        call.enqueue(new Callback<userlogin>() {
            @Override
            public void onResponse(Call<userlogin> call, retrofit2.Response<userlogin> response) {

                if (response.isSuccessful()) {
                    userlogin ul = response.body();

                    try{
                        String res = new Gson().toJson(response.body());
                        Log.d("Response", res);
                        System.out.println("Users:: " + ul.getUsers().toString());
                        Log.d("Message", ul.getMessage().toString());

                        List<users> userList = ul.getUsers();

                        for(int i = 0; i < userList.size(); i++){
                            Log.d("Users", userList.get(i).getUsername());
                        }

                    } catch (Exception e){
                        Log.d("exception", e.getMessage());
                    }
                } else {
                    Log.d("unSuccessful", response.message());
                }
            }

            @Override
            public void onFailure(Call<userlogin> call, Throwable t) {
                Log.d("onFailure", t.getMessage());
            }
        });

A: After AbdulAli pointed out that it appeared to not be receiving the users list I decided to look over my code and run a few more tests on the server API. I discovered there was an issue with sessions. They weren't picking up and therefor returned a "Successful" yet empty user list. After implementing some CookieJar functions in I was able to pass my cookie for sessions and the user list was no longer empty.
While I feel like an idiot for missing something so obvious, I am very grateful for you pointing that out AbdulAli.


text:
Q: Yeoman copy function doesn't work after prompting i am fiddleing around with yeoman and want to write my first generator for a simple html5 boilerplate. My problem is, that the two functions in my generator work well on their own but not together and i don't know why. I checked some generators from the yeoman page, but i don't see what i am doing wrong. I hope you can help me. This is my code:
'use strict';
var generators = require('yeoman-generator');
var yosay = require('yosay');

module.exports = generators.Base.extend({

  initializing: function(){
    this.log(yosay("\'Allo \'allo I will create your HTML5 Boilerplate..."));
  },

  prompting: function() {
    var done = this.async();
    this.prompt({
      type: 'input',
      name: 'name',
      message: 'Your project name',
      //Defaults to the project's folder name if the input is skipped
      default: this.appname
    }, function(answers) {

      this.props = answers
      this.log(answers.name);
      done();
    }.bind(this));
  },

  writing: function(){
    this.fs.copyTpl(
      this.templatePath('_page/_index.html'),
      this.destinationPath('index.html'),
      { title: "answers.name" }
    );
  },
});

Thanks in advance!

A: Try using the Promises version of the prompting function, as shown on yeoman.io.
Example:
prompting: function() {
    return this.prompt({
      type: 'input',
      name: 'name',
      message: 'Your project name',
      //Defaults to the project's folder name if the input is skipped
      default: this.appname
    }).then(function(answers) {
      this.props = answers
      this.log(answers.name);
    }.bind(this));
  },

Changes:

*

*add return before this.prompt().

*change this.prompt(prompts, callback); to this.prompt(prompts).then(callback);


text:
Q: How To Load Partial View after AJAX Insert as Flash Message I have a partial view in my system, which i include in all of my views which then displays any of the flash messages I might have coming from controller. I just started using jQuery and inserting record into my db dynamically.
Allthrough script works(found it elsewhere and modified it), I want to change how i load my flash messages, I dont want to specify them on my view files in script section, I want to send them from my controller and load my partial view like I do on my other pages.
part of my script;
        $('#submit').click(function () {
            $.ajax({
                url: postURL,
                method: "POST",
                data: $('#add_name').serialize(),
                type: 'json',
                success: function (data) {
                    if (data.error) {
                        printErrorMsg(data.error);
                    } else {
                        i = 1;
                        $('.dynamic-added').remove();
                        $('#add_name')[0].reset();
                        $(".print-success-msg").find("ul").html('');
                        $(".print-success-msg").css('display', 'block');
                        $(".print-error-msg").css('display', 'none');
                        $(".print-success-msg").find("ul").append(
                            '
New Project Space has been added
');
                    }
                }
            });
        });

        function printErrorMsg(msg) {
            $(".print-error-msg").find("ul").html('');
            $(".print-error-msg").css('display', 'block');
            $(".print-success-msg").css('display', 'none');
            $.each(msg, function (key, value) {
                $(".print-error-msg").find("ul").append('
' + value + '
');
            });
        }

Part of controller
    if ($validator->passes()) {
        foreach ($request->input('label') as $key => $value) {
            Space::create([
                'label'=>$value,
                'user_id' => $user,
                'customer_id' =>$customer,
                'project_id' => $projectid,
                ]);
        }
        return response()->json(['success'=>'done']);
    }

    return response()->json(['error'=>$validator->errors()->all()]);

part of partial
@if ($message = Session::get('success'))

    <button type="button" class="close" data-dismiss="alert">×</button>
        {{ $message }}

@endif

A: Laravel has a really cool feature to allow you to load a partial view from the controller into your view via ajax.
Create a partial view, let's call it partialDisplay.  Put your html, css, and any loops with the $variable and any
s inside into this view and take it out of the ajax success function.  Then, you can just call your partial and send the actual message.
Name a section of the partial view (say 'messageContent') to be called by the controller.  The partial can still load any base views or other dependencies, but we will focus on the area you need, messageContent
Partial View:
@extends('layouts.baseModal')

 @section('messageContent')
    // css, loops of data, etc go here
     @foreach($var as $v)

{{$v->somethingLikeNameOrmessage}}

   // etc
 @stop

Controller:
$view = view('partialDisplay', compact('yourVar(s)'));

    $sections = $view->renderSections(); // returns an associative array of 'content', 'pageHeading' etc

    return $sections['messageContent']; // this will only return whats in the content section

Then, in ajax, you can just stick in the whole view, complete with formatting, etc:
success: function (html) {
       $("#yourMessageDiv").html(html);
 },


text:
Q: Access LinkedIn r_fullprofile with LinkedIn Developer Partner Program? I tried to reach out to LinkedIn support for more information on how to get LinkedIn Developer Partnership to access the full LinkedIn API and gain access to a user's LinkedIn Full Profile, but they directed me to StackOverflow to use the Linkedin tag. Does anybody know who I should get in touch with to access the full LinkedIn profile API?

A: Linkedin removed r_fullprofile feature after update to api v2. See attached image with official support response.


text:
Q: PHP mail() strange additional information automatically sending Well, recently, I created a script and placed it up on a domain I have access to. Once I attempted to send an email, the email went through, no problem, but there was a thing that I found strange.
My subject field isn't being set. My subject line is completely blank as if I never sent one. It also doesn't seem as if my headers are being sent through either. (See this: Image)
Also, is there a reason why these things are sent in the email along with my message? Like, could it possibly be a setting in php.ini?

Message-Id: message-id-here@**.gs
Date: Wed,  2 Jan 2013 05:37:47 +0400 (MSK)
From: www-data@**.gs (www-data)
Return-Path: www-data@**.gs
X-OriginalArrivalTime: 02 Jan 2013 01:37:47.0814 (UTC)
  FILETIME=[C5131C60:01CDE889]
I'm sending an email, and this is the message.
Is this going through correctly?

Currently, this is what my script looks like.

    <title>Email</title>

    <?php
        ini_set("mail.add_x_header", "Off");
        if(isset($_POST['send']))
        {
            $To = ((isset($_POST['to'])) ? $_POST['to'] : '');
            $Subject = ((isset($_PST['subject'])) ? $_POST['subject'] : '');
            $Message = ((isset($_POST['message'])) ? $_POST['message'] : '');
            $Headers = ((isset($_POST['from'])) ? "From: " . $_POST['from'] . "\r\n" : '');
            $Headers = ((isset($_POST['reply-to'])) ? "Reply-to: " . $_POST['reply-to'] . "\r\nReturn-Path:" . $_POST['reply-to'] . "\r\n" : '');
            if(mail($To, $Subject, $Message, $Headers))
            {
                echo 'Sent to ' . $To . '.';
            }
        }
    ?>

    <form method="POST">
        To: <input type="text" name="to" value="" />

        Subject: <input type="text" name="subject" value="" />

        Message: <textarea name="message" style="width:300px; height:200px;"></textarea>

        From: <input type="text" name="from" value="" />

        Reply-To: <input type="text" name="reply-to" value="" />

        <input type="submit" name="send" />
    </form>

A: Your subject isn't set because you have a typo. Change:
$Subject = ((isset($_PST['subject'])) ? $_POST['subject'] : '');

to:
$Subject = ((isset($_POST['subject'])) ? $_POST['subject'] : '');

As for headers, your Return-To overrides From header. You should also change \r\n to \n as some email clients interpret \r\n as "end of all headers".
So, instead of:
$Headers = ((isset($_POST['from'])) ? "From: " . $_POST['from'] . "\r\n" : '');
$Headers = ((isset($_POST['reply-to'])) ? "Reply-to: " . $_POST['reply-to'] . "\r\nReturn-Path:" . $_POST['reply-to'] . "\r\n" : '');

Do:
$Headers = array();
if (isset($_POST['from']))
{
    $Headers[] = "From: " . $_POST['from'];
}
if (isset($_POST['reply-to']))
{
    $Headers[] = "Reply-to: " . $_POST['reply-to'];
    $Headers[] = "Return-Path: " . $_POST['reply-to'];
}
$Headers = implode("\n", $Headers) . "\r\n";


text:
Q: Load gif in image view In my application has a part that will grab images from a server. The problem is that while images are being loaded in the application that space remains vacant. How do I get that gif to warn the user that the image is being loaded?
Example: http://goo.gl/mwFCC
Thank you!

A: You can use a progress Bar(Custom Progress bar) in the vacant space and as soon as your image is downloaded remove it.
Create a Xml in Drawable as follows
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:drawable="@drawable/image1" android:duration="200" />
   <item android:drawable="@drawable/image2" android:duration="200" />
</animation-list>

Now your progress bar will look like this
// Put this in Your vacant space
 <ProgressBar
android:id="@+id/myId"
android:indeterminateDrawable="@drawable/my_progress_indeterminate"
        android:layout_height="50dp"
 android:layout_width="50dp">
</ProgressBar>

A: While the remote image is being downloaded, show an animated GIF or some other kind of animation (e.g. using something like this http://androidosbeginning.blogspot.se/2010/09/gif-animation-in-android.html) in the view that should hold the remote image. Once the download is complete, notify the main thread and tell it to update the view with the downloaded image.

A: You can use the buit in android ProgressDialog to achieve this, For exemple use an AsynchronousTask to download the image on your onPreExecute() show your dialog on doInBackground()  process downloading and in onPostExecute() dismiss your dialog and display the result. You can also take a look at frame animation if you want to use custom dialog.


text:
Q: Count number of occurrence of each word in python is a set of string? I have the following 3 sentences that I searched for in a text and appended them to the list sentence using sentence.append()
For example
sentence[0]=" hello my name is John"
sentence[1]="good morning I am John"
sentence[2]= "hello I am Smith"

I want to assign a score for each sentence and each word based on the number of occurrences of each word in all the 3 sentences.
for example:
Hello score= 2 since it appeared twice **SOLVED**
sentence[0] score= hello score( which is 2) + my (1) + name (1) + is (1) + John(2) = 6

So I used that to count the occurrence (score) of each word in the sentence, my question is how can I use it to calculate the score of the sentence ?
dict = {}
for sentenceC in sentence:
    for word in re.split('\s', sentenceC): # split with whitespace
        try:
            dict[word] += 1
        except KeyError:
            dict[word] = 1
print (dict)

A: Break the problem up into subtasks
def getWordScores(sentences):
   scores = {}
   for sentence in sentences:
      for word in sentence.strip().split():
          word = word.lower()
          scores[word] = scores.get(word,0) + 1
   return scores

def getSentenceScore(sentence, word_scores):
   return sum(word_scores.get(w.lower(), 0) for w in sentence.strip().split())

Then compose the tasks to get the solution
word_scores = getWordScores(sentence)
print word_scores['hello']
print getSentenceScore(sentence[0], word_scores)

A: You can get your score like this:
import re

sentence = list()

sentence.append(" hello my name is John")
sentence.append("good morning I am John")
sentence.append("hello I am Smith")

value = dict()
for sentenceC in sentence:
    for word in sentenceC.strip().split(" "): # split with whitespace
        try:
            value[word.lower()] += 1
        except KeyError:
            value[word.lower()] = 1
print (value)

score = dict()
number = 1
for sentenceC in sentence:
    for word in sentenceC.strip().split(" "): # split with whitespace
        try:
            score[number] += value[word.lower()]
        except KeyError:
            score[number] = value[word.lower()]
    number += 1

print score

#output: {1: 7, 2: 8, 3: 7}


text:
Q: $.ajax is not working? How i call ajax inside jQuery onclick function? I am calling the ajax inside a function. The control is going inside the function but not executing ajax call it is showing 404.
[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
jquery.min.js:2 GET http://localhost:5080/Employee-Mybatis/employee/employee/employeeInfo 404
code is :-
<script>
function showEmpDetails(empid)
{
    console.log(empid);
    $.ajax({
        url: "employee/employeeInfo",
        async: false,
        success: function(result) {

            console.log(result);
        }
    });
}
</script>

I am using this src link for ajax :-
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>


text:
Q: Implement multiple functions in one method I am new to solid principle. I think i'm violating this kind of implementation:
class Students{
     public void Save(int id){
          if(id !== 0){
               //add students here...
          }else{
               //edit student details here...
          }
     }
}

There are many instances that you call different functionalities in one method. Is this right? or if not, please answer sample code. Thank You

A: There are alot of articles telling what solid does.
Found this one with a quick google.
https://www.codeproject.com/Articles/703634/SOLID-architecture-principles-using-simple-Csharp
As for you Students class.  It is probably a repository or services to get Students or Save students or to delete student. Only doing stuff around student data. (S(ingle resposibilty))
public void Save(Student studentModel)
{
    //Only save the studentModel
}

I injected the StudentModel in this function the only thing this function need is this model to do his magic. Refering to the D of(D)ependecy injection.
Please refer the link provided. And try to uphold the SOLID principle.
Makes your code eventually easier to understand/ maintain. And keep it KISS https://en.wikipedia.org/wiki/KISS_principle


text:
Q: Get contents of gapi Object I want to pull some Google Analytics data through GAPI. However, what I'm getting back is an array in an Object in an array. I don't know how to get the data out of this.
This is the response:
gapiReportEntry Object ( [metrics:gapiReportEntry:private] => Array ( [pageviews] => 102 [visits] => 79 [avgTimeOnSite] => 30.569620253165 [percentNewVisits] => 98.73417721519 [visitBounceRate] => 77.215189873418 [UniquePageviews] => 92 ) [dimensions:gapiReportEntry:private] => Array ( [browser] => Safari (in-app) ) )

And this is the code I ran:
define('ga_email','my_email');
define('ga_password','my_password');
define('ga_profile_id',$analyticsid);

require('Including/php/gapi-1.3/gapi.class.php');

$number = 0;

while($number < 3) {
    $date = date("Y-m-d",strtotime("-".$number." days"));

    $ga = new gapi(ga_email,ga_password);
    //$dimensions, $metrics, $sort_metric=null, $filter=null, $start_date=null, $end_date=null, $start_index=1, $max_results=30)
    $request = $ga->requestReportData(
        ga_profile_id,
        array('browser'),
        array('pageviews','visits','avgTimeOnSite','percentNewVisits','visitBounceRate','UniquePageviews',),
        array('-visits'),
        null,
        $date,
        $date,
        1,
        30
    );

    ${'data'.$number} = $request;

    $number++;

}

And then print_r($data0[0]); gives me this result.

A: Using the Gapi.class.php you should use $request->getVisits(); to get the visitcount, for the pageviews you would use $request->getPageviews(); etc.


text:
Q: required init?(coder aDecoder: NSCoder) not called I wrote my own Button,Textfield, ..., classes. In the storyboard in "Custom Class" I set the class to the UIElement. This works very well.
Now I needed a toolbar that is added programatically. When I add the Toolbar in my ViewController everything is fine. But I want to create my own toolbar class like this.
class MyOwnToolbar : UIToolbar {

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    //never called
    self.backgroundColor = UIColor.redColor()
    self.tintColor = UIColor.greenColor()
    self.barTintColor = UIColor.blueColor()
}

override init(frame: CGRect) {
   //error: super.init isn'T called on all paths before returning from initiliazer
}

In my ViewController I try to call like this:
fromToolBar = MyOwnToolBar() //call nothing?
fromToolBar = MyOwnToolBar(frame: CGRectMake(0,0,0,0)) //doesn't work because init(frame: CGRECT) doesnt work

Old code in my ViewController that worked:
    self.untilToolBar = UIToolbar(frame: CGRectMake(0,0,0,0))
    untilToolBar?.backgroundColor = redColor
    untilToolBar?.tintColor = greenColor
    untilToolBar?.barTintColor = blueColor

So I could use my working solution, but I want to unterstand why my code isn't working. So maybe somebody have a solution or good links.

A: It is depending how do you create you're MyOwnToolbar if you add this in interface builder and connect class to the UI element use method initWithCoder
If you're creating your MyOwnToolbar programmatically, you should use init or initWithFrame.
Example:
class MyOwnToolbar: UIToolbar {

      private func initialize() {
          self.backgroundColor = UIColor.redColor()
          self.tintColor = UIColor.greenColor()
          self.barTintColor = UIColor.blueColor()
      }

      override init(frame: CGRect) {
          super.init(frame: frame)
          initialize()
      }

     required init?(coder aDecoder: NSCoder) {
          fatalError("init(coder:) has not been implemented")
     }
}

A: Oleg got it right, if you use storyboard or a xib to create your view controller, then init?(coder aDecoder: NSCoder) will be called.
But you are building your view controller programmatically, so init(frame: CGRect) will be called instead of init?(coder aDecoder: NSCoder).
you should override init(frame: CGRect):
override init(frame: CGRect) {
    super.init(frame: frame)
    self.backgroundColor = UIColor.redColor()
    self.tintColor = UIColor.greenColor()
    self.barTintColor = UIColor.blueColor()
}


text:
Q: How to apply Dijkstra algorithm to find the optimal time for visiting shopping centres I tried this Synchronous Shopping problem on HackerRank and I had no clue how to approach it. So I looked at the editorial, and I am confused. Maybe I misunderstood how Dijkstra's single source shortest path algorithm works.
This is taken from the editorial:
He says

The shortest distance to the state D(V, B) denotes the minimum time required
  to visit shopping center V with fish from the mask B bought.

and then he describes two possible ways we might move from one state to another, and after that he says

When all the minimal times are calculated....

I assume he means, we should have considered all possible ways to obtain fish, after we reach node N. All 2^k ways. Like, we consider
1) we only have the first fish when we reach node N
2) we only have the second fish...
3) we only have the first fish and the second fish..
etc..
but if we run Dijkstra, it will calculate the shortest path from node 1 to node N, but we have to travel a specific path to get from node 1 to node N. And we will only get the fish available along those nodes. How do we calculate all other states? (reaching node N with different sets of fish)

A: Let me try to help you, as I recently did the exercise. I will try to build the solution or the main idea piece by piece.
Summary of the problem: There're two cats, they start at the shopping 1 and goes until N. At each shopping they buy a set of fishes and they can only stop at N if both cats have bought all fishes. Both cats can go different paths and revisit shopping mall.
The objective of the problem is finding the minimum time of buying all fishes, which is the maximum time between the two cats reach N and the two together bought all fishes available.
Now, let's try to build the solution up: Imagine that you have no fishes and you only want to know the shortest time that a cat would take to go from shopping 1 to N. Dijkstra can solve this problem, right? It would calculate all the shortest time from the source (shop 1) to all other nodes.
Next step is adding the fishes: Now, assume that we have only one cat and we have to buy fishes at each stop. Try to imagine the following: Instead of each vertex of your graph being just the shopping mall is the shopping and a combination of the fishes that the cat bought so far, storing information.
This means that a shopping can be added more than once to the priority queue, which does not happen in the "normal" Dijkstra algorithm. This allows you to calculate the shortest time from the source and all possible combinations to reach that shopping with fishes bought. Unfortunately, this increases the number of vertices to O(N*2^(k-1)). Make sure you store the shortest time for all vertices, we will use this in the next step.
Another essential trick is keeping the fishes in a bitset instead of a list or vector as buying fishes is an OR operation. Most bitwise operations used are constant O(1).
The last step is adding the second cat:If you calculate the Dijkstra as mentioned below, you will get all the shortest time, for all vertices, which are states for all shopping and fishes bought. We are interested only in the cases where we are at the shop N and the combination of fishes bought by the cat 1 and 2 are equal to all fishes bought.
What has been taken into account is that if one cat arrives at N, it has to wait the other to arrive, meaning that no matter what were the fishes that one cat bought, if the other arrive if the rest, that's fine.
Technically, you will process all the possible scenarios available for the shopping N and if the combination of fishes of the cat 1 and 2 are equal to all fishes bought, you get the shortest time (the minimum among all possibilities).
This is unfortunately a exhaustive approach but passes fine. This is the two for stacked after the Dijkstra processing.


text:
Q: Sort a string column by datetime in a DataTable I am trying to sort a DataTable on a string column by DateTime.
For various reasons, the column must be left as a string data type. I know I can copy the data out into another table, convert that column to a DateTime column, sort on that and copy it back but I'm wondering if there's a neater way.
I've tried the basics of DefaultView and LINQ to no prevail.

A: Stumbled upon a method right after I posted.
EnumerableRowCollection<DataRow> query = from row in dataTable.AsEnumerable()
                                         orderby DateTime.Parse(row.Field<string>(propertyName)) ascending
                                         select row;
dataTable = query.AsDataView().ToTable();

A: Try Add while create DataTable
    table.Columns.Add("dateValue", typeof(DateTime?));

    var orderedRows = from row in dt.AsEnumerable()
                      orderby  row.Field<DateTime>("Date")
                      select row;
    DataTable tblOrdered = orderedRows.CopyToDataTable();

(Or)
 var orderedRows = from row in dt.AsEnumerable()
                      let date = DateTime.Parse(row.Field<string>("Date"), CultureInfo.InvariantCulture)
                      orderby date
                      select row;

A: You can sort dates as a string if you use the format YYYYMMDD

A:         List<DataRow> rows = new List<DataRow>();
        foreach (DataRow row in table.Rows)
        {
            rows.Add(row);
        }
        rows.Sort((r1,r2)=>DateTime.Parse((string)r1["columnname"]).CompareTo(DateTime.Parse((string)r2["columnname"])));
        var clone = table.Clone();
        rows.ForEach(r => clone.Rows.Add(r.ItemArray));
        return clone;


text:
Q: BERT Binary Text Classifier giving ValueError: Expected input batch_size doesn`t match target I am working on binary text classification problem and using Bert sequence classification model in pytorch. Here is the link to colab notebook.
After training the model, I am trying to predict on sample text. I have checked the shape of the input_id tensor it is [1,128]. I have used batch_size = 16.
review_text = "I love completing my todos! Best app ever!!!"

encoded_review = tokenizer.encode_plus(
  review_text,
  max_length=MAX_SEQ_LEN,
  add_special_tokens=True,
  return_token_type_ids=False,
  pad_to_max_length=True,
  return_attention_mask=True,
  return_tensors='pt',
)
input_ids = encoded_review['input_ids'].to(device)
print(input_ids.shape)
attention_mask = encoded_review['attention_mask'].to(device)
print(attention_mask.shape)
output = model(input_ids, attention_mask)
output

This produces the error
Truncation was not explicitely activated but `max_length` is provided a specific value, please use `truncation=True` to explicitely truncate examples to max length. Defaulting to 'longest_first' truncation strategy. If you encode pairs of sequences (GLUE-style) with the tokenizer you can select this strategy more precisely by providing a specific strategy to `truncation`.
torch.Size([1, 128])
torch.Size([1, 128])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-22-74eeba339c4c> in <module>()
     14 attention_mask = encoded_review['attention_mask'].to(device)
     15 print(attention_mask.shape)
---> 16 output = model(input_ids, attention_mask)
     17 output

7 frames
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
    720             result = self._slow_forward(*input, **kwargs)
    721         else:
--> 722             result = self.forward(*input, **kwargs)
    723         for hook in itertools.chain(
    724                 _global_forward_hooks.values(),

<ipython-input-7-71a85d6c1fce> in forward(self, text, label)
      8
      9     def forward(self, text, label):
---> 10         loss, text_fea = self.encoder(text, labels=label)[:2]
     11
     12         return loss, text_fea

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
    720             result = self._slow_forward(*input, **kwargs)
    721         else:
--> 722             result = self.forward(*input, **kwargs)
    723         for hook in itertools.chain(
    724                 _global_forward_hooks.values(),

/usr/local/lib/python3.6/dist-packages/transformers/modeling_bert.py in forward(self, input_ids, attention_mask, token_type_ids, position_ids, head_mask, inputs_embeds, labels, output_attentions, output_hidden_states)
   1282             else:
   1283                 loss_fct = CrossEntropyLoss()
-> 1284                 loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
   1285             outputs = (loss,) + outputs
   1286

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
    720             result = self._slow_forward(*input, **kwargs)
    721         else:
--> 722             result = self.forward(*input, **kwargs)
    723         for hook in itertools.chain(
    724                 _global_forward_hooks.values(),

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/loss.py in forward(self, input, target)
    946     def forward(self, input: Tensor, target: Tensor) -> Tensor:
    947         return F.cross_entropy(input, target, weight=self.weight,
--> 948                                ignore_index=self.ignore_index, reduction=self.reduction)
    949
    950

/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction)
   2420     if size_average is not None or reduce is not None:
   2421         reduction = _Reduction.legacy_get_string(size_average, reduce)
-> 2422     return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
   2423
   2424

/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in nll_loss(input, target, weight, size_average, ignore_index, reduce, reduction)
   2214     if input.size(0) != target.size(0):
   2215         raise ValueError('Expected input batch_size ({}) to match target batch_size ({}).'
-> 2216                          .format(input.size(0), target.size(0)))
   2217     if dim == 2:
   2218         ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)

ValueError: Expected input batch_size (1) to match target batch_size (128).

A: As per your code at colab is concerned, you are not converting the data in specified shape which is [B,*dims] where B is batch size and *dims are other dimensions. So use torch.unsqueeze(input_ids,0) read here to add a dimension as batch_size.


text:
Q: AtEndOfStream condition error in vbscript I encounter a problem with a double loop in a vbs script.
This is the script:
Set fso = CreateObject("Scripting.FileSystemObject")
Set sourceFile = fso.OpenTextFile("source.txt")
Set validFile = fso.OpenTextFile("valid.txt")
Set result = fso.CreateTextFile("result.txt", True)

Do while validFile.AtEndOfStream <> True
Wscript.echo validFile.AtEndOfStream
  validLine = validFile.ReadLine
  Do while sourceFile.AtEndOfStream <> True
    sourceLine = sourceFile.ReadLine
    If InStr(sourceLine,validLine) > 0 then
        result.WriteLine(sourceLine)
    End if
  Loop
sourceFile.Close
Loop
Wscript.echo "End of script"
result.close
validFile.close

The second Loop will not be reset at its end, so the next first loop start, it does nothing.
The sourceFile.AtEndOfStream return -1 unlike 0.
I have put sourceFile.Close wich seems to do a reset but nothing append.
Thx for your help.

A: While you can read each line from one (source) file and loop over all lines of a second file (valid) to use each line in valid on each line in source by opening/closing valid in the outer loop, you shouldn't.
Load the content of valid into memory before you start the loop on source.
If you give some details about your real world problem - what do you want to check source for? - we could discuss how and into what to load valid.

A: When you read a file in a loop, the cursor (i.e. the position in the file from which you currently read) doesn't magically return to the beginning of the file after the loop ends. Particularly not when you close the file after the loop (because then you don't even have a file anymore). You need re-open it before you can read it again. Also, I'd suggest using Until condition instead of While condition <> true as the former is much better readable than the latter:
Do Until validFile.AtEndOfStream
  validLine = validFile.ReadLine

  Set sourceFile = fso.OpenTextFile("source.txt")
  Do Until sourceFile.AtEndOfStream
    ...
  Loop
  sourceFile.Close
Loop

However, as Ekkehard.Horner pointed out, reading a file over and over again is usually not a good choice performance-wise. If at least one file is relatively small (compared to the available amout of RAM) it's better to read that file into an array and iterate over that array in the inner loop:
sourceText = Split(fso.OpenTextFile("source.txt").ReadAll, vbNewLine)

Do Until validFile.AtEndOfStream
  validLine = validFile.ReadLine
  For Each sourceLine In sourceText
    ...
  Next
Loop

A: What is it that you're trying to do?
I can see at least one problem here right off. If you do sourceFile.Close then try to read it on the next loop, you won't be able to because it's closed.
Try moving this line
Set sourceFile = fso.OpenTextFile("source.txt")
right before this line in the script
Do while sourceFile.AtEndOfStream <> True
You'll be opening and closing the file at each loop, which is for each line in the valid.txt file. This doesn't seem like good practice, but if you explain what your goal is maybe I could help find a better way.

A: Thx for your help.
Indeed, I had not enough time to do things well but I have completely rewrite this little script with your suggestions and it works great!!
Set fso = CreateObject("Scripting.FileSystemObject")
Set validFile = fso.OpenTextFile("valid.txt")
Set result = fso.CreateTextFile("result.txt", True)
sourceText = Split(fso.OpenTextFile("source.txt").ReadAll, vbNewLine)

Do until validFile.AtEndOfStream

  validLine = validFile.ReadLine

  For Each sourceLine In sourceText

    If InStr(sourceLine,validLine) > 0 then
        result.WriteLine(sourceLine)
    End if

  Next

Loop

Wscript.echo "Fin du traitement"
result.close
validFile.close

Bye.


text:
Q: how to keep a hash value in the table column in rails i am very new to rails . I am having a table holding all users basic information like
users(id,name,email)
now i am trying to keep some additional information of these users in a separate table like
user_details(id,user_id,additional_info)
I have created this user_details table . Now i try to keep some default records for checking . how to keep the hash value of the user's additional details in the additional_info like if my additional details are user's (designation,salary,prjtname) in the column additional_info of the User_details table.
Also what datatype i have to give for this additional_info column of the User_details table. Please give some suggestions ..

A: The data type for that column must be text so in your migrations you can specify:
add_column :user_details, :additional_info, :text

Then in your model you have to specify that this column will contain a hash and you do that with the serialize command:
class UserDetail < ActiveRecord::Base
  serialize :additional_info

After that you can save hash information.
@ud = UserDetail.new
@ud.additional_info = {:salary => 1000000}
@ud.save

A: As of MySQL 5.7.8 there is a support for a native JSON data type, so saving a hash is much more direct and can be searchable and more:
https://dev.mysql.com/doc/refman/5.7/en/json.html

A: Another alternative would be to use JSON fields on the model. The migration would have something like:
create_table :events do |t|
  t.json 'payload'
end


text:
Q: Microsoft graph API Java HTTP client does not allow updating by patch Is there an alternative way to updating a listitem without using the PATCH method or the base SDKs (since i'm doing through a HTTP client).
public Boolean updateItem(Item i) {
        if(i.getId() != null) {
            String URL = "https://graph.microsoft.com/v1.0/sites/"+siteId+"/lists/"+listId+"/items/"+i.getId()+"";

            try {
                URL url = new URL(URL);
                HttpURLConnection http = (HttpURLConnection) url.openConnection();
                http.setRequestMethod("PATCH");
                http.addRequestProperty("Accept", "application/json;odata.metadata=none");
                http.addRequestProperty("Content-Type", "application/json");
                http.setRequestProperty("Authorization", "Bearer "+getAuth());
                http.setDoOutput(true);
                http.setDoInput(true);

                send(http.getOutputStream(), i.toJson());

                http.connect();
                if(http.getResponseCode() == 200) {
                    String content = read(http.getInputStream());
                    System.out.println(content);
                    return true;

                }else {
                    String errorContent = read(http.getErrorStream());
                    System.out.println("UPDATE ITEM ERROR:"+errorContent);
                }
            }catch(IOException e) {
                System.out.println("UPDATE ITEM (IOException):"+e.getMessage());
            }
        }
        return false;
    }

The getAuth() returns a valid access token.
I have attempted this:
http.setRequestProperty("X-HTTP-Method-Override", "PATCH");

However Microsoft seems to only recognise it as POST

A: Solved. I used Apaches HTTP Client to do the patch method (org.apache.http.client.methods.*).


text:
Q: Getting one Roslyn syntax receiver per class I have a simple source generator defined as
[Generator]
public class NestedObjectGenerator : ISourceGenerator
{
  public void Initialize(GeneratorInitializationContext context)
  {
    context.RegisterForSyntaxNotifications(() => new MySyntaxReceiver());
  }
  public void Execute(GeneratorExecutionContext context)
  {
    var recv = (MySyntaxReceiver)context.SyntaxReceiver;
    ClassDeclarationSyntax cds = recv?.Class;
    if (cds is null) return;

    // use cds here
  }

  private class MySyntaxReceiver : ISyntaxReceiver
  {
    public ClassDeclarationSyntax Class { get; private set; }

    public void OnVisitSyntaxNode(SyntaxNode node)
    {
      if (node is ClassDeclarationSyntax cds &&
        cds.Modifiers.Any(SyntaxKind.PartialKeyword))
      Class = cds;
    }
  }
}

I am running this generator on a file that has several partial classes in it. However, it seems that Execute() gets called only once, and the Class that is included is the class that has the Main() method, even though I have other classes in the file.
So, my question: how can I get Execute() to run once per affected syntax node, i.e., to get it to run once per partial class?

A: You can change your reciever like this:
private class MySyntaxReceiver : ISyntaxReceiver
{
  public List<ClassDeclarationSyntax> ClassCandidates { get; } = new();

  public void OnVisitSyntaxNode(SyntaxNode node)
  {
    if (node is ClassDeclarationSyntax cds && cds.Modifiers.Any(SyntaxKind.PartialKeyword))
      ClassCandidates.Add(cds);
  }
}

And then in the Execute method of the source generator you can loop on all the nodes you collected.
I got this approach from a really informative video
https://www.youtube.com/watch?v=P9Pv5IdinMU
Here is the github with the demos in the presentation, i learned this from these examples:
https://github.com/JasonBock/SourceGeneratorDemos


text:
Q: Host joined to AD on separate vlan cannot access website with public ip on another vlan I have 5 vlans.
vlan 1 hosts the website with public ip 67.x.x.x. Hosts are in domain1
vlan 2-4 are able to access the website using via domain name which resolves to external ip 67.x.x.x. Hosts are all in domain2, domain3,domain4.
vlan 5 has 4 hosts, 1 Domain Controller, 1 Remote Desktop Gateway, the rest is miscellaneous all joined to an AD domain domain5.
The strange part, vlan 5 hosts are unable to access the website hosted on vlan1 EXCEPT the RDG host. The RDG host is able to access it.

I've checked firewall rules, disable firewall on both the vlan1 website host and the client in vlan5.
I've attempted to move vlan5 client into vlan1 and changed the gateway and dns. Still no luck.
I've edited the hosts file attempting to manually assign the local IP to vlan1 webhost to resolve to domain name. That only worked after clearing dns cache 5 times.
So, why is the RDG gateway able to access the site normally without edits to the hosts file, and every other one inside the same domain as RDG is not (without editing hosts file)? Any clues?

A: I think one would need to know a lot more about the configuration of this setup before definitive answers could be offered.  Are all of the hosts on the same switch?  Does the RDG have an external IP?  Is the RDG configured to use a different DNS server than the other VLAN 5 servers?  Does the website server have an internal IP address that is translated (NAT) by a firewall or other appliance?  If you ping the website URL from a VLAN 5 server, do you get a different IP address than you do from the RDG?
Most likely the network path between the RDG and the website is different from the other servers on VLAN 5.  Trace through the network path from two distinct servers and see if you can see a relevant difference.


text:
Q: kitchen converge on chef_roles using chef_zero doesn't expand run_list Issue:
I was trying to use chef_zero to test my cookbook roles specified in ruby DSL format, but when I tried to do kitchen converge. It looks like it's not able to expand the role specified in
kitchen.yml.
How to Resolve: Is it not possible to use chef-zero to test roles in a cookbook using test-kitchen or am I not calling the role correctly in my kitchen.yml. how do I test roles using chef_zero locally.
**chef-environment**:

Chef Development Kit Version: 0.12.0
chef-client version: 12.8.1
berks version: 4.3.0
kitchen version: 1.6.0

**kitchen.yml**:

suites:
  - name: default
    run_list:
      - role[test_role]

 **Error**

 [2016-05-25T12:58:37-04:00] ERROR: Role test_role (included by 'top level') is in the runlist but does not exist. Skipping expand.

   ================================================================================
   Error expanding the run_list:
   ================================================================================

   Missing Role(s) in Run List:
   ----------------------------
   * test_role included by 'top level'

   Original Run List
   -----------------
   * role[test_role]

chef-stacktrace.out:
Chef::Exceptions::MissingRole: The expanded run list includes nonexistent roles: test_role

A: ChefFS (and thus zero, local mode, solo, etc) didn't support Ruby-formatted files until 12.10 (the most recent release). You'll need to use the JSON format for older Chef.


text:
Q: How to retrieve value from checkbox defined in django template I have created a menu with three options(home,change password and logout). In home I am displaying all the books stored in the database. Now I want to filter the contents based on categories of the books using checkbox. By default all the books are shown upon filtering the category only the books of that category should be shown.But for me it is showing all the books even after clicking on all the checkbox (checkbox contains the categories).I think there is some problem in my template file.
urls.py,
 url(r'^welcome_user/$',views.welcome_user, name='welcome_user'),

Models.py,
class Add_cat(models.Model):
    category = models.CharField("Name",max_length=25,unique=True)

    def __unicode__(self):
        return u'{0}'.format(self.category)

class Add_prod(models.Model):
    book = models.CharField("Book Name",max_length=40)
    author = models.CharField("Author",max_length=30)
    price = models.PositiveIntegerField("Price")
    image = models.ImageField(upload_to='images',null=True)
    cat = models.ForeignKey(Add_cat,on_delete=models.CASCADE)

Template file,
{% block content %}
{% load staticfiles %}

<link rel="stylesheet" href="{% static 'style.css' %}">

        <form action="{% url 'welcome_user' %}">

Categories

            {% for i in products %}
                <input type="checkbox" name="cat_name" value="{{i.cat}}">{{i.cat}}

            {% endfor %}
        <button type="submit">Submit</button>
        </form>

        {% for i in products %}

Rs.{{i.price}}

        {% endfor %}

{% endblock %}

Views.py,
@login_required
def welcome_user(request):
    if 'cat_name' in request.GET:
       filter_category = request.GET.getlist('cat_name')
       my_products = Add_prod.objects.filter(cat__in=filter_category)
       context = { "products":my_products}
    else:
       my_products = Add_prod.objects.all()
       context = { "products":my_products}
return render(request,"welcome-user.html",context)

A: To check whether checbox value is in sent form you should go with following condition
    if 'cat_name' in request.GET:
        #checkbox has been checked
    else:
        #it is not checked

Remember that in operator return boolean so you can also do
    filter_category = 'cat_name' in request.GET

To get value you just need to get values of 'cat_name' key like:
    value = request.GET['cat_name']

after checking whether it is in GET parameters or not

A: I think all you need to do is add __in to your filter:
@login_required
def welcome_user(request):
    filter_category = request.GET.getlist('cat_name')
    categories = Add_cat.objects.all()
    if filter_category: # I couldn't decipher the structure of an `Add_cat`, so I left off the `in` check since it would not work for lists
        print filter_category
        my_products = Add_prod.objects.filter(cat__in=filter_category) # the template implies that this field is `cat` and not `category`
        context = { "products":my_products}
    else:
        my_products = Add_prod.objects.all()
        context = { "products":my_products}
    return render(request,"welcome-user.html",context)

A: Checkboxes work a little bit different from other form inputs, so if you examine a post sent from a form that includes a checkbox,

if the checkbox is checked, your queryset will look like:
the value will be 'on'
So, you have to check
 if request.POST.get('cb1')=='on':
        "item is selected"
    else:
        "item is not selected"

A: Try this below code
Add_prod.objects.filter(cat__in=filter_category)
@login_required
def welcome_user(request):
    filter_category = request.GET.getlist('cat_name')

    if filter_category:

        my_products = Add_prod.objects.filter(cat__in=filter_category)
        context = { "products":my_products}
    else:
        my_products = Add_prod.objects.all()
        context = { "products":my_products}
    return render(request,"welcome-user.html",context)

Template file
Remove quotes(') from {% url 'welcome_user' %}
<form method='get' action="{% url welcome_user %}">

UPDATE
Add quotes between views.welcome_user
urls.py
url(r'^welcome_user/$','views.welcome_user', name='welcome_user'),


text:
Q: Using Javascript Mongodb driver for Aggregation I am trying to extract aggregate data from Mongodb for each filename each version where platform is win
My data has following format
[
{ "_id" : { "platform" : "mac", "filename" : "f1.json", "version" : "1.4.14" }, "avgSecs" : 15 },
{ "_id" : { "platform" : "win", "filename" : "f2.json", "version" : "3000.0.0_developer" }, "avgSecs" : 1217 },
{ "_id" : { "platform" : "win", "filename" : "f3.json", "version" : "1.4.14" }, "avgSecs" : 1711 },
{ "_id" : { "platform" : "win", "filename" : "f3.json", "version" : "3000.0.0_developer" }, "avgSecs" : 1191 }
]

My code is as follows
  [ {$sort:{filename:1}},{$match:{platform:"win"}},{ $group:{ _id: {filename:"$filename", version:"$version"}, avgSecs: {$avg:"$int_secs"} } }]

which is send to mongodb using JS apis as follows
        collection.aggregate(aggQuery).toArray(function(err,docs){
            assert.equal(null,err)
            resolve(docs);
        })

but I dont get parsed and aggregate data but complete data as is from the db.
I have checked the same aggregate query works fine with mongodb shell. I am not sure what is the problem with JS api. Am I using it the right way

A: Ok found it.
AggQuery was sent in as string while it was expecting an Array Object.
Made the object Array and now results are as expected.


text:
Q: Measuring execution time with clock in sec in C not working I'm trying to measure execution time in C using clock() under linux using the following:
#include <time.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char const* argv[])
{
  clock_t begin, end;
  begin = clock();
  sleep(2);
  end = clock();
  double spent = ((double)(end-begin)) / CLOCKS_PER_SEC;
  printf("%ld %ld, spent: %f\n", begin, end, spent);
  return 0;
}

The output is:
1254 1296, spent: 0.000042

The documentation says to divide the clock time by CLOCKS_PER_SEC to get the execution time in sec, but this seems pretty incorrect for a 2sec sleep.
What's the problem?

A: Sleeping takes almost no execution time. The program just has to schedule its wakeup and then put itself to sleep. While it's asleep, it is not executing. When it's woken up, it doesn't have to do anything at all. That all takes a very tiny fraction of a second.
It doesn't take more execution time to sleep longer. So the fact that there's a 2 second period when the program is not executing has no effect.

A: clock measures CPU time (in Linux at least). A sleeping process consumes no CPU time.
If you want to measure a time interval as if with a stopwatch, regardless of what your process is doing, use clock_gettime with CLOCK_MONOTONIC.

A: man clock() has the answer:
The clock() function returns an approximation of processor time used by the program.
Which clearly tells that clock() returns the processor time used by the program, not what you were expecting the total run time of the program which is typically done using gettimeofday.


text:
Q: Unable to send parameters in @html.actionlink to partialview I have one actionlink inside the foreach loop. Depending on the model items I am generating link buttons with values dynamically.
This is how it looks
@foreach (var group in Model.records)
{

        @Html.ActionLink(@group.clientId.ToString(), "detailsbyClientId", "DocumentVerification", new { id = @group.clientId.ToString()},null)
        @group.clientName
        @group.Count

}

On clicking link button i am calling partial view as below.
[HttpGet]
public PartialViewResult detailsbyClientId(int? clientId)
{
    return PartialView();
}

I am receiving a null value for clientId but @group.clientId.ToString() contains a valid value.

A: Try this:
The point is the name of the variable you are passing and the name of the variable that is expecting the value in the controller should be the same.
 @foreach (var group in Model.records)
 {

    @Html.ActionLink(@group.clientId.ToString(), "detailsbyClientId", "DocumentVerification", new { clientId = group.clientId},null)
    @group.clientName
    @group.Count

 }

 [HttpGet]
 public PartialViewResult detailsbyClientId(int? clientId)
 {
    return PartialView();
 }

A: The parameter in your method is named clientId but your generating a query string value named id. Change one or the other to match
public PartialViewResult detailsbyClientId(int? ID)
{
    ....
}

and in the view
@Html.ActionLink(@group.clientId.ToString(), "detailsbyClientId", "DocumentVerification", new { id = group.clientId },null)

Note you do not need the @ nor .ToString() in the 4th parameter - just new { id = group.clientId }


text:
Q: Show that $\left|\int^{b}_{a}cos(f(x))dx\right| \leq \frac{2}{m}$ Let $f:[a,b] \to \mathbb{R}$ such that $f$ has a derivative which is monotonically decreasing and satisfies $f'(x) \geq m > 0, \forall x \in [a,b].$ Then,$\left|\int^{b}_{a}\cos(f(x))\right| \leq \frac{2}{m}$
My attempt: By Bonnett's form of Mean value theorem, $\exists c \in [a,b]$ such that $$\left|\int^{b}_{a}\cos(f(x))dx\right|\leq \int^{b}_{a}\frac{|\cos(f(x))|}{f'(x)}f'(x)dx = f'(a)\int^{c}_{a}\frac{|\cos(f(x))|}{f'(x)}dx \leq \frac{f'(a)}{m}(b-a).$$
Could anyone advise me on how to get the required inequality? Thank you.

A: $$
\left| \int_a^b \cos f(x)\, dx \right| \leq \int_a^b \frac{|\cos f(x)| f'(x)}{f'(x)}dx \leq \frac{1}{m} \int_{f(a)}^{f(b)} |\cos u| du
$$
and now it should be easy to conclude. Roughly speaking, the last integral is something like $\sin f(b)-\sin f(a)$ and you can estimate this difference from above by $2$.


text:
Q: Disallow user access to microphone Blacklisting a kernel module would disable the microphone for all users. I have set up a restricted user, who should not be able to use the microphone. The restricted user should, however be able to have sound output.
Is there a way of reliably disabling the microphone for a restricted user?

A: After experimenting a lot this seems to be the solution:
sudo setfacl -m u:user:- /dev/snd/pcmC0D0c

On my computer, /dev/snd/pcmC0D0c is the microphone. Blocking write access for a specific user seems to forbid capturing.
With the above command, I reduce the rights for the user "user" to --- (check with getfacl /dev/snd/pcmC0D0c), which does not allow for capturing sound.
Hint: for finding microphones in /dev/snd/ the c for capturing at the end of the name may be an indicator.
NOTE: As all changes made to /dev/ will be lost at reboot, as these files are placed in RAM, you would have to additionally add the above command (without sudo as /etc/rc.local is executed with root rights at boot) to /etc/rc.local before the "exit 0" line.


text:
Q: Modulus of exponential function with real and complex arguments Can anyone please explain why
$$|e^{\frac12 \sin(2x) }|\le e^{1/2}$$
for all real $x$,
 while $$|e^{-i\sin(x)^{2}}|=1$$
for all real $x$?

A: If $x \in \mathbb R$, then $-1 \le \sin 2x \le 1$.  Since exponentiation by a real number is a monotonically increasing function, $$|e^{(\sin 2x)/2}|$$ attains its maximum when $\sin 2x$ is maximized; i.e., when $\sin 2x = 1$.  (The absolute value is irrelevant because $e^x > 0$ for all $x \in \mathbb R$.  It follows that $$e^{(\sin 2x)/2} \le e^{1/2}.$$
For the second identity, we note that $$|e^{i\theta}| = |\cos \theta + i \sin \theta| = \sqrt{\cos^2 \theta + \sin^2 \theta} = 1$$ for any $\theta \in \mathbb R$.  Therefore $$|e^{-i\sin x^2}| = 1$$ since $-\sin x^2$ or $-\sin^2 x$ (whichever you prefer) is a real number.


text:
Q: How to have several handlers using Logbook? I'm using logbook to log message in a Python app but
import logbook

from logbook import Logger, StreamHandler, NullHandler

log = Logger('LogbookExample')

import sys
StreamHandler(sys.stdout).push_application()

NullHandler().push_application()

def main():
    log.info('Hello, World!')

if __name__ == "__main__":
    main()

doesn't work as I was expecting...
nothing appears. Like if NullHandler was replacing StreamHandler
So I wonder how to have several handlers connected to app ?

A: The problem here is choosing NullHandler. It acts as a "black hole", swallowing all logs and not propagating them up the stack.
Stacking non-NullHandlers is easy:
StreamHandler(sys.stdout).push_application()
StreamHandler(sys.stderr, bubble=True).push_application()

The bubble keyword means the handler should continue propagation up the stack after handling the record.