text:
Q: if image is → on-error fetch image on the base of gender value I'm trying to fetch an image, and if on-error, get the default image based on the gender value.
pls advice How can I fetch an on-error default image on base of gender value ?
echo"

<img  src=".'imagefolder/'.$_row['img']."

<?php if (".$_row['gender']." != 'Male'):?>

onerror = this.src='female-default.jpg'

<?php else: ?>

onerror = this.src='male-default.jpg'

<?php endif; ?>

>";

A: Your quotes mean that none of the PHP inside is being evaluated, and you can't use if/else blocks inside an echo anyway. You can break it apart
echo "";

or you can use a ternary
echo "";


text:
Q: Can't append a list to an existing file I have an existing .txt file that I would like to use to store my data, but when using this code I get an error at line 39 at switch case 1.
using System;
using System.Collections.Generic;
using System.IO;

class Program
{

    public static List<Pw> Site = new List<Pw>();
    static void Main(string[] args)
    {

        string file = @"C: \Users\james\Documents\DataFolder\Vault.txt";

        string command = "";
        while (command != "exit")
        {
            Console.Clear();
            Console.WriteLine("Please enter a command: ");
            command = Console.ReadLine().ToLower();
            switch (command)
            {
                case "1":
                    AddPw();
                    File.AppendAllLines(file, Pw.Site);

                    break;

                case "2":

                    if (File.Exists(file))
                    {
                        // Read all the content in one string
                        // and display the string
                        string str = File.ReadAllText(file);
                        Console.WriteLine(str);
                    }
                    break;
            }
        }

    }
    private static void AddPw()
    {
        Pw pw = new Pw();

        Console.Write("Enter the Username/Email: ");
        pw.Username = Console.ReadLine();

        Console.Write("Enter Full Name: ");
        pw.FullName = Console.ReadLine();

        Console.Write("Enter Phone Number: ");
        pw.PhoneNumber = Console.ReadLine();

        Console.Write("Enter Your Password: ");
        string password = Console.ReadLine();
        pw.Password = password;

        Site.Add(pw);
    }

    private static void PrintPw(Pw pw)
    {
        Console.WriteLine("Username/Email: " + pw.Username);
        Console.WriteLine("Full Name: " + pw.FullName);
        Console.WriteLine("Phone Number: " + pw.PhoneNumber);
        Console.WriteLine("Password: " + pw.Password[0]);
        Console.WriteLine("-------------------------------------------");
    }

    private static void ListPw()
    {
        if (Site.Count == 0)
        {
            Console.WriteLine("Your address book is empty. Press any key to continue.");
            Console.ReadKey();
            return;
        }
        Console.WriteLine("Here are the current people in your address book:\n");
        foreach (var pw in Site)
        {
            PrintPw(pw);
        }
        Console.WriteLine("\nPress any key to continue.");
        Console.ReadKey();
    }

}

public class Pw
{
    public string Username { get; set; }
    public string FullName { get; set; }
    public string PhoneNumber { get; set; }
    public string Password { get; set; }
}

A: I have updated your existing function.
using this function you can add and append data in existing file.

private static void AddPw(string filePath)
{
    try
    {
        Pw pw = new Pw();
        if (!File.Exists(filePath))
        {
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath))
            {
                Console.Write("Enter the Username/Email: ");
                pw.Username = Console.ReadLine();
                sw.WriteLine(pw.Username);

                Console.Write("Enter Full Name: ");
                pw.FullName = Console.ReadLine();
                sw.WriteLine(pw.FullName);

                Console.Write("Enter Phone Number: ");
                pw.PhoneNumber = Console.ReadLine();
                sw.WriteLine(pw.PhoneNumber);

                Console.Write("Enter Your Password: ");
                pw.Password = Console.ReadLine();
                sw.WriteLine(pw.Password);
            }
        }
        else
        {

            using (StreamWriter sw = File.AppendText(filePath))
            {
                Console.Write("Enter the Username/Email: ");
                pw.Username = Console.ReadLine();
                sw.WriteLine(pw.Username);

                Console.Write("Enter Full Name: ");
                pw.FullName = Console.ReadLine();
                sw.WriteLine(pw.FullName);

                Console.Write("Enter Phone Number: ");
                pw.PhoneNumber = Console.ReadLine();
                sw.WriteLine(pw.PhoneNumber);

                Console.Write("Enter Your Password: ");
                pw.Password = Console.ReadLine();
                sw.WriteLine(pw.Password);
            }
        }
    }
    catch (Exception ex)
    {
    }
}

A: File.AppendAllLines(file, Pw.Site);

In this line, you need to pass an IEnumerable for AppendAllLines to work.  You can easily convert Site (which is List<Pw>) to an IEnumerable<string> using the ConvertAll method.  Here's one way of achieving this:
Replace that line with this:
File.AppendAllLines(file, Site.ConvertAll<string>(
  (p) => string.Format("{0} | {1} | {2} | {3}\n",
    p.Username,
    p.FullName,
    p.PhoneNumber,
    p.Password
  ))
);

This "lambda" basically takes your Pw object and converts it into a string inline.

redpajama_set_name: RedPajamaStackExchange


text:
Q: why is the button image is being compressed? Why is the image being messed up? I have a set heigh of 130 and set width of 130, and when I use the preview mode it looks fine, but for some reason the image is being compressed into a small space, and the size too. I have clipped to subviews, but it is still messed up. Why? How do I fix this?
Image of how the constraints look like
Image of how the button image looks like on the phone
userpic.contentMode = .ScaleAspectFill

A: As i understand your issue, just trying to fix it...

ForAllObject.contentMode = Scale To Fill

I think, It'll helps...


text:
Q: How to maintain application state in windows phone 7? I want to maintain the state of an application .please tell me how to save the state of the application in windows phone 7?
Thanks,

A: read about life cycle of app, tombstone,dormant,active,closed.
You might need to use some state helpers to maintain controls state. Check link below
http://lnluis.wordpress.com/2011/09/26/managing-application-state-in-windows-phone-7/
This one is what i prefer but it depends on your app design.
http://tombstonehelper.codeplex.com/
Read this:
http://www.developer.nokia.com/Community/Wiki/Tombstoning_helper_for_Windows_Phone_7


text:
Q: How to import Project in Cube IDE 32 properly enter image description here  I need Help, I work on one project and yesterday i have accident and i damage my PC,I did Project backup and Now i try to import Projrct on my lap top, and i folow instructions but i folow some unexpected errors also, is saying that hal drivers is missing, i give propher path address to all folders but still not fixed, old project was worked fine on Win10 english FW1,5,1  i try to import in win 11 German, i download and add FW 1,5,1 but error still exist.
i try older backup version and still same messige. there is no missing files. just some incompatabiliity.


text:
Q: The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction in SQL Server I have an Error log table, We insert error details into this table if there is any exception in stored procedure or trigger.
I can see an entry for an update trigger in this table. But I am not able to understand the root cause of the error.
Is this trigger causing the issue? or some other stored procedure is causing this issue?
Error Message: The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction.
Procedure Name: In the procedure name I get the trigger name
Error Number: 3930
Query to insert into an error log table.
END TRY
BEGIN CATCH
    INSERT INTO Mas_ErrorLog (ProcedureName, ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, ErrorLine)
    SELECT Error_Procedure(), Error_Number(), Error_Message(), Error_Severity(), Error_State(), Error_Line()
END CATCH

Note: Just to highlight one thing, I can't see an entry for this trigger in other environments databases like Dev, Beta or UAT. It's occurring only in the Production database so I cannot directly make changes and test.
And it's an old log, I cannot reproduce this case, I need to investigate the root cause.


text:
Q: How to reference a view from fragment Android Why won't this let me reference the EditText? i tried passing activity and it didn't work.
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

public class HomeFragment extends Fragment {

    public HomeFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
        EditText savedata = (EditText).getActivity(),findViewById(R.id.savebtn);
        return rootView;
    }
}

A: Change this
 EditText savedata = (EditText).getActivity(),findViewById(R.id.savebtn);

to
  EditText savedata = (EditText)rootView.findViewById(R.id.savebtn);

Assuming the edittext belongs to fragment_home.xml.
You can also initialize in onActivityCreated using getView().findViewById(id)
Note:
The fragment can access the Activity instance with getActivity() and easily perform tasks such as find a view in the activity layout:
View listView = getActivity().findViewById(R.id.list);

A: You can't pass reference from Activity.
Change this:
  EditText savedata = (EditText)rootView .findViewById(R.id.savebtn);


text:
Q: Why is there a huge performance difference between 32 and 64 bit JDK? So I've been doing Project Euler, and I found two ways to solve Problem 57. However, there seems to be a huge difference in performance between using a 32bit JDK and a 64bit JDK.
public static int fractionSolution (int l){
int count = 0;
for (int i = 1; i < l; i++) {
    BigFraction f = iterateFraction(i).subtract(new BigFraction(1,1));
    if(f.getDenominator().toString().length() < f.getNumerator().toString().length()){
        count++;
    }
}
return count;
}

public static BigFraction iterateFraction(int n){
    if(n==1){
        return new BigFraction(2.5);
    }
    else{
        BigFraction base = new BigFraction(1,1);
        BigFraction two = new BigFraction(2,1);
        return two.add(base.divide(iterateFraction(n-1)));
    }
}

public static int patternSolution (int l){
    BigInteger n = new BigInteger("3");
    BigInteger d = new BigInteger("2");
    int count = 0;
    for (int i = 1; i < l; i++) {
        n = n.add(d.multiply(new BigInteger("2")));
        d = n.subtract(d);
        if(n.toString().length() > d.toString().length()){
            count++;
        }
    }
    return count;
}

If I run the fractionSolution on 64 bit JDK, it will take 30 seconds, but on 32bit, it will take 90 seconds.
If I run patternSolution on 64 bit JDK, it will take about 80 ms, but on 32 bit, it will take about 40 ms.
Why is there such a huge difference between the JDKs? Which one should I use?
I'm using Java SE 7, JDK 1.7
Here are screen caps of my program so you don't have to run it.
http://imgur.com/elzQMi3,BxEZ1RK,lDo6YBW,rRiaelE#0
You can tell which JDK it is from the file paths.


text:
Q: Как слинковаться на библиотеку в проекте Пришла необходимость частично разделить сборку программы и разбить на подмодули, что бы во время выполнения при необходимости выгружать их из памяти.
Но вот ведь незадача, добавил проект, перенес все необходимое в пустой проект, поставил компилировать как динамическую библиотеку, добавил ссылку в основное приложение, и... Ничего. Хочет .lib от библиотеки.
Знаю что можно с помощью dumpbin и программы lib это сделать, но должен же быть способ компилировать библиотеку, и автоматически создать библиотеку для линковки?

A: Почему у вас не создается .lib сложно сказать, слишком мало информации.
Библиотеку dll можно подключить двумя способами, подробнее:
https://ru.stackoverflow.com/a/715687/188399
Чтобы подгружать/выгружать во время выполнения вам явно подходит позднее связывание, для него .lib и не нужен.


text:
Q: Bash script stops without error when the extraction of image EXIFs with exiftool encounters an empty file I have this script which processes images in subfolders on Ubuntu 22.04 with exiftool 12.57:
#!/bin/bash

set -e

DIR=/path/to/photos

for f in $(find "${DIR}" -type f -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png");
do
  echo "processing ${f}..."
  exiftool "${f}" >> output.txt
  printf -- '#%.0s' {1..80} >> output.txt
  printf '\n' >> output.txt
done

But it simply stops without throwing any warning or error to stdout/stderr when it reaches an empty file:
$ tail output.txt
################################################################################
ExifTool Version Number         : 12.57
File Name                       : 20222601_DSC00057.JPG
Directory                       : /path/to/photos/experiment 11
File Size                       : 0 bytes
File Modification Date/Time     : 2020:10:26 15:03:22+01:00
File Access Date/Time           : 2023:03:02 16:47:51+01:00
File Inode Change Date/Time     : 2023:03:02 15:07:08+01:00
File Permissions                : -rw-rw-r--
Error                           : File is empty

The file is indeed a 0 byte file:
$ ls -larth /path/to/photos/experiment\ 11/20222601_DSC00057.JPG
-rw-rw-r-- 1 1000 1000 0 Feb 12  2021 '/path/to/photos/experiment 11/20222601_DSC00057.JPG'

How could I get the script to continue processing other files, because there are still plenty of folders with photos to process?
Version info
$ bash --version
GNU bash, version 5.1.16(1)-release (x86_64-pc-linux-gnu)

$ cat /etc/os-release
PRETTY_NAME="Ubuntu 22.04.2 LTS"
NAME="Ubuntu"
VERSION_ID="22.04"
VERSION="22.04.2 LTS (Jammy Jellyfish)"
VERSION_CODENAME=jammy
ID=ubuntu
ID_LIKE=debian
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
UBUNTU_CODENAME=jammy

$ uname -mor
5.19.0-32-generic x86_64 GNU/Linux

$ exiftool -ver
12.57

A: For the posterity and because I found it very interesting as well, I rebuild steeldriver's answer as a Community wiki:

set -e causes the shell (script) to exit when exiftool returns a
non-zero exit status (which it apparently does when passed an empty
file).
If you need to run the script with set -e for other reasons, you
could either:

*

*set +e before the exiftool command and then reset set -e after

or (more idiomatic, I think)
change:
exiftool "${f}" >> output.txt

to:
exiftool "${f}" >> output.txt || true

so that the compound command always exits successfully regardless of
the exit status of the simple command exiftool
BTW your loop over the find command's output is fragile - see Why
is looping over find's output bad practice?

A: Check for an empty file and not ask exiftool to process it:
if [[ -s "${f}" ]] ; then
   exiftool "${f}" >>output.txt
else
    echo "Empty" >>output.txt
fi

Read man bash.


text:
Q: Is there a formula for (0.5)²+(1)²+(1.5)²+(2)²+...+(25)² (1/4)(1³) + (1/9)(1³+2³) + (16)(1³+2³+3³) + ... + (1/2704)(1³+2³+3³+...+51³) = ?
Initially, I factored it as 1³ (1/2² + 1/3² + ... + 1/52²) + 2³ (1/3² + ... + 1/52²) + 3³ (1/4² +...+ 1/52²) + ... + 51³ (1/52²), but got stuck to split them as separate series.
Alternatively, I observed this pattern
1³/4 + (1³/9 + 2³/9) + (1+8+27)/16 + 100/25 + ... + (1+2+3+...+51)/52
= (1/2)² + (3/3)² + (6/4)² + (10/5)² + ... + ((1+...+51)/52)²
= (1/2)² + (2/2)² + (3/2)² + (4/2)² + (5/2)² ... + (51/2)²
= (1/2)² (1+2²+3²+...+51²)
= (1/2)² (1/6)(51)(2(51)+1)(51+1)
= (1/2)² (1/6)(51)(103)(52)
= (1/2)² (17)(103)(26)
= 45526/4
= 11381.25
Does this seem correct?

A: By Faulhaber,$$1^3+2^3+3^3+\cdots n^3=\frac{n^2(n+1)^2}4$$
and your sum can be written as
$$\frac14+\frac44+\frac94+\cdots\frac {n^2}4.$$
By Faulhaber again, this is
$$\frac{n(n+1)(2n+1)}{24}.$$

A: The sum can be expressed as:
$$
\frac1{2^2}\cdot 1^3+\frac1{3^2}\cdot (1^3+2^3)+\frac1{4^2}\cdot (1^3+2^3+3^3)+\cdots +\frac1{52^2}\cdot (1^3+2^3+\cdots +51^3)=$$
$$\sum_{i=2}^{52} \frac1{i^2} \sum_{j=1}^{i-1} j^3\stackrel{(1)}{=}\\
\sum_{i=2}^{52} \frac1{i^2}\cdot (\frac{(i-1)i}{2})^2=\sum_{i=2}^{52} \frac{(i-1)^2}4=\frac14\sum_{i=1}^{51} i^2\stackrel{(2)}{=}\cdots$$
where:
$$\sum_{i=1}^{n} i^3=(\frac{n(n+1)}{2})^2   \quad  \quad  (1)$$
$$\sum_{i=1}^{n} i^2=\frac{n(n+1)(2n+1)}{6}   \quad  \quad  (2)$$
Can you finish?


text:
Q: How to debug DBIx::Class? I was recently working on a Perl project that required me to use DBIx::Class as the ORM to interact with a database. One of the things I found most annoying and just time consuming was just trying to debug and understand what was happening.
I was especially frustrated with and error I was getting Column 'XXXXXX' in where clause is ambiguous and I figured out what was causing this error. It was down to the fact I was requesting columns from 2 different tables which where joined on the XXXXXX attribute and in the WHERE clause the column wasn't being aliased. This lead to DBIx::Class not knowing which column to use.
The most frustrating thing was not knowing what DBIx::Class was doing, leading me to have many doubts about where the error was coming from.
How to efficiently debug this kind of DBIx::Class errors?

A: You enable debugging by setting the DBIC_TRACE environment variable to 1 or a filename.
That's documented at the very top of DBIx::Class::Manual::Troubleshooting

A: So I knew what the error was, but I didn't know exactly where it was being caused. If this was plain old SQL I would've simply added the aliases myself but I didn't know how to do that in DBIx::Class. Moreover, I had no clue what SQL query was actually being executed, which made things even worse.
That's when I found out about the as_query method (https://metacpan.org/pod/DBIx::Class::ResultSet#as_query) which, when logged, prints out the SQL query that DBIx::Class executes. LIFE CHANGER. Saved me from so much trouble and gave me exactly what I needed. Shortly after I was able to solve the issue.
Moral of the story: if you're having trouble seeing what DBIx::Class is doing, use this and save yourself from countless headaches.


text:
Q: How to create and write a file into a folder on the same directory? I've been creating and writing into a file in the directory I have all my project files, but now that i finished everything, I'm trying to tidy things up.
My executable is creating and writing into a file in the same directory that it's placed on. Now, I've created a folder in this same directory called 'models' and i need the previous mentioned file to be created in this folder. I have a Windows machine and i'm using C++.
What i have at the moment, in a simplified way is:
void createFile(string fich){
    ofstream file(fich);
}

I've tried things like
void createFile(string fich){
    string path = "../models/" + fich;
    ofstream file(path);
}

without any success. How could i solve this?


text:
Q: Starting .NET Core installer using Inno Setup fails with result code 2 I'm trying to build up an installer using Inno Setup. I need to setup a prerequisite installation for .NET Core framework. By far I'm able to detect .NET Core existence. But I'm having difficulty with executing the installation.
Here's the code I have by far:
[Files]
Source: "\\shared\path\dotnet-runtime-3.1.10-win-x64.exe"; DestDir: "{tmp}"; \
  Flags: deleteafterinstall; BeforeInstall: InstallFramework; \
  Check: FrameworkIsNotInstalled

[Code]
var
  CancelWithoutPrompt: boolean;
  InstallValue: Cardinal;

function InitializeSetup(): Boolean;
begin
  CancelWithoutPrompt := false;
  result := true;
end;

procedure CancelButtonClick(CurPageID: Integer; var Cancel, Confirm: Boolean);
begin
  if CurPageID=wpInstalling then
    Confirm := not CancelWithoutPrompt;
end;

function FrameworkIsNotInstalled: Boolean;
begin
  Result := not RegQueryDWordValue(HKEY_LOCAL_MACHINE,
    'SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x64\sharedfx\Microsoft.NETCore.App',
    '3.1.10', InstallValue) or (InstallValue <> 1)
end;

procedure InstallFramework;
var
  StatusText: string;
  ResultCode: Integer;
begin
  StatusText := WizardForm.StatusLabel.Caption;
  WizardForm.StatusLabel.Caption := 'Installing .net core framework...';
  WizardForm.ProgressGauge.Style := npbstMarquee;
  try
    if not Exec(ExpandConstant('{tmp}\dotnet-runtime-3.1.10-win-x64.exe'), '/q /norestart', '', SW_SHOW, ewWaitUntilTerminated, ResultCode) then
    begin
      // you can interact with the user that the installation failed
      MsgBox('.NET Core installation failed with code: ' + IntToStr(ResultCode) + '.',
        mbError, MB_OK);
      CancelWithoutPrompt := true;
      WizardForm.Close;
    end;
  finally
    WizardForm.StatusLabel.Caption := StatusText;
    WizardForm.ProgressGauge.Style := npbstNormal;
  end;
end;

I'm getting result code 2 response from the installation, anyone could enlighten me what's code 2 error about? Or is that any way I could extract further detail on the error information? I tried empty argument and tried to search for Code 2 error information on the internet but still no luck.
I had tried with Shellexec and both return the same result
The installation directly using the .net exe are working fine locally
Any help or information would be much appreciate =)

A: You are trying to run the dotnet-runtime-3.1.10-win-x64.exe before you actually "install" it to the {tmp}:
BeforeInstall: InstallFramework

You have to use the AfterInstall parameter:
AfterInstall: InstallFramework


text:
Q: How to get into an object that is in an array Let's say I have an array like this :
arrayOfObject = [{item: {this: is,  that: is}}, {item2: {this: is, that: is}}]

I'm trying to access item and item2 without having to use a 0/1 index. I'd like to be able to say arrayOfObjects[item] to get into the object. Is this possible?

A: You can use Array.find.

arrayOfObject = [{
  item: {
    this: 'is',
    that: 'is'
  }
}, {
  item2: {
    this: 'is',
    that: 'is'
  }
}]

console.log(arrayOfObject.find(ob => ob['item']));
console.log(arrayOfObject.find(ob => ob['item2']));

A:

var arrayOfObject = [{
    "item": {
        "this": "is",
        "that": "is"
    }
}, {
    "item2": {
        "this": "is",
        "that": "is"
    }
}];

var itemObject = {};
arrayOfObject.forEach(function(value) {
    var filterObject = Object.keys(value).filter(val => val.indexOf("item") != -1);
    if (filterObject.length > 0) {
        filterObject.forEach(key => {
            itemObject[key] = itemObject[key] || [];
            itemObject[key].push(value[filterObject[0]]);
        });
    }
});

console.log(itemObject.item); //item
console.log(itemObject.item2); //item

A: Yeah sure it is possible:
var result = arrayOfObject.map(a => a.item);

or
var result = arrayOfObject.map(a => a.item2);

A: You can not do exactly this but something similar where you would "convert" your array to an object and then use the keys to access the values:

arrayOfObject = [{ item: { this: "a", that: "b" } }, { item2: { this: "c", that: "d" } }]

const arrayToObject = arrayOfObject.reduce((r,c) => Object.assign(r,c), {})

console.log(arrayToObject['item'])
console.log(arrayToObject['item2'])

In the snippet above we convert the arrayOfObject to arrayToObject and then simply access the values via the keys.
Otherwise what you are trying to do is not possible since you can only access values from an array by index or via some kind of a function which would traverse it and get you the entry, like find etc.


text:
Q: Dynamic summarise throught dynamic multiplication for an external vector I have a tibble such:
X = tibble(Name = rep(c("A","B","C"),5),
       Coeffs_1 = runif(15,0,1),
       Coeffs_2 = runif(15,0,1)) %>% arrange(Name)

Y = runif(10,0,100)

In this example the amount of "Reps" per "Names" is arbitrarily fixed at 5, and the amount of Coeffs_2 is arbitrarily fixed at 2, but in my code they could be any number and I don't know the exact number.
I also have a vector with n = reps*2 elements:
Y = runif(10,0,100)

In this specific case, it's 10 = 5*2.
My task is to summarise, per each Name, per each Coeff, this formula:
Result_x[1] = sum(Coeff_x[1]*Y[2] + Coeff_x[2]* Y[3] + ... + Coeff_x[Reps]*Y[Reps+1]) - Y[1]
Result_x[2] = sum(Coeff_x[1]*Y[3] + Coeff_x[2]* Y[4] + ... + Coeff_x[Reps]*Y[Reps+2]) - Y[2]
.
.
.
Result_x[Reps] = sum(Coeff_x[1]* Y[Reps+1] + Coeff_x[2]* Y[Reps+2] + ... + Coeff_x[Reps]*Y[Reps*2]) - Y[Reps]

So that in the end, the final summarise tibble should look like:

Name
Lag
Result_1
...
Result_x

A
+1
a number
numbers
a number

A
+2
a number
numbers
a number

A
...
a number
numbers
a number

A
Reps
a number
numbers
a number

B
+1
a number
numbers
a number

B
+2
a number
numbers
a number

...
...
a number
numbers
a number

...
Reps
a number
numbers
a number

The dynamic nature of the issue makes hard for me to define it well with a for cycle, and the presence of the external vector that must be re-indexed and properly summarised for each row in the original tibble makes me difficult to work with a pipeline.
I thought that defining a custom function could help but again, it messes with pipeline code.

A: Split the 'X' by 'Name', loop over the list (map), while creating shifted lead values of 'Y' in a list with n specified as a vector.  Loop over the list, summarise across the 'Coeff' columns for each of the nested list by taking the sum of product of the column value with the corresponding 'y' length corrected and subtract from the first value of 'y'
library(dplyr)
library(purrr)
library(data.table)
X %>%
   group_split(Name) %>%
   map_dfr(~ map_dfr(shift(Y, n = 1:nrow(.x), type = 'lead'),
        function(y) .x %>%
      summarise(Name = first(Name), across(starts_with('Coeff'),
         ~ sum(. * y[seq_along(.)], na.rm = TRUE) - first(y)))) ) %>%
   mutate(Lag = rowid(Name))

-output
# A tibble: 15 × 4
   Name  Coeffs_1 Coeffs_2   Lag
   <chr>    <dbl>    <dbl> <int>
 1 A        127.      54.4     1
 2 A        162.     134.      2
 3 A        127.      68.2     3
 4 A        109.      38.0     4
 5 A        108.      94.0     5
 6 B        175.     197.      1
 7 B        187.     240.      2
 8 B        151.     200.      3
 9 B        132.     159.      4
10 B        102.     152.      5
11 C         48.8    131.      1
12 C         89.1    128.      2
13 C         42.5     98.7     3
14 C         29.4     95.7     4
15 C         41.7     50.1     5


text:
Q: Visual Studio 2008 takes too long to build Windows Forms App solution I looked everywhere on the internet and this web site and found nothing that would help me so I resorted to make my own post.
I have a VS 2008 solution comprising of 6 projects: 1 Windows Forms App, 1 Windows Service, 4 DLLs. They are built in VB.
When I try to build one of the projects, or all of them, it says "Build started..." at the bottom of the IDE but the IDE appears to be frozen...can't click anything on it...and it stays like this for about 30 minutes. After that, it "unfreezes" and I can continue working with it.  I am trying to find out what is the cause for this behavior, how can I correct it? Anything that can help.
FYI - I am building/running from the IDE...not building from command prompt. Also, there are some third-party DLLs that are referenced but not registered. However, I don't think this is the problem because the compiler should only report the warning (like it is actually doing) and go on with the build... I don't see why it would freeze because of this.
Thanks in advance.

A: Do you have a Virus Scanner or some other disk monitoring service running?  I would try and disable all of those first to see if the problem persists.

A: Looks like you didn't got a perfect answer from last 3 years, My VS2010 Solution have 2 projects, One is my application and 2nd is my Installer Project, My solution was taking 10 minutes to build, I added output window to layout, and I checked my application project was building in couple of seconds, But it was installer project that was taking too much time, So I temporary removed that Installer project, and everything was working fine.


text:
Q: meteor collections field search I grab the currently selected mongo document using 'this' inside of a Template.alerts.events function. I then want to check to see if the current document (this) contains a specific field. To be precise, I want to see if it contains the userId which I store there myself previously.
doc {
    field1: 'a'

    myfield: {
        userId1: timestamp
        userId2: timestamp
        ...
    }

}

I basically want to see if the current user's userId is in the userId fields of myfield.
I have tried:
var x = this.userId
if(this.myfield.x) {
    //do something
}

and I'm wondering whether it is because I need to wrap userId in a string or something, but I can't get the condition to evaluate. I have also tried using object.hasOwnProperty which also didn't work. How can I do this in a non query way?

A: I'm assuming that you're trying to see if 'x' is a field in the object this.myField. If so, you have to do something like this: if (this.myfield[this.userId]). If you're trying to compare x and this.myfield, then you need to do if (this.userid == this.myfield)


text:
Q: Regular expression to fetch the value within all the " " a='fdkfjsdflksdj lfkjdflksdjf["fdkljfdfl"]fkjdfldjkf["fdfdf"]dfdfsdfsdfsdfddfdfkdfj["fdfds"]fdfasdfds'

I need to fetch the values which is inside "" that means out put should be
fdkljfdfl
fdfdf
fdfds

I have written the below coding
puts a[/\["(.*)"\]/m]

but it returns
["fdkljfdfl"]fkjdfldjkf["fdfdf"]dfdfsdfsdfsdfddfdfkdfj["fdfds"]

Can you help me to take that particular string within ""

A: puts a.scan(/\["(.*?)"\]/m)

              ^^

Make your regex non greedy.Or use negation based regex.
puts a.scan(/\["([^"]*)"\]/m)

A: Try:
a.scan(/"([^"]*)"/).flatten
#=> ["fdkljfdfl", "fdfdf", "fdfds"]

it will return the array of string


text:
Q: Is there a function to reverse an array, but only specific indexes? I need help to find a way to reverse a list. The only condition is to reverse specific index ranges. For example if my arr is [0,1,2,3,4,5,6,7], and you must reverse everything from index 2 to 5, then the end arr would be [0,1,5,4,3,2,6,7]? I code in Python3. Any help is appreciated!

A: To reverse indexes a to b, you can use the slice ([:]) operator and the function reversed():
l[a:b + 1] = reversed(l[a:b + 1])

A: a = list(range(8))
a[0:2] + list(reversed(a[2:5])) + a[5:]

This should reverse only the specific portion that you want and welcome to Stackoverflow!


text:
Q: Cocycle Group Clarification I'm just beginning to learn about group cohomology and I have a question about calculating the group of cocycles. My reasoning may be wrong at any of the following steps or perhaps all of them.
So, I'd like to calculate $Z^2(\mathbb{Z}/2, \mathbb{Z}/2)$ with respect to the trivial action. This group is given by the kernel of the map $$d_2: C^2\rightarrow C^3,$$ which takes $f(g_1,g_2)$ to $$d_2f(g_1,g_2,g_3)=g_2+g_3 -f(g_1+g2, g_3)+f(g_1,g_2+g_3) - f(g_1,g_2),$$ assuming I've done everything up until this point correctly. Thus, I am looking for the collection of functions from $(\mathbb{Z}/2)^2$ to $\mathbb{Z}/2$ that are taken to the identity of $C^3$. Since $C^3$ is an abelian group under pointwise addition, its identity element should be the function that sends every $g_i$ to $0\in \mathbb{Z}/2$.
But, suppose $g_1=g_2=g_3=0$. Then, for $f$ to be in the kernel of the coboundary homomorphism, we require $$d_2f(0,0,0)=f(0,0)=0.$$ Similarly, since we want $d_2f$ to be zero for all $g_i$, if $g_1=g_2=1$ and $g_3=0$, then we need $$d_2(1,1,0)=f(0,0)=1,$$ a contradiction. I know that I must be missing something fundamental, so if anyone could clarify the picture, I'd be very thankful.


text:
Q: Setting Filter for dynamoDB Table I have data in dynamoDB table and am trying to filter it based on data attributes. Below is an example of the JSON data. An example for filter query would be: payload.stat > 200.
However, attempts to use such query in DynamoDB navigation pane does not work and I get error: "An item consists of one or more attributes. Each attribute consists of a name, a data type, and a value. When you read or write an item, the only attributes that are required are those that make up the primary key"
How can I filter the data using attributes within payload?
{
  "payload": {
    "lock": "L1",
    "maxtmptr": 50,
    "serial": "SX001",
    "stat": 255,
    "timeover": 0.17,
    "tmptr": 30
  },
  "serial": "SX001",
  "timestamp": "1472784542467"
}

Screenshot of DynamoDB Table:

A: You can query or scan the result using FilterExpressions. When you query the dynamodb, partition key is must. When you scan the dynamodb, partition key is optional. But Scan is slower than Query.
Try with this
var params = {
        "TableName": tableName,
         "FilterExpression": "payload.lock = :val1 and timestamp = :val2",
        "ExpressionAttributeValues": {
            ":val1": "lockInput",
            ":val1": "timestamp"
        },
        "ReturnConsumedCapacity": "TOTAL"
    };

if you need more filter options, you can customize your FilterExpression.


text:
Q: Dynamically change li selection by click

$("#prev").click(function() {
  var elems = $('#smallTitle li a');
  var prev = elems.filter('.action');
  if ( prev.length === 0 ) prev = elems.last();

  elems.not( prev.addClass('action') ).removeClass('action');
});

$("#next").click(function() {
  var elems = $('#smallTitle li a');
  var next = elems.filter('.action').next();
  if ( next.length === 0 ) next = elems.first();

  elems.not( next.addClass('action') ).removeClass('action');
});
.SwitchURL-small-list{
    display:flex;
    list-style:none;
    font-size: 22px;
    font-weight:bold;
}

.SwitchURL-smaill-item{
    border-bottom: 0px solid#AE96DA;
    padding: 0 1%;
    margin-bottom: 1%;
    font-size: 20px;
}

.SwitchURL-small-link{
    color: #CFC1E9;
    margin-right: 15px;
    margin-left: 15px;
}

.SwitchURL-small-link:hover{
    color: #AE96DA;
}

.SwitchURL-small-link.action {
    border-bottom: 2px solid#AE96DA;
    color: #AE96DA;
    margin-right: 15px;
}

  <button id="prev" type="button"> > </button>

    AA

      BB

      CC

      DD

      EE

  <button id="next" type="button"> > </button>

I have a
 element, and inside the
 is use href to let user click to the corresponding file,
The
 is look like:

Now
 selection is "AA", then when I click the next(>) button,

 selection will be dynamic change to "BB", like this image:

or when I click the previous(<) button,

 selection will be dynamic change to "EE", like this image:

And the AA file which is display now will also dynamic change to BB or EE file, too.
Tips: it may be will use removeClass("action") and addClass("action") to make
 change, but I try many times, it cannot achieve my target.
Can anyone help me? Thank you ;]

A: Best way I can think of to do this is keep track of the current "action" index, increment / decrement that when clicking the buttons and iterate the list of links, toggling the action class based on the index.

const links = $(".SwitchURL-small-link")
const modulo = links.length
let selectedIndex = links.index(".action")

$("#smallTitle button").on("click", function() {
  const inc = this.id === "next" ? 1 : -1
  selectedIndex = (((selectedIndex + inc) % modulo) + modulo) % modulo

  links.each((index, link) => {
    link.classList.toggle("action", index === selectedIndex)
  })
})
.SwitchURL-small-list {
  list-style: none;
  display: flex;
  justify-content: space-evenly;
  margin: 0;
  padding: 0;
}

.SwitchURL-small-link.action {
  border-bottom: 2px solid#AE96DA;
  color: #AE96DA;
}

 <button id="prev" type="button"> < </button>

 AA

 BB

 CC

 DD

 EE

 <button id="next" type="button"> > </button>

See JavaScript % (modulo) gives a negative result for negative numbers regarding the fancy modulo arithmetic.

A: I suppose this should work. The comments should help you understand the steps. You can remove them once you understand how the code works.
For your JavaScript:
$('#prev').click(function () {
  // the array of all five links
  var elems = $('#smallTitle li a');
  // get the index of the currently active link
  var activeIndex;
  for (var i = 0; i < elems.length; i++) {
    if (elems[i].classList.contains('action')) {
      activeIndex = i;
      break;
    }
  }

  // get the index of the previous link
  var prevIndex = activeIndex - 1;
  if (prevIndex === -1) prevIndex = elems.length - 1;

  // change the active classes
  elems[activeIndex].classList.remove('action');
  elems[prevIndex].classList.add('action');
});

$('#next').click(function () {
  // the array of all five links
  var elems = $('#smallTitle li a');
  // get the index of the currently active link
  var activeIndex;
  for (var i = 0; i < elems.length; i++) {
    if (elems[i].classList.contains('action')) {
      activeIndex = i;
      break;
    }
  }

  // get the index of the next link
  var nextIndex = activeIndex + 1;
  if (nextIndex === elems.length) nextIndex = 0;

  // change the active classes
  elems[activeIndex].classList.remove('action');
  elems[nextIndex].classList.add('action');
});

A: so simple in JS:

(function() // IIFE closure to protect variables
  {
  const
    links    = [...document.querySelectorAll('.SwitchURL-small-list >li > a.SwitchURL-small-link')]
  , len      = links.length
  , setActiv = n => links.forEach((el,ix)=> el.classList.toggle('action', ix===n))
    ;
  let  activItem = 0
  setActiv(activItem)

  document.querySelector('#prev').onclick = () =>
    {
    activItem = (activItem -1 + len) % len
    setActiv(activItem)
    }
  document.querySelector('#next').onclick = () =>
    {
    activItem = (activItem +1) % len
    setActiv(activItem)
    }
  }
)()
ul {
  list-style  : none;
  font-size   : 2em;
  font-family : Arial, Helvetica, sans-serif;
  }
li {
  display : inline-block;
  width   : 1.3em;
  }
li a {
  color           : #d2bfe7;
  text-decoration : none;
  }
li a.action {
  color : #c249a4
  }
button {
  color      :  #7f7f7f;
  border     : none;
  background : none;
  font-size  : 1.4em;
  }

  <button id="prev" type="button"> < </button>

    AA

    BB

    CC

    DD

    EE

  <button id="next" type="button"> > </button>

A: Here is a vanilla JavaScript example. I added a data-id attribute to each list-item that corresponds with its index for that nodeList. I also added a class to all potential clickable items including buttons, buttons I added the class button and btn, so we can evaluate classList containing next, prev and buttons to add proper logic to conditionals. We also wrap our buttons in list-item tags.
Then I used the [nodeList.length - 1] as index to get last list-item and nodeList[0] to get first list-item. We run conditionals for both next and prev buttons => if e.target.classList.contains('next') we check the current list-item, current = document.querySelector('.action'), is the last, if it is, we set the index to 0. If prev is in classList, and index is 0, we set index to [nodeList.length - 1]. We then either increment on next or decrement on prev. It the event.target is a list-item we set the event.target.classList.add('action').

const buttons = document.querySelectorAll('.btn')
const smallItem = document.querySelectorAll('.SwitchURL-small-item')

function moveSelection(e) {
  // define the current set listitem
  let current = document.querySelector('.action')
  // remove the current actions class
  current.classList.remove('action')
  // define the event target
  const target = e.target
  // get the list-items dataset id
  let data = parseInt(current.parentNode.dataset.id)
  // conditional to check for next and prev buttons
  target.classList.contains('button') ?
    // conditional for next buttons
    target.classList.contains('next') ?
    // check if the list-item is the last one
    data === smallItem.length - 1 ?
    // lets add the action to the first list-item
    smallItem[0].children[0].classList.add('action') :
    // else lets add the data-id by one
    // to get the index of the next element
    smallItem[data + 1].children[0].classList.add('action') : // we have the previous button
    // if we are on the first list-item
    data === 0 ?
    // set the action class to the last list-item
    // using smallItem.length - 1 to match
    // proper index, 5 - 1 = 4
    smallItem[smallItem.length - 1].children[0].classList.add('action') :
    // else we decrement the index by one
    smallItem[data - 1].children[0].classList.add('action') :
    // event target is a "small item" simply assign
    // it to the event target using classList.add()
    target.classList.add('action')
}

// iterate over all buttons
buttons.forEach(btn => {
  // add event listener to each button and pass in
  // callback for logic to determine button being clicked
  btn.addEventListener('click', moveSelection)
})
.SwitchURL-small-list {
  display: flex;
  list-style: none;
  font-size: 22px;
  font-weight: bold;
}

.SwitchURL-small-item {
  border-bottom: 0px solid#AE96DA;
  padding: 0;
  margin-bottom: 0;
  font-size: 20px;
  flex: 0;
}

.SwitchURL-small-link {
  color: #CFC1E9;
}

.SwitchURL-small-link:hover {
  color: #AE96DA;
}

.SwitchURL-small-link.action {
  border-bottom: 2px solid#AE96DA;
  color: #AE96DA;
}

/* added to control width of buttons */

.btn {
  flex: 0;
}

/* added for left margin of all buttons execpt first one */

li~li {
  margin-left: 1rem;
}

.prev {}

    <button class="btn button prev"> prev </button>

    AA

    BB

    CC

    DD

    EE

    <button class="btn button next"> next </button>

A: You can use a combination of parent().children() to acess back and forth the children of the  ul. Also, same functionality happens when clicking on previous or next buttons, so it's possible to encapsulate it in a single function. Observe:

function prevOrNext(str) {
  var temp, childType, nthChild;
  var elems = $('ul li');
  var current = elems.children('a.action').removeClass("action")

  if (str === "#prev") {
    temp = current.parent().prev()
    childType = ":first-child"
    nthChild = ":nth-last-child(2)";
  }
  if (str === "#next") {
    temp = current.parent().next()
    childType = ":last-child"
    nthChild = ":nth-child(2)";
  }

  if (temp.is(elems.parent().children(childType))) {
    elems.parent().children(nthChild).children('a').addClass('action')
  } else {
    temp.children('a').addClass("action")
  }
}

$("#prev").click(() => prevOrNext("#prev"))
$("#next").click(() => prevOrNext("#next"))
.SwitchURL-small-list{
    display:flex;
    list-style:none;
    font-size: 22px;
    font-weight:bold;
}

.SwitchURL-smaill-item{
    border-bottom: 0px solid#AE96DA;
    padding: 0 1%;
    margin-bottom: 1%;
    font-size: 20px;
}

.SwitchURL-small-link{
    color: #CFC1E9;
    margin-right: 15px;
    margin-left: 15px;
}

.SwitchURL-small-link:hover{
    color: #AE96DA;
}

.SwitchURL-small-link.action {
    border-bottom: 2px solid#AE96DA;
    color: #AE96DA;
    margin-right: 15px;
}

   <button id="prev" type="button"> < </button>

   AA

   BB

   CC

   DD

   EE

   <button id="next" type="button"> > </button>


text:
Q: How to pass and store information through methods In the following example when the screen in touched a method is called that passes a number to the view controller that is stored by MyViewController. Only problem the view controller doesn't store the number since I want to use it later in another method. Please help. Thank you.
MyViewController.h
@class MyView;

@interface ViewController : UIViewController {
     int number;
}

-(void)assignNumber(int)sentNumber;

@property int number;

MyViewController.m
-(void)loadView {
    MyView *aView = [[MyView alloc] initWithFrame:wholescreen];
    self.view = aView;
    [aView release];
}

-(id)initWithNibName...... {
    number = 0;
}

-(void)assignNumber:(int)sentNumber {
    number = sentNumber;
}

MyView.h & MyView.m
Default with TouchesBegin, when touched [viewController assignNumber:5];

A: If you don't declare @synthesize, you won't be able to access number from outside of the viewController internals. Try adding
@synthesize number;

to the top of MyView.m; This creates setters and getters. then, you can replace your
[viewController assignNumber:5];

call with
[viewController setNumber:5];

and access it with either viewController.number or [viewController number].

A: You may want to @synthesize the variable number in your ViewController implementation.


text:
Q: Sorting columns from two files with awk I have two input files
28a39a289906c01159f999a68996091a tom@dong.com
274d1d2c7e931fb55ac0c91dd41f2be7 go@far.com
44d25d3b1b70b240d5058f1be1cef576 person@domain.com
2227a768f6d253b7bf81bb4ecb15b52d person@gmail.com

and
28a39a289906c01159f999a68996091a
274d1d2c7e931fb55ac0c91dd41f2be7
44d25d3b1b70b240d5058f1be1cef576
2227a768f6d253b7bf81bb4ecb15b52d

i'm trying to exclude all the rows in file 1 where file2 and file1 have a matching column 1.
md5 suppression.
What i could find was awk 'NR==FNR{a[$1]=$0;next}{print a[$2]}' $1 $2
which i know is pretty close just not sure what i did before to do what i want to do now.

A: If order doesn't matter (i.e. just exclude all emails with an md5 in the exclude file) and you're not wedded to awk, use join:
join -v 1 -j 1 <(sort emails) <(sort excludes)

-v 1 tells it to print lines in the first file (emails) that don't have a corresponding line in the second file (excludes).
-j 1  tells it to only look at the first column of each.

If you want to use awk, I believe this should work:
awk 'NF==1{exclude[$1]++} NF==2&&!exclude[$1]' excludes emails

Or if the two files correspond line-by-line and you only want to exclude, e.g. line 2 if both have the same hash on that particular line, use this:
awk 'NF==1{hash[FNR]=$1} NF==2&&hash[FNR]!=$1' excludes emails

A: This has the benefit that the files can go in either order:
sort file1 file2 | uniq -u --check-chars 32 | grep -E '.{33}'

sort file1 file2 is combining and sorting the files in preparation for uniq.
uniq -u --check-chars 32 considers only the first 32 characters, and with -u, prints only the unique lines.
grep -E '.{33}' prints only the lines containing 33 or more characters.
EDIT
As Peter.O points out, this does not handle the case where two or more entries in the files list have the same md5. In that case, those files will not be printed. I like the join solution the best.
However, this logic depends on all separate files having unique md5's, which is a bad assumption depending on the use of this output. Here is an example of a backup script using the md5sum logic. Though the join logic correctly identifies both fileA and fileB (unlike my solution), there is still a problem:
echo "hello world" > fileA
cp fileA fileB
./backup_script.sh
cp fileA fileC
./backup_script.sh

Did the op indend fileC to be backed up?

A: This command should work:
awk '
  NR==FNR {
    a[$1]=$0;
    next
  }
  { if ( a[$1] ) delete a[$1] }
  END {
    for ( md5 in a ) {
      if ( a[md5] ) { print a[md5] }
    }
  }
' file1 file2


text:
Q: How would you parse in bash #extra_modules  How would I parse
 #extra_modules some string

in kdump.conf file to get "some string" as actual output in bash script ?
Thanks !

A: grep "#extra_modules" kdump.conf | cut -c 16-

grep finds the lines with the phrase "#extra_modules", and cut selects all the characters after the first space


text:
Q: TextboxFor in EditorTemplate does not save value I'm having trouble with using an EditorTemplate in MVC.
My EditorTemplate looks like this:

    @Html.DisplayFor(model => model.Title)
    @Html.DisplayFor(model => model.Authors)
    @Html.DisplayFor(model => model.ISBN13)
    @extPrice.ToString("N2")
    @Html.TextBoxFor(model => model.Price, new { data_val_number = "The field Price must be a number." })
    @Html.TextBoxFor(model => model.MemberPriceStartDate, "{0:dd-MM-yyyy}", new { @class = "form-control datepicker" })
    @Html.TextBoxFor(model => model.MemberPriceEndDate, "{0:dd-MM-yyyy}", new { @class = "form-control datepicker" })
    @Html.HiddenFor(model => model.BookId)

The @model is of type Books (Books is singular due to a database-messup -_-).
The EditorTemplate is called from the view like so:
@Html.EditorFor(model => model)

Where @model is of type IEnumerable<Books>.
When posted to my controller, Books.Price is passed correctly, but Books.MemberPriceStartDate and Books.MemberPriceEndDate is always null.
The hidden field Books.BookId is also passed correctly.
Any ideas as to why that might happen?
EDIT:
Here are the relevant properties on the Books object:
public Nullable<System.DateTime> MemberPriceStartDate { get; set; }
public Nullable<System.DateTime> MemberPriceEndDate { get; set; }
public Nullable<decimal> Price { get; set; }
public int BookId { get; set; }

A: In your model date format for particular field and
 your input date format-"dateFormat: 'dd-mm-yy'" may mismatch.


text:
Q: how i can check all checkboxes watin I want to get all check boxes in page checked.
How to select all check boxes and enable all ?
var chk = browser.checkboxes.where(x => x.id("test string"));

A: You can use this approach.
'
//Getting the count of the check boxes on the page.

int countOfCheckBox = browser.CheckBoxes.Count;

for (int i = 0; i < countOfCheckBox; i++)
{
    browser.CheckBoxes[i].Checked = true;
}
'


text:
Q: Tests dependent on commonly used functionality with NUnit I have some initialization code to use my API. The initialization may fail and I´d like to test it in an NUnit test.
After the initialization the API may be used. I´m testing the API too, but all my test methods will use the same, common, initialization code.
What I would ideally like is if this behavior:

*

*The Initialization test is run.

*The other tests are run if [1] succeeded.

In all cases where [1] will fail, so will all other tests. But the valuable information is that [1] fails. That's where I most likely will find the problem. It would be nice if the other tests could be marked with ? or something, indicating that they did not execute as functionality they depend on didn't pass the tests.
I know that tests should not be brittle. But I can't get around the fact that the initialization code is necessary for correct execution of other functionality.
This is a more general problem where some functionality depends on other functionality. Where the "other functionality" is far too commonly used to provide any real value by failing all tests depending on it. It would be better if the "other functionality" would be tested separately.

A: OK here's how I would go about this...
Put the common initialization into a Setup method since its needed for all tests. If initialization throws an error, you'd see

*

*all Tests in a suite failing (which I have been trained over time to recognize as a hint that maybe setup / teardown has thrown an exception).

*the stacktrace for the failing tests containing the Setup method.

If this is too implicit for you, you may (although I wouldn't recommend it) add an empty test with a good name to the same suite. If that test shows up as green, you can be sure that Setup / common init code has succeeded.
[Test]
public void VerifySetup() {}

Update: Seem like you have a pretty niche requirement. I don't know of any mechanism in NUnit to specify such conditional execution of tests - e.g. Run Test2 thru 10 only if Test1 passes.

A: I've been in contact with the NUnit developers. It's not possible at the moment without writing a pretty complex plugin. The feature will turn up somewhere in the 3.x code base but will not appear in 2.5. I will consider writing it, but not for the time being.

A: Try this:

*

*Define the "Initialization test" as a TestCase

*Make all your other tests a subclass of this TestCase

*Create a Suite which runs your tests in some specific order so that your  "Initialization test" is first.

A: I think that this pretty clear cut. The problem is that you're having a hard time separating out your API responsibilities. You have two. Initialization of API and API execution. Writing your tests to have this kind of dependency can kill you.
So I would recommend that the API create an initialization object and then various command objects to execute the API. The command objects will be in some kind of store or you could create on the fly.
The API will use a mocked initialization object and it will use mocked command objects.
The Initialization Object really doesn't have any dependencies except for whatever you need to initialize.
The Command objects will need a mocked initialization object.
[EDIT]
There are two way to get the other tests to fail if the initialization test fails

*

*Add a private variable to the test case. private isInitialized = false;. Then all your other tests check the state of this variable if not true then fail.

*Extend your test case with the API class. Add private function that interrogate state of initialization.
The cleaner of the two is 2. The fastest implementation is 1.
IMHO This can be a code smell when you have to couple your tests in such a manner. If as you said it is an integration tests. Why do you have a separate test for initialization. Integration is more along the lines of run some action against your API. So each integration test MUST initialize the API.
You might want to rethink your cascade failure scenario. It might be too much noise at completion of tests.
[EDIT1a]
The only way I can see to satisfy your requirements is to extend NUnit. Specifically look into Test Case Builders and Test Decorators.
The link is dated March 2008, so hopefully it isn't to out of date.


text:
Q: Twitter Web Intents inside iOS/Android Webview - any Redirect/Callback URL? Twitter Web intents provides convenient JS lib to allow the user to tweets from an external website.

link

This works great on mobile browser by openining a new window  with twitter's textarea for the user to submit its tweet. Once tweeted the popup close and the user is back on the original page.
However in the context of a native app using webviews (a good example is facebook webview) the flow seems to be broken. Rather than opening a popup or new window it redirect the current webview to twitter page. From there there is no way for the user go back to the original page.
Is there any parameter that i could pass to  https://twitter.com/intent/tweet for twitter to redirect back to the user page after tweeting or canceling.
I have tried to use twitter @anywhere as well but the tweetbox does not even display on iOS UIWebview.
Is there any alternative for client side only flow ?


text:
Q: How do I build a new object that contains a List as attribute? So, in my main form class I have the following list, which is populated by user input:
List<string> ProduseAlese = new List<string>();

And after it's populated, it's going into this constructor:
Comenzi comanda = new Comenzi(nrCom, dataCom, dataLiv, factura, ProduseAlese);

And my class looks like this:
public class Comenzi
{
    public int NrComanda { get; set; }
    public DateTime DataComanda { get; set; }
    public DateTime DataLivrare { get; set; }
    public List<string> Articole { get; set; }
    public Facturi Factura { get; set; }

    public Comenzi(int nrcomanda, DateTime datacomanda, DateTime datalivrare, Facturi _factura, List<string> _articole)
    {
        NrComanda = nrcomanda;
        DataComanda = datacomanda;
        DataLivrare = datalivrare;
        Factura = _factura;
    }
}

What do I have to write in the constructor?
The point is to copy the items from the initial list into the newly created object.

A: This should work:
public List<string> Articole { get; set; } = new List<string>();
public Facturi Factura { get; set; }

public Comenzi(int nrcomanda, DateTime datacomanda, DateTime datalivrare, Facturi _factura, List<string> _articole)
{
    NrComanda = nrcomanda;
    DataComanda = datacomanda;
    DataLivrare = datalivrare;
    Factura = _factura;
    _articole = _articole?? new List<string>();
    Articole.AddRange(_articole.ToArray());
}

A: If what you want is to copy the list objects into a new list, you can use the ToList() method from the System.Linq namespace.
Articole = _articole.ToList();

A: Maybe you don't "have to" use the class constructor to feed all your object data, unless there is a requirement needing you to do so.
Since your properties are public you could asign a value to them after creating the object
Comenzi comanda = new Comenzi(nrCom, dataCom, dataLiv, factura);
comanda.Articole = ProduseAlese;

Keep in mind that as you're developing your application your class definition might grow and is not a good practice to fill ALL the properties in the constructor. You have to keep only the ones that are mandatory for your objects of that class.


text:
Q: web server leaks a private IP address through its HTTP headers. how to fix? I've already located this question on server fault:
Server Fault Question
But there is no answer. Does anyone have any advice on how to fix the issue?
We're running 2003 Server R2 Ent, latest service pack is applied, IIS 6.0
Here's what the compliance company is saying:

Synopsis : This web server leaks a private IP address through its HTTP headers. Description : This may expose internal IP addresses that are usually hidden or masked behind a Network Address Translation (NAT) Firewall or proxy server. There is a known issue with Microsoft IIS 4.0 doing this in its default configuration. This may also affect other web servers, web applications, web proxies, load balancers and through a variety of misconfigurations related to redirection. See also : http://support.microsoft.com/support/kb/ articles/Q218/1/80.ASP

Any ideas?
Thanks

A: Umm... have you read the KB and it's companion article for IIS6?
http://support.microsoft.com/kb/834141/


text:
Q: Running TestNG through commadline ubuntu not working When tried to run the testNg through commandline in ubuntu it throws the
java –cp "bin:/home/john/selenium-lib/*" org.testng.TestNG src/testing.xml

Error: Could not find or load main class –cp

*

*src/TestCase */
package Test;
 import org.testng.annotations.Test;

 public class TestCase {
    String message = "Hello World";

       @Test
       public void testPrintMessage() {
           System.out.println("Invoked testString " + message);

       }
 }

src/testing.xml

A: I am guessing that you perhaps did a copy paste due to which - (hyphen) is being read as a special character –. Please try again by typing -cp (hyphen cp)


text:
Q: Related to sum of series I have a doubt in this particular question
Q.
If $$(20)^{19}+2(21)(20)^{18}+3(21)^2(20)^{17}+\cdots+20(21)^{19}=k(20)^{19}$$ then find the value of $k$
In this I have tried to solve it by first taking out the general term and then calculating the sum but eventually I am not getting the correct answer which is $400$.
Can you tell me where I am going wrong in solving this question and is my method of solving this question correct?? Can we solve such type of questions by taking general term??

A: So, $k$ must be $$k=1+2\left({21\over 20}\right)+3\left({21\over 20}\right)^2+\cdots +20\left({21\over 20}\right)^{19}$$which can be written as $$k=\sum_{i=1}^{20} i\left({21\over 20}\right)^{i-1}$$By defining $$f(x)=\sum_{i=1}^{20} ix^{i-1}={d\over dx}\sum_{i=1}^{20} x^{i}$$it is clear that
$$
k{={d\over dx}\sum_{i=1}^{20} x^{i}\Bigg|_{x={21\over 20}}
\\={d\over dx}\left[{x^{21}-1\over x-1}-1\right]_{x={21\over 20}}
\\=\left[{21x^{20}(x-1)-(x^{21}-1)\over (x-1)^2}\right]_{x={21\over 20}}
\\={\left({21\over 20}\right)^{21}-\left[({21\over 20}\right)^{21}-1]\over \left({1\over 20}\right)^2}
\\=400
}
$$


text:
Q: How to pass "this" context to an anonymous function I'm trying to build autocomplete for some input fields with DevBridge Autocomplete famous plugin/library (not sure what the exact term is).
My common problem is that I lose "this" context when entering the function that should determine what parameter to send (which is now a simple alert($(this).attr('class')) to check the context)
I need to pass an argument to my backend to know which input is the current one beeing treated.
My selector is on an input html looking like that:
<input type="text" class="input_actu input_autocomplete" id="input_contentactualites0" name"input_contentactualites0" data-id="" value="" size="70" maxlength="300"/>

For now it looks like this:
  $('.input_autocomplete').devbridgeAutocomplete({
  serviceUrl: 'autocomplete',
  params: {
    flag: function() {
      alert($(this).attr('class'));
    }
  },
  minChars: 3,
  type: 'post',
  onSelect: function(suggestion) {
    $(this).attr("data-id", suggestion.data)
   }
  });

There are plenty of posts and solutions about this problem, I've tried the .bind(this) like that :
    $('.input_autocomplete').devbridgeAutocomplete({
        serviceUrl: 'autocomplete',
        params: {flag: function () {
        alert($(this).attr('class'));
    }.bind(this)},
        minChars: 3,
        type: 'post',
        onSelect: function (suggestion) {
            $(this).attr("data-id", suggestion.data)
        }
});

And it doesn't seem to work, I've also read about call() but I'm not sure if it can work in my case.
Also I would rather not use a Global as it's not the good way to do it.
Any advice is very welcome, thanks for your time reading and helping :)

A: Maybe this help ?
    var params = {
        flags: function (o) {
            alert($(o).attr('class'));
        }
    };

    var config = {
        serviceUrl: 'autocomplete',
        minChars: 3,
        type: 'post',
        onSelect: function (suggestion) {

            $(this).attr("data-id", suggestion.data);
            //#####################Fire the event:
              params.flags(this);
        }
    };

    var configDev = $.extend(config, params);

    $('.input_autocomplete').devbridgeAutocomplete(configDev);


text:
Q: C# .Net application, some specific html pages not opening, renders empty screen on click using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using eLearningHub.Core.DataModel.Base;

namespace eLearningHub.Core.DataModel
{
    [Table("ClassEnroll")]
public class ClassEnroll : BaseModel
{
    [Required]
    public string Status { get; set; }

    [ForeignKey("ClassModel")]
    [DisplayName("Class")]
    public int ClassId { get; set; }
    public ClassModel ClassModel { get; set; }

    [ForeignKey("TeacherModel")]
    [DisplayName("Teacher")]
    public int TeacherId { get; set; }
    public TeacherModel TeacherModel { get; set; }

    [ForeignKey("StudentModel")]
    [DisplayName("Student")]
    public int StudentId { get; set; }

    public StudentModel StudentModel { get; set; }

}
}

the above code is the C# core datamodel.
cshtml code:
@model IEnumerable<eLearningHub.Core.DataModel.ClassEnroll>
@{
    ViewBag.Title = "CourseListByStudent";
    Layout = "~/Views/Shared/_DashBoard.cshtml";
}
<link href="~/Content/AdminLTE/Content/cardstyle.css" rel="stylesheet" />

@if (TempData["Msg"] != null)
{

            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

 info!

            @TempData["Msg"].ToString()

}
@if (TempData["FMsg"] != null)
{

            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

 Failed!

            @TempData["FMsg"].ToString()

}

@foreach (var c in Model)
{

Class Details

Class Name :

@c.ClassModel.ClassName

Teacher :

@c.TeacherModel.Name

 Email :

 @c.TeacherModel.Email

                       Notes
                    Notice
                    Exam Mark

}

Let me further explain my issue, I am running a .net application that i have done, however, I have many cshtml pages and all connected to an sql DB, everything in the program works perfectly except for some pages, they simply won't load whatsoever and I cant figure out why that is happening,
I have also realized that all the pages that are not working or even loading (no error given, simple an empty page)
All the pages that are not opening have the same public class ClassEnroll
any tips ?


text:
Q: When input is empty or has < 2 caracters dont show result I'm using this js to get results from a php file and output them, this happens on keyup. Everything is working well but the problems is when I type something and than erase the last result won't erase. How can I make the script erase the result if the input is empty or if there is only one character typed?
$('#username-search').keyup(function() {
    if (this.value.length < 2) return;
    var usersearch = $(this).val();

    $.post("autocomplete_user.php", {
        results: usersearch,
    },

    function(data) {
        $('#data').html(data)
    });
});

A: Update your if statement to the following:
if (this.value.length < 2) {($('#data').html() != "" ? $('#data').html("") : return true)}
What this does is, if the input goes below 2, it will check to see if that DOM element with the id of DATA has anything in it, if it does, it erases the data, if not then it just returns.

A: You can do this with JQueryUI Autocomplete
See also https://stackoverflow.com/questions/188442/whats-a-good-ajax-autocomplete-plugin-for-jquery


text:
Q: Ext-js display calendar from Monday in Ext Date Menu In Ext.picker.Date or datePicker we can set this as shown in below code.
var dateField=new Ext.form.DateField({
startDay: 1
});

But i am unable to do the same in dateMenu.Can anyone help me out with this.

A: did you try picker property?
http://docs.sencha.com/extjs/3.4.0/#!/api/Ext.menu.DateMenu  (under property)

A: It works fine for me, see the fiddle.
To quote the documentation:

Notes:
Although not listed here, the constructor for this class accepts all of the configuration options of Ext.picker.Date.


text:
Q: How to handle Dialogflow list response I am developing an app for Google Assistant using Dialogflow (using Dialogflow online interface, without any external server).
I have a list of products. Each product has an intent which is trained with its product name.
For example if I say "Product 1" the assistant will show me some information about "Product 1".
I also made an intent which lists all the products you can browse. As a response it shows a Google Assistant "List" which displays the names of all the items.
But when I click one of the items, it will type its name("Product 1") but the item name is not recognized and I got the fallback intent.
I though lists could work like suggestion chips but it looks like answers are interpreted differently.
By looking for examples I could only find examples using Dialogflow API from code (https://actions-on-google.github.io/actions-on-google-nodejs/classes/conversation_helper.list.html), and it seems that list answers are handled with a special type of intent.
Is there a way to handle list response directly from Dialogflow online interface ?

A: It does not handle the List or Carousel interfaces the same way it handles the suggestion chips. As you note - they trigger a special Event, which you're expected to create an Intent for.
There are a number of reasons for this, but one good one is that these tend to be fairly dynamic (they're meant to represent things like search results), so having to manage these with a Session Entity might be more difficult.
You can use the Dialogflow Inline Editor to handle them. This is essentially the same as using a fulfillment server - however Dialogflow handles most of the server management for you.


text:
Q: Case class implementing trait Case class can extend trait and implement it using its fields.
trait IWork {
  def itWorks: String
}
case class Example(itWorks: String) extends IWork

It compiles and works fine. Could you please explain, why it can't be compiled?
trait IsAfter {
  def after(test: Date): Boolean
}
case class Example2(after: Date => Boolean) extends IsAfter

A: You can implement an abstract def using a val and that's what you're doing in the first example.
However, you're working under the assumption that methods and functions are the same thing. Unfortunately this is not the case, despite the best efforts by the scala compiler to hide this fact.
Here's a thorough explanation of the differences.
For this reason you cannot implement an abstract method using a function, but you have to do something like
class Example2(a: Date => Boolean) extends IsAfter {
  def after(test: Date) = a(test)
}


text:
Q: What is the best way to insert source code examples into a Microsoft Word document? I have to write some documents that will include source code examples. Some of the examples will be written from the IDE, and others would be written in place. My examples are primarily in Java.
As someone who is used to LaTeX, doing this in Word is extremely painful. However, I am bound to Word for this. The only options I have seen are:

*

*Write or copy into the document,
then use a fixed type font, arrange
formatting and hope that Word didn't
uppercase stuff for you. Needless to
say, this looks like crap.

*Copy and paste screenshots of source
code from the IDE. At least I keep
colors. However, if I change my font
size, I'm screwed. I'm also screwed
across page boundaries. And let's
admit it, Word is not great at
managing multiple images on a
document.

*Write HTML (not really an option
here)

Is there some better (and ideally portable) way to do this? Is there at least some sort of verbatim style similar to the LaTeX environment? Is there at least some pretty printer that I could copy-and-paste as RTF?

A: Use this - http://hilite.me/
hilite.me converts your code snippets into pretty-printed HTML format, easily embeddable into blog posts, emails and websites.
How:
Just copy the source code to the left pane, select the language and the color scheme, and click "Highlight!". The HTML from the right pane can now be pasted to your blog or email, no external CSS or Javascript files are required.
For Microsoft Word document: Copy the the content from the Preview section and paste to your Microsoft Word document.
3 sections : Source Code , HTML and Preview

A: These answers look outdated and quite tedious compared to the web add-in solution; which is available for products since Office 2013.
I'm using Easy Code Formatter, which allows you to codify the text in-place. It also gives you line-numbering options, highlighting, different styles and the styles are open sourced here: https://github.com/armhil/easy-code-formatter-styles so you could extend the styling yourself. To install - open Microsoft Word, go to Insert Tab / click "Get Add-ins" and search for "Easy Code Formatter"

A: I recently came across this post and found some useful hints. However, I ended up using an entirely different approach which suited my needs. I am sharing the approach and my reasoning of why I chose this approach. The post is longer than I would have liked, but I believe screenshots are always helpful. Hopefully, the answer would be useful to someone.
My requirements were the following:

*

*Add code snippets to a word document, with syntax highlighting for easier visibility and differentiation of code and other text.

*Code snippet shall be inline with other text.

*Code snippet shall break across pages smoothly without any extra effort.

*Code snippet shall have a nice border.

*Code snippet shall have spell-check disabled.

My Approach is as listed below:

*

*Use external tool to achieve syntax highlighting requirement 1 above.
One could use notepad plus plus as described above. However, I use the tool present here - https://syntax-highlighter.k26.ch/. This gives me the option to use line number, as well as very nice syntax highlighting (Please use Google Chrome for this step, because syntax highlight is not copied when using Mozilla Firefox, as also pointed out by couple of user comments). Steps to achieve syntax highlighting are listed below:

*

*Open the website provided above in chrome and Copy the code snippet in the text area. I will be using a sample XML to demonstrate this (XML sample from here - http://www.service-architecture.com/articles/object-oriented-databases/xml_file_for_complex_data.html).

*Select the language from drop down menu.

*Click "Show Highlighted" button. It will open a new tab, with syntax-highlighted code snippet, in this case the XML sample we chose. See image below for example.

*To Turn off the line numbers, inspect the page in chrome. Then, under styles, deselect the "margin" property in ".dp-highlighter ol", as shown in the image below. If you want to keep the line numbers, go to next step.

*Select the syntax-highlighted code and click copy. Now your code is ready to be pasted into Microsoft word.

Thanks to this blog for providing this information - http://idratherbewriting.com/2013/04/04/adding-syntax-highlighting-to-code-examples-online-and-in-microsoft-word/.
2. To achieve requirements 2, 3 and 4 above, use table in Microsoft word, to insert the code snippet. Steps are listed below:

*Insert a table with single column.

*Paste the copied text from step 1. in the table column. I have kept the line numbers to show how well this works with Microsoft word.

*Apply border, as you like. I have used size 1pt. Resulting Microsoft word snippet will appear as shown in screenshot below. Note how nicely it breaks across the page - NO extra effort needed to manage this, which you would face if inserting "OpenDocument Text" object or if using "Simple TextBox".

*To achieve requirement 5, follow the steps below:

*Select the entire table or the text.

*Go to Review tab. Under Language, choose "Proofing Language". A new pop-up will be presented.

*Select "Do not check spelling or grammar". Then, click OK.

*Resulting text has spell-check disabled. Final result is shown in the image below and meets all the requirements.

Please provide if you have any feedback or improvements or run into any issues with the approach.

A: This is related to this answer: https://stackoverflow.com/a/2653406/931265
Creating an object solved all of my problems.
Insert > Object > Opendocument Text
This will open a document window, paste your text, format it how you want, and close it.
The result is a figure. Right click the object, and select 'add a caption'.
You can now make cross references, create a table of figures.

A: If you are still looking for an simple way to add code snippets.
you can easily go to [Insert] > [Object] > [Opendocument Text] > paste your code > Save and Close.
You could also put this into a macro and add it to your easy access bar.
notes:

*

*This will only take up to one page of code.

*Your Code will not be autocorrected.

*You can only interact with it by double-clicking it.

A: I absolutely hate and despise working for free for Microsoft, given how after all those billions of dollars they STILL do not to have proper guides about stuff like this with screenshots on their damn website.
Anyways, here is a quick guide in Word 2010, using Notepad++ for syntax coloring, and a TextBox which can be captioned:

*

*Choose Insert / Text Box / Simple Text Box

*A default text box is inserted

*Switch to NPP, choose the language for syntax coloring of your code, go to Plugins / NPPExport / Copy RTF to clipboard

*Switch back to word, and paste into the text box - it may be too small ...

*... so you may have to change its size

*Having selected the text box, right-click on it, then choose Insert Caption ...

*In the Caption menu, if you don't have one already, click New Label, and set the new label to "Code", click OK ...

*... then in the Caption dialog, switch the label to Code, and hit OK

*Finally, type your caption in the newly created caption box

A: You need to define a style in your Word document and use that for source code. I usually have a style called "Code" which has a monospaced font in a small point size, fixed size tabs, single line spacing, no before/after paragraph spacing, etc. You only need to define this style once and then reuse it. You paste in your source code and apply the "Code" style to it.
Note that some editors (e.g. Xcode on the Mac) add RTF as well as text to the clipboard when copying/pasting between applications - Word recognises RTF and helpfully retains the formatting, syntax colouring, etc.
Source code in Xcode:

Copied and pasted to Word:

(Note: it's a good idea to disable spell-checking in your "Code" style in Word.)

A: On a Mac I find this solution with vim to be wonderful:
https://github.com/zerowidth/vim-copy-as-rtf

A: There is an easy way if you want simple code formatting.

*

*Open word> Insert tab> click on "Get Add-ins"

*search for "Content mixer"
3.click on "Add"

Then content mixer add will open automatically and you can copy paste your code in there and click on "Insert" to insert it in word doc.

A: It kind of depends on the IDE. Both Visual Studio and Eclipse, for example, will allow you to copy as RTF and paste into Word, keeping all your formatting.
Notepad++ has a plugin called "NppExport" (comes pre-installed) that allows you to copy to RTF, though I don't care much for Notepad++'s syntax highlighting (it'd definitely be passable though). What it does do is support dozens of languages, whereas the aforementioned IDEs are limited to a handful each (without other plug-ins).

A: You can use Open Xml Sdk for this. If you have the code in html with color and formatting. You can use altchunks to add it to the word documents.
Refer this post Add HTML String to OpenXML (*.docx) Document
Hope this helps!

A: This is what i did.
End results :

https://stackoverflow.com/a/25092977/1161594

A: You can using Plugin Syntax Highlight in Ms.Word https://store.office.com/syntax-highlighter-WA104315019.aspx?assetid=WA104315019 . i follow that step and it's work

A: In Word, it is possible to paste code that uses color to differentiate comments from code using "Paste Keep Source Formatting." However, if you use the pasted code to create a new style, Word automatically strips the color coded text and changes them to be black (or whatever the auto default color is). Since applying a style is the best way to ensure compliance with document format requirements, Word is not very useful for documenting software programs. Unfortunately, I don't recall Open Office being any better.
The best work-around is to use the default simple text box.

A: I have tried all your methods, but they didn't work for me, in fact I have created an easier method using MS Word Tables.
Pros:

*

*More beautiful

*Easier to manage & more consistent

*Are less prone to problems

*No need for external plugins or MS Word micro coding.

*Easier to handle by simple users (such as myself).

Cons:
It will not maintain code colouring although someone could improve my trick.
Steps:

*

*Insert a 3x3 table, in my case I always make the total width of the table equals the free page's width (3 rows minimum to test the tables style).

*Use invisible borders ("No Borders" option), and activate "View Gridlines" option. it should have this aspect.
Be ware that those lines are for you to see the table's grid, and the will not be printed.

*Make the adjustments to cells' spacing and columns' width to get the aspect you like. (You will have to get in "Table Properties" for fine tuning).

*Create a "Paragraph Style" with the name of "Code" just for your code snippets (check https://stackoverflow.com/a/25092977/8533804 to get the idea, you don't have to follow all of it)

*Create another "Paragraph Style" with the name of "Code_numberline" that will be based upon the previous created style.

*In the newly created "Code_numberline" add the numbering style that you like (this will automate line numbering).

*Apply "Code_numberline" to the first column, and "Code" to the 3 column.

*Add a fill in the middle column.

*Save that table style and enjoy!

A: So I've found the majority of answers on this question to either be only semi-functional or broken entirely (eg the website used is down). This solution is entirely self-contained in Word, works across multiple pages, and keeps your syntax highlighting.
Here's the steps:

*

*Temporarily set your IDE's theme to a light one, so that the text will fit in with the rest of your document.

*Copy the required code (HTML colourising info will be copied with it).

*In Word, hit Ctrl+Alt+V and choose HTML Format to paste the coloured text.

*Select all your text and then expand the styles gallery on the home tab of the ribbon.

*Choose "Create a style". Use a name such as "Code"

*Right click your new style in the gallery and choose "Modify".

*Under the formatting section, change the font to Consolas or your choice of monospace font. Also set the line spacing to Condensed (this option is next to the text alignment options).

*Under the format button in the bottom left, choose "Language", then enable the "Don't check spelling or grammar" option.

*If you want this style to be available in future documents, change to the "New documents based on this template" radio button.

Optional: for line numbers...

*Back in the Modify Style dialogue, choose the format button again and choose "Numbering".

*Choose the "Define new number format" option.

*Remove the dot after the number '1' in the number format box.

*Choose "Right" as the number alignment.

*Hit ok, then select your new number alignment option. Finally, hit ok on the Modify Style dialog.

Finally, select your code, and set it to be the Code style, which should apply all the required formatting.


text:
Q: given a start date how to find the end date which have 365 or 366 days based on the leap year public static DateTime GetBudgetYearEndDateConsideringLeapYear(DateTime budgetYearStartDate)
    {
        DateTime endDate = DateTime.MinValue;
        if (budgetYearStartDate == null)
            throw new ArgumentNullException("budgetYearStartDate must be provided before calling this method");

        int startingDateMonth = budgetYearStartDate.Month;
        if (startingDateMonth > 2) /// Leap year for the starting year is escaped because  Month is NOT February
        {
            endDate = budgetYearStartDate.AddDays(365);
            bool isEndYearLeapYear = DateTime.IsLeapYear(endDate.Year);

            if (isEndYearLeapYear)
            {
                return endDate.AddDays(1);
            }
            return endDate;
        }
        else  // started from JAN/ FEB
        {
            if (DateTime.IsLeapYear(budgetYearStartDate.Year))
            {
                return budgetYearStartDate.AddDays(366);
            }
            return budgetYearStartDate.AddDays(365);
        }

    }

What am I missing here

A: What's wrong with:
public static DateTime GetBudgetYearEndDateConsideringLeapYear
    (DateTime budgetYearStartDate)
{
    return budgetYearStartDate.AddYears(1);
}

? In other words, return the date a year from the start date, regardless of whether or not it's a leap year.
A couple of things to note:

*

*You should consider what you want the result to be if the start date is February 29th

*Your check for nullity is pointless, given that DateTime is a value type

A: AddYears takes leap years into account so...
budgetYearEndDateConsideringLeapYear = budgetYearStartDate.AddYears(1);

A: How about startDate.AddYears(1).AddDays(-1);?
This assumes that given a start date of July 1, you want an end date of June 30.  The example you posted suggests that you want July 1 -> July 1, in which case, it would be startDate.AddYears(1);.

A: Try this:
DateTime dtStartOfThisYear = new DateTime( 2011, 11 , 1 ) ;
DateTime dtStartOfNextYear = dtStartOfThisyear.AddYears(1) ;

If you crack open the AddYears() method in Reflector, you'll see that it just invokes the AddMonths() method, passing it the value years * 12. Clever, huh?
And if you crack open AddMonths(), you'll see
public DateTime AddMonths(int months)
{
    if ( ( months < -120000 ) || ( months > 0x1d4c0 ) )
    {
        throw new ArgumentOutOfRangeException("months", Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadMonths"));
    }

    int datePart = this.GetDatePart( 0 ) ;
    int month    = this.GetDatePart( 2 ) ;
    int day      = this.GetDatePart( 3 ) ;

    int num4     = ( month - 1 ) + months ;
    if ( num4 >= 0 )
    {
        month     = ( num4 % 12 ) + 1 ;
        datePart += num4 / 12 ;
    }
    else
    {
        month     = 12 + ( ( num4 +  1 ) % 12 ) ;
        datePart +=        ( num4 - 11 ) / 12   ;
    }

    if ( ( datePart < 1 ) || ( datePart > 0x270f ) )
    {
        throw new ArgumentOutOfRangeException("months", Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
    }

    int num5 = DaysInMonth( datePart , month );
    if ( day > num5 )
    {
        day = num5 ;
    }

    return new DateTime(((ulong) (DateToTicks(datePart, month, day) + (this.InternalTicks % 0xc92a69c000L))) | this.InternalKind);
}

I believe you'll find that this code does what you want: for instance, if you start on 29 February of a leap year and add 1 year, you'll wind up on 28 February of the next year.


text:
Q: How does the heat energy from burning a gallon of gasoline compare to the solar energy the resulting $\rm CO_2$ absorbs in the atmosphere? I think essentially all of the energy from a gallon of gasoline burned in, say, a car is eventually converted into heat in the atmosphere. But I don't think the heat from burning fossil fuels contributes in any material way to global warming -- the idea of heating the earth directly, even at the scale we currently burn fossil fuels, seems unlikely. But the earth is nonetheless warming up.
That suggests, a little counterintuitively to me, that the solar heat adsorbed by the $\rm CO_2$ generated from burning a gallon of gas must exceed the heat from burning that gallon of gas (at least over the timescale that that $\rm CO_2$ remains in the atmosphere -- Google gives me a half-life of ~120 years.) Perhaps even by a few orders of magnitude.
To put a specific point on it: what fraction of the total heat from burning a gallon of gasoline actually comes from burning the gasoline? (Over the whole lifetime of the $\rm CO_2$ in the atmosphere.)


text:
Q: Assignment with pandas iloc where RHS length is shorter than LHS I am trying to perform np.where function on a dataframe starting from row 20 onward. The code that I entered as follow:
df['buy'] = np.where((df.iloc[20:,]['signal']==1), 'buy','no buy')

It showed the error below:
ValueError: Length of values (226) does not match length of index (246)
Anyone know how to fix it please?
I want pandas to return value from row 20 onward.

A: This is an assignment error, df has 246 entries, but you are trying to assign a numpy vector with 226 values to it.
What do you intend the result should be?
you could subset the dataframe?
df_sub = df.iloc[20:].copy()
df_sub['buy']=np.where((df_sub.iloc['signal']==1), 'buy','no buy')

A: IIUC, you could use "mixed" indexing for the assignment:
n = df.columns.get_loc('buy')
df.iloc[20:, n] = np.where((df.iloc[20:,]['signal']==1), 'buy','no buy')


text:
Q: vlookup next match or skip row I am trying to get the next match in excel when using Vlookup or Index Match. I cant seem to skip results I already have. I cannot have a helper column because it is a database that is imported from access that I cannot change, and I can't have VB code (mainly because I don't know VB too well and I don't know how to use it in excel). Here is an example of what I want:

This is just an example. I have a database with hundreds of records from 50 teams that I don't really want to give out

A: Use this "array formula" in G4
=IFERROR(INDEX(B$2:B$100,SMALL(IF(A$2:A$100=G$1,ROW(A$2:A$100)-ROW(A$2)+1),ROWS(G$4:G4))),"")
comfiirmed with CTRL+SHIFT+ENTER and copied down as far as required and more. When qualifying values run out you get blanks
Adjust ranges as required


text:
Q: Examples of non-singular hypersurfaces exhibiting Hasse principle failures Suppose that $f\in \mathbb{Z}[x_1,\dots,x_n]$ and $f$ is a homogenous polynomial of degree $d$. Can we always construct $f$ such that the hypersurface $S_f=\{x \in \mathbb{Z}^n:f(x)=0\}$ exhibits the failure of the Hasse principle? In particular, I am trying to understand why the non-singularity condition in results of Birch (Forms in Many Variables), Browning-Prendiville etc. is vital. I am told that there in case of $d=4$, there is an example of Hasse failure, probably by Swinnerton-Dyer ($S_f$ for $f(x_1,x_2,x_3,x_4)=7x_1^4+8x_2^4-9x_3^4-14x_4^4$) (not sure how it is a Hasse failure and how easy it is to prove that it is one, but at any rate, it is a non-singular hypersurface that demonstrates that 4 variables are not nearly enough). Can we find more examples of such hypersurfaces which fail to satisfy the hassy principle, for degree $d=4$ or otherwise? I was just hoping to find a large class of examples of such $f$, not just one.

A: Daniel Loughran's suggestion to study the paper Random Diophantine Equations by Poonen and Voloch was a good one.
Te conjecture 3.2 of the paper Daniel Loughran linked, together with Appendix A (both due to Colliot-Thélène), implies that the Hasse principle holds for nonsingular hypersurfaces of degree $4$ in $n$ variables as soon as $n>4$.
So, conjecturally, the condition $n>48$ in Browning-Prendiville is not at all necessary, and the $n>48$ condition is "merely" a restriction of the technique.
For $n=4$, there are more counterexamples. The paper Counterexamples to the Hasse principle in families contains two infinite families along the lines of Swinnerton-Dyer's example.


text:
Q: Is it possible to create a NavLink like structure in React using only HTML5 and JavaScript? I have a question for you, is it possible to create a NavLink like structure in React using only HTML5 and JavaScript?
For example, if we have a homepage.html and a content.html file and I want to go to content.html when an "a" element is clicked, how can I do this without refreshing the page?

A: Yes you can do it using the history API, you can navigate to different pages without refreshing the page
window.history.pushState('page 2, "page 2 title", "page2.html")

Incase of replace the page you can use window.history.replaceState() to replace the current page with the new page.
Reference:- https://developer.mozilla.org/en-US/docs/Web/API/History_API/Working_with_the_History_API


text:
Q: Unity3d: Random.Range() Not working the way I intended I'm spawning objects from a list and so-far i got them to find a parent object that's already live in the scene.The problem is Random.Range() isn't working like I want. I want the listed Objects to spawn to a random parent, instead, they're spawning to the they're parent relative to the order of the list.
Ex. 0,1,2,3,4,5,6,7,8,9 = Bad
Ex. 8,3,1,4,6,3,7,9,5,2 = Good
lol
var theRange = Random.Range(obj1.Length,obj1.Length);
    for(var i: int = 0; i < theRange; i++){
        var obj2 : GameObject = obj1[i];
        if(obj2.transform.childCount == 0){
        objfromList.transform.parent = obj2.transform;
        objfromList.transform.localPosition = Vector3(0,-2,0);
    }
    }

Deeply thankful

A: Following up on my comment, it sounds like you just want a shuffle function.  Here is a simple Fisher-Yates shuffle:
void shuffle(int[] a){
    for(int i = a.Length-1; i>=0; i--){
        int j = Random.Range(0,i);
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }
}

void usage(){
    int[] a = {0,1,2,3,4,5}; // assumes obj1.Length = 6
    shuffle(a);
    for(int i = 0; i < a.Length; i++){
        GameObject obj2 = obj1[a[i]];
        GameObject objFromList = GetNextObject(); // dummy method grabbing next list object

        objFromList.transform.parent = obj2.transform;
        objFromList.transform.localPosition = Vector3(0,-2,0);
    }
}

This should get you part way to what you need.  If the order of obj1 isn't important you can shuffle it directly instead of using a secondary array like a in my example.


text:
Q: Getting an assertion error while views testing using invalid data in django I am testing my webapp by developing testcases using invalid data. Everything runs fine except for an assertion error that is bugging me a lot. I am trying to prevent a suer from registering if a same email id like his exists. In such a case, the same form will be rendered with the context as errors.(Check the code written below). But it keeps on showing an assertion error.
Here is my code:
Here is my views.py:
def register(request):
    if request.method == 'POST':
        user_form = CustomUserCreationForm(data=request.POST)
        if user_form.is_valid():
            ob = CustomUserCreationForm.register(user_form)
            if ob.is_active is False and ob.is_staff is False:
                return render(request, 'todoapp/waiting.html')
            else:
                return render(request, 'todoapp/admin_success.html')
        else:
            return render(request, 'todoapp/register.html', {'errors': user_form.errors})
    return render(request, 'todoapp/register.html', {'form': CustomUserCreationForm()})

Here is my urls.py:
url(r'^register/', views.register, name='register'),

Here is my tests.py:
sent_data = {
            'first_name': 'john',
            'last_name': 'doe',
            'email': 'johndoe@gmail.com',
            'password': 'johndoe'
        }
        response = self.client.post(url, sent_data)
        self.assertEqual(response.status_code, 200)
        expected_data = {
            'email': 'User with this Email already exists.'
        }
        self.assertEqual(response.context['errors'], expected_data)

Here is the error:
self.assertEqual(response.context['errors'], expected_data)
AssertionError: {'email': [u'User with this Email already exists.']} != {u'errors': {u'email': u'User with this Email already exists.'}}

A: Assertion Error are because of left!=right here you want to compare the message as response you can check for this specific case
self.assertEqual(response.context['errors']['email'][0], expected_data['email'])

or
better you can modify your expected_data as errors comes in a list
expected_data = {
            'email': [u'User with this Email already exists.']
        }

self.assertEqual(response.context['errors'], expected_data)

Key is you see what response is actually getting returned and build your expected-data like that now onward.


text:
Q: Is it generally better to compress content on the proxy server or the app server? We're using an F5 for load balancing and SSL proxying.  Behind it we're serving up java applications with Tomcat instances.  These are fairly small applications - hundreds of concurrent users.
I'd like to compress some of the content, and I'm looking for advice on choosing to configure compression on the F5, or on the tomcat instances.  Any big factors in the decision, or is it 6-of-one half-dozen of the other?

A: If you are doing Layer 7 load balancing (HTTP) then there is no real benefit in the app server compressing the content because the proxy will uncompress the content sending it to the client. This happens because the LB might support different  version/option than what the client is requesting. Example LB speaks HTTP/1.1 to app server but the client speaks HTTP/1.0. Second example LB supports compression therefore app server's response is compressed but the client doesn't support compression.
You  should disable compression on the app servers and let the LB handle compression. You'll save the LB a couple of CPU cycles of uncompressing and recompressing the content.
Disclaimer. I have used other load balancers but not a F5.

A: The question really boils down to where you want the added overhead to handle the compression logic to run.  If your app servers are beefy put it there, otherwise the F5 should be able to handle it.  Regardless, this is something you will have to evaluate based on how much will get compressed and how much additional load that places on your systems.

A: BIG-IP does compression in hardware on most platforms (up to ~16Gbps).  If your servers do it in software, you could save server CPU resources by doing compression there.
BIG-IP System Hardware Product Datasheet
http://www.f5.com/pdf/products/big-ip-platforms-datasheet.pdf
BIG-IP does not de-compress response content unless you've configured a feature which requires parsing of the response content (like HTTP response payload rewriting or ASM web app security response parsing).
Aaron


text:
Q: D Templates: Sort a list of types Assume you have a type like the following:
struct Value(int v_)
{
  static const v = v_:
}

How would you sort a list of these types, assuming an interface something like this:
alias Sorted!(Value!(4), Value!(2), Value!(1), Value!(3)) SortedValues;

You may use D 2.x features if it makes for a better solution, but please state if you do so.
I'll post my solution in a day or so.  :)

A: Using D 1.0, have a QuickSort!
http://paste.dprogramming.com/dplgp5ic

A: By the way unless you have other reasons to do it there is no need to wrap the value in structs as tuples work just fine with values as well.
alias Sorted!(4, 2, 1, 3) SortedValues;

A: Here's my solution.  Note quite as cool as FeepingCreature's, but probably simpler to understand; it works by recursively inserting the first type into the rest of the list (after having sorting it).
module sort;

/*
 * Tango users substitute "tango.core.Tuple" for "std.typetuple" and "Tuple"
 * for "TypeTuple".
 */

import std.typetuple;

struct Val(string v_)
{
    static const v = v_;
}

template Sorted_impl(T)
{
    alias TypeTuple!(T) Sorted_impl;
}

template Sorted_impl(T, U, V...){

    static if( T.v < U.v )
        alias TypeTuple!(T, U, V) Sorted_impl;

    else
        alias TypeTuple!(U, Sorted_impl!(T, V)) Sorted_impl;
}

template Sorted(T)
{
    alias TypeTuple!(T) Sorted;
}

template Sorted(T, U...)
{
    alias Sorted_impl!(T, Sorted_impl!(U)) Sorted;
}

pragma(msg, Sorted!(Val!("a")).stringof);

pragma(msg, Sorted!(Val!("b"), Val!("a")).stringof);

pragma(msg, Sorted!(
    Val!("d"), Val!("a"), Val!("b"), Val!("c")
).stringof);

static assert( false, "nothing to compile here, move along..." );