Q: Class to test if date is valid using Int input with boolean output, and how to test (java) I have an assignment for class in which I have to create a class (called FunWithCalendars) that takes in 3 int values (month, day, and year) and uses 1 boolean method (isValid) to check if the overall date is valid, which uses 3 other helper methods (isLeapYear, isValidMonth, isValidDay) to determine whether the day and month given are valid. I now want to test my file in Eclipse.
So far I've learned to test classes/methods with this code ( Im a newbie, so this is the only way I know):
public class driverFunWithCalendars {
    public static void main(String [] args ) {
        FunWithCalendars test = new FunWithCalendars () ;
        System.out.println( test.FunWithCalendars () );

However, Im not understanding how I'm supposed to test the boolean method for a true or false when I have to enter int values that aren't defined in the method. The error in the code above is at "new FunWithCalendars () ;" and "(test.funwithcalendars () );".
Here's my main code:
public class FunWithCalendars
{
    private int month, day, year;

    public FunWithCalendars( int m, int d, int y )
    {
        month = m;
        day = d;
        year = y;
    }

     public boolean isValid ( boolean isValidMonth, boolean isValidDay )
     {
         if ( isValidMonth && isValidDay )
         {
             return true;
         }
         else
         {
             return false;
         }

     }

     public boolean isLeapYear (int year)
     {

        if ( (year / 400) == 0 )
        {
            return true;
        }
        else if ( ((year / 4) == 0) && ((year/100) !=0))
        {
            return true;
        }
        else
        {
            return false;
        }
     }

     public boolean isValidMonth ( int month )
     {
        if ( month >= 1 && month <= 12 )
        {
            return true;
        }
        else
        {
            return false;
        }
     }

     public boolean isValidDay  ( int month, int day, int year, boolean isLeapYear )
     {
         if ( (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && ((day<=31) && (day>=1)) )
         {
             return true;
         }
         else if ( (month == 4 || month == 6 || month == 9 || month == 11) && ((day<=30) && (day>=1)) )
         {
             return true;
         }
         else if ( (month == 2) && ( isLeapYear = true) && ((day<=29) && (day>=1)) )
         {
             return true;
         }
         else if ( (month == 2) && ( isLeapYear = false) && ((day<=28) && (day>=1)) )
         {
             return true;
         }
         else
         {
             return false;
         }
     }

}

}
}

Basically, I just want to know how I can test my code with 3 int values ( a date, or month, day year) to see if the date is valid or not using my isValid method. I'm really sorry if my question is unclear, or the assignment in the way I explained is confusing but like I said Im a newbie to Java and to Stackoverflow questions and I have yet to understand Java to the point that I can ask more efficient and concise questions, but I really hope some of you can help me. Ill also attach a transript of my original assignment, which may be less confusing and helpful to you if you're trying to help me:
/*
The calendar we use today is the Gregorian Calendar, devised by Italian astronomer Aloysius Lilius and decreed by Pope Gregory XIII on February 24th, 1582. In the Gregorian Calendar, the average length of a year is exactly 365.2425 days. We can make that happen with some rather complex "leap year" rules:
If a year is divisible by 4, it's a leap year… unless it's divisible by 100, in which case it's not a leap year… unless it's divisible by 400, in which case it's a leap year.
Okay, that's confusing. Let's try again:
A year is a leap year if:
a. It's divisible by 400
b. It's divisible by 4 and it's not divisible by 100.
Based on those rules, 1512, 1600, and 2000 were leap years. 1514, 1700, and 1900 were not.
(And you thought leap year was just every four years! That was the case with Julius Caesar's calendar—which was wrong, because adding a 366th day every four years would give us an average year length of 365.25 days instead of the far more accurate 365.2425 days. 0.0075 days per year doesn't sound like a lot, but in the 1500s astronomers noticed that predictable events, such as the solstice and equinox, were "off" by about 10 days. Hence the new, improved calendar.)
In the Gregorian Calendar, the number of days per month are as follows:
Month              Name               Days
1                      January             31
2                      February           28 or 29
3                      March               31
4                      April                 30
5                      May                  31
6                      June                 30
7                      July                  31
8                      August              31
9                      September        30
10                     October            31
11                     November         30
12                     December         31
Based on the Gregorian Calendar's leap year rules, and the usual number of days per month, complete the class FunWithCalendars. You will need:
Three int field variables to keep track of the month, day, and year.
The constructor of FunWithCalendars, which will take in values for the month, day, and year, and assign them to field variables. (This is written for you, you may use the starter file FunWithCalendars.java ).
The method:
boolean isValid()
which will return a true or false. A true result means that the month and day are valid values for that year.
You will need three helper methods:
boolean isLeapYear()
which will return a true only if the year represents a leap year.
You also need:
boolean isValidMonth()
which will return a true only if the month field is between 1 and 12. And finally:
boolean isValidDay()
which will return a true only if that day exists in that month in the given year. Remember to check for a leap year when checking to see if 29 is valid in February!
Again, we expect a true from isValid() if and only if we get a true from isValidMonth() and from isValidDay(). (We will assume that all years are valid.)
Tests:
7/20/2010 is valid.
13/1/2009 is not valid. (13 is not a valid month.)
11/31/2009 is not valid. (That day does not exist in that month.)
2/29/2007 is not valid. (2007 was not a leap year.)
2/29/2000 is valid. (2000 was a leap year.)
*/
Thanks to anyone who can help!

A: Let’s take the first test as an example:

Tests:
7/20/2010 is valid.

So in your driver class/test class construct a FunWithCalendars object denoting July 20 2010. The constructor takes three arguments for this purpose. Next call its isValid method. I believe that the idea was that you shouldn’t need to pass the same arguments again. Your isValid method takes two boolean arguments. Instead I believe that it should take no arguments and itself call the two helper methods passing the values that are already inside the FunWithCalendars object. So before you can get your driver class to work, I believe you have to fix your design on this point.
Once you get the call to isValid() to work, store the return value into a variable. Compare it to the expected value (true in this case). If they are equal, print a statement that the test passed. If they are not equal, print a statement containing both the expected and the observed value.
Do similarly for the other tests. Don’t copy-paste the code, though. Instead wrap it in a method and call the method for each test case, passing as arguments the data needed for that particular test. Remember to include the expected result as an argument so the method can compare.
Edit:

… My confusion is in how to construct an object (in general, and also
specifically FunWithCalendars), how to call the isValid method and
have it not take any arguments, how to have the isValid method call
the two helper methods which pass the values that are in the
FunWIthCalendars object.

It’s basic stuff, and I don’t think Stack Overflow is a good place to teach basic stuff. Let’s give it a try, only please set your expectations low.
How to construct an object: You’re already doing this in your driver class using the new operator:
    FunWithCalendars test = new FunWithCalendars () ;

Only you need to pass the correct arguments to the constructor. Your constructor takes three int arguments, so it needs to be something like:
    FunWithCalendars test = new FunWithCalendars(7, 20, 2020);

How to call the isValid method and have it take no arguments, after the above line:
    boolean calculatedValidity = test.isValid();

This stores the value returned from isValid() (false or true) into a newly created boolean variable that I have named calculatedValidity. From there we may check whether it has the expected value, act depending on it and/or print it. The simplest thing is to print it, for example:
    System.out.println("Is 7/20/2020 valid? " + calculatedValidity);

Calling with no arguments requires that the method hasn’t got any parameters:
public boolean isValid ()
{

How to have isValid() call the two helper methods: You may simple write the method calls en lieu of mentioning the parameters that were there before. Again remember to pass the right arguments:
    if (isValidMonth(month) && isValidDay(month, day, year, isLeapYear(year)) )

In the method calls here I am using the instance variables (fields) of the FunWithCalendars object as arguments. This causes the method to use the numbers that we entered through the constructor and to use the three helper methods.
I have run your code with the above changes. My print statement printed the expected:

Is 7/20/2020 valid? true

PS I am on purpose not saying anything about possible bugs in your code. It’s a lot better for you to have your tests tell you whether there are any.


Q: I want to upload multiple files using Django I want to upload multiple files or a folder in form , The html form uploads the multiple files successfully but when it comes to django handling it is showing me night-mares in day light .
I have created my html form like this
<input type="file" name="file" multiple />

I have created a model like this
class Report(models.Model):
    name = models.CharField(max_length=60)
    report = models.CharField(max_length=10)
    task = models.CharField(max_length=60)
    date = models.DateField(null=True)
    start_time = models.TimeField()
    end_time = models.TimeField()
    no_of_hours = models.CharField(max_length=20)
    team_lead = models.CharField(max_length=30)
    today_progress = models.CharField(max_length = 1000)
    file_input = models.FileField(upload_to='documents/')
    concern = models.CharField(max_length=1000)
    next_plan = models.CharField(max_length=1000)
    next_plan_file = models.FileField(upload_to='next/')

And views.py like this

def save(request):
    report_object = Report()
    report_object.name = request.POST["name"]
    report_object.report = request.POST["report"]
    report_object.task = request.POST["task"]
    report_object.date = request.POST["date"]
    report_object.start_time = request.POST["start_time"]
    report_object.end_time = request.POST["end_time"]
    report_object.no_of_hours = request.POST["no_of_hours"]
    report_object.team_lead = request.POST["team_lead"]
    report_object.today_progress = request.POST["today_progress"]
    report_object.file_input = request.FILES.["file_input"]
    report_object.concern = request.POST["concern"]
    report_object.next_plan = request.POST["next_plan"]
    report_object.next_plan_file = request.FILES.["upload_next"]
    report_object.save()
    return redirect('/')

I pass the file into the model i have created but only the last file gets inserted and shown in Admin Panel
Now I get only last file (if I select 3 files then get 3rd file). How to get all files or folder ?
And even want to show in Django Admin Panel

A: Try this and check out this works!!
Replace
file=request.FILES.get('file')

with
files = request.FILES.getlist('file')

you have to loop through each element in your view
if form.is_valid():
    name = form.cleaned_data['name']
    for f in files:
        File.objects.create(name=name, file=f)
    return HttpResponse('OK')

Here name is your model field and saving all uploaded files in name field


Q: Working with images in C++ or C The first thing is that I am a beginner.  Okay?
I've read related answers and questions, but please help me with this problem:
How can I open an JPEG image file in C++, convert it to a grayscale image, get its histogram, resize it to a smaller image, crop a particular area of it, or show a particular area of it?
For these tasks, is C or C++ faster in general?
What libraries are simplest and fastest?  The running time is very important.
Thanks.

A: There are many good libraries for working with images in C and C++, none of which is clearly superior to all others.  OpenCVwiki, project page has great support for some of these tasks, while ImageMagickwiki, project page is good at others.  The JPEG group has its own implementation of JPEG processing functions as well.  These are probably good resources to start from; the API documentation can guide you more specifically on how to use each of these.
As for whether C or C++ libraries are bound to be faster, there's no clear winner between the two.  After all, you can always compile a C library in C++.  That said, C++ libraries tend to be a bit trickier to pick up because of the language complexity, but much easier to use once you've gotten a good feel for the language.  (I am a bit biased toward C++, so be sure to consider the source).  I'd recommend going with whatever language you find easier for the task; neither is a bad choice here, especially if performance is important.
Best of luck with your project!

A: well for basic image manipulations you could also try Qt's QImage class (and other). This gives you basic functionality for opening, scaling, resizing, cropping, pixel manipulations and other tasks.
Otherwise you could as already said use ImageMagick or OpenCV. OpenCV provides a lot of examples with it for many image manipulation/image recognition tasks...
Hope it helps...

A: here is an example using magick library.
program which reads an image, crops it, and writes it to a new file (the exception handling is optional but strongly recommended):
#include <Magick++.h>
#include <iostream>
using namespace std;
using namespace Magick;
int main(int argc,char **argv)
{
  // Construct the image object. Seperating image construction from the
  // the read operation ensures that a failure to read the image file
  // doesn't render the image object useless.
  Image image;

  try {
    // Read a file into image object
    image.read( "girl.jpeg" );

    // Crop the image to specified size (width, height, xOffset, yOffset)
    image.crop( Geometry(100,100, 100, 100) );

    // Write the image to a file
    image.write( "x.jpeg" );
  }
  catch( Exception &error_ )
    {
      cout << "Caught exception: " << error_.what() << endl;
      return 1;
    }
  return 0;
}

check many more examples here

A: libgd is about the easiest, lightest-weight solution.
gdImageCreateFromJpeg
gdImageCopyMergeGray
gdImageCopyResized

Oh, and it's all C.

A: If running time is really important thing then you must consider image processing library which offloads processing job to GPU chip, such as:

*

*Core Image (Osx)

*OpenVIDIA (Windows)

*GpuCV (Windows, Linux)


Q: Android: Disable texture filtering/interpolation on AnimationDrawable I have a frame-by-frame AnimationDrawable that I'd like to scale without Android's default, blurry interpolation.  (It's pixel art and looks better with nearest-neighbor.)  Can I set a flag?  Override onDraw?  Anything to tell the GPU not to use texture filtering?
Do I need to scale up each individual bitmap in the animation instead?  This seems like a waste of CPU and texture memory.
Code example:
// Use a view background to display the animation.
View animatedView = new View(this);
animatedView.setBackgroundResource(R.anim.pixel_animation);
AnimationDrawable animation = (AnimationDrawable)animatedView.getBackground();
animation.start();

// Use LayoutParams to scale the animation 4x.
final int SCALE_FACTOR = 4;
int width = animation.getIntrinsicWidth() * SCALE_FACTOR;
int height = animation.getIntrinsicHeight() * SCALE_FACTOR;
container.addView(animatedView, width, height);

A: This seems to work, as long as you can assume that all the frames in an AnimationDrawable are BitmapDrawables:
for(int i = 0; i < animation.getNumberOfFrames(); i++) {
    Drawable frame = animation.getFrame(i);
    if(frame instanceof BitmapDrawable) {
        BitmapDrawable frameBitmap = (BitmapDrawable)frame;
        frameBitmap.getPaint().setFilterBitmap(false);
    }
}

A: If you know the texture ID of the texture that's being rendered, at any time after it's created and before it's rendered you should be able to do:
glBindTexture(GL_TEXTURE_2D, textureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

If this is the only texture being rendered then you can do that anywhere from your render thread and it will get picked up without having to explicitly glBindTexture().


Q: Use the pumping lemma to show that the following languages are not regular languages L = {anbm | n = 2m} Use the pumping lemma to show that the following languages are not regular languages L = {an bm | n = 2m}

A: Choose a string a^2p b^p. The pumping lemma says we can write this as w = uvx such that |uv| <= p, |v| < 0 and for all natural numbers n, u(v^n)x is also a string in the language. Because |uv| <= p, the substring uv of w consists entirely of instances of the symbol a. Pumping up or down by choosing a value for n other than one guarantees that the number of a's in the resulting string will change, while the number of b's stays the same. Since the number of a's is twice the number of b's only when n = 1, this is a contradiction. Therefore, the language cannot be regular.

A: L={anbm|n=2m} Assume that L is regular Language Let the pumping length be p L={a2mbm} Since |s|=3m > m (total string length) take a string s S= aaaaa...aabbb....bbb (a2mbm times taken) Then, u = am-1 ; v= a ; w= ambm. && |uv|<=m Now If i=2 then S= am-1 a2 ambm = a2m-1bm Since here we are getting an extra a in the string S which is no belong to the given language a2mbm our assumption is wrong Therefore it is not a regular Language


Q: Declaring constants with the nameof() the constant as the value Scenario
I have a class for declaring string constants used around a program:
public static class StringConstants
{
    public const string ConstantA = "ConstantA";
    public const string ConstantB = "ConstantB";
    // ...
}

Essentially, it doesn't matter what the actual value of the constant is, as it used when assigning and consuming. It is just for checking against.
The constant names will be fairly self-explanatory, but I want to try and avoid using the same string values more than once.

What I would like to do
I know that nameof() is evaluated at compile-time, so it is entirely possible to assign the const string's value to the nameof() a member.
In order to save writing these magic strings out, I have thought about using the nameof() the constant itself.
Like so:
public static class StringConstants
{
    public const string ConstantA = nameof(ConstantA);
    public const string ConstantB = nameof(ConstantB);
    // ...
}

Question...
I guess there is no real benefit of using the nameof(), other than for refactoring?
Are there any implications to using nameof() when assigning constants?
Should I stick to just using a hard-coded string?

A: Whilst I think the use of nameof is clever, I can think of a few scenarios where it might cause you a problem (not all of these might apply to you):
1/ There are some string values for which you can't have the name and value the same. Any string value starting with a number for example can't be used as a name of a constant. So you will have exceptions where you can't use nameof.
2/ Depending how these values are used (for example if they are names of values stored in a database, in an xml file, etc), then you aren't at liberty to change the values - which is fine until you come to refactor. If you want to rename a constant to make it more readable (or correct the previous developer's spelling mistake) then you can't change it if you are using nameof.
3/ For other developers who have to maintain your code, consider which is more readable:
public const string ConstantA = nameof(ContantA);

or
public const string ConstantA = "ConstantA";

Personally I think it is the latter. In my opinion if you go the nameof route then that might give other developers cause to stop and wonder why you did it that way. It is also implying that it is the name of the constant that is important, whereas if your usage scenario is anything like mine then it is the value that is important and the name is for convenience.
If you accept that there are times when you couldn't use nameof, then is there any real benefit in using it at all? I don't see any disadvantages aside from the above. Personally I would advocate sticking to traditional hard coded string constants.
That all said, if your objective is to simply to ensure that you are not using the same string value more than once, then (because this will give you a compiler error if two names are the same) this would be a very effective solution.

A: I think nameof() has 2 advantages over a literal strings:
1.) When the name changes, you will get compiler errors unless you change all occurences. So this is less error-prone.
2.) When quickly trying to understand code you didn't write yourself, you can clearly distinguish which context the name comes from. Example:
ViewModel1.PropertyChanged += OnPropertyChanged; // add the event handler in line 50

...

void OnPropertyChanged(object sender, string propertyName) // event handler in line 600
{
    if (propertyName == nameof(ViewModel1.Color))
    {
         // no need to scroll up to line 50 in order to see
         // that we're dealing with ViewModel1's properties
        ...
    }
}

A: Using the nameof() operator with public constant strings is risky. As its name suggests, the value of a public constant should really be constant/permanent. If you have public constant declared with the nameof() and if you rename it later then you may break your client code using the constant. In his book Essential C# 4.0, Mark Michaelis points out: (Emphasis is mine)

public constants should be permanent because changing their value will
not necessarily take effect in the assemblies that use it. If an
assembly references constants from a different assembly, the value of
the constant is compiled directly into the referencing assembly.
Therefore, if the value in the referenced assembly is changed but the
referencing assembly is not recompiled, then the referencing assembly
will still use the original value, not the new value. Values that
could potentially change in the future should be specified as readonly
instead.


Q: Magento connect's order delivery date extension disable required dates I used Magento connects Order Delivery Date extension to allow the buyer to set the date, when they should receive the goods. Now i want to disable some dates on the calendar that shows at checkout page. Can i use general JQuery calendar date disable at this point? If i can not what is the way it should be done? Any helps would be appreciated.


Q: How to obtain list of devices and their parameters using HKLM\SYSTEM\CurrentControlSet\Enum? How to obtain the content and the main parameters of devices using registry section HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum?
Well, I need to scan registry tree, containing ..\Enum\{SomeID}\{OneMoreID}\{MyDearValue}, which should contain some description, i.e. "KINGSTON 100500TB Flash of God". And the main question is: how to obtain all of this string descriptions, using WinAPI and C++?

A: Use the Win32 Registry functions.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms724875(v=vs.85).aspx


Q: Linq to sql table dynamically with ExecuteQuery VB I am using VB Framework 4.0 and Linq to sql.
I want to choose dynamycally the name of table. I have used the library namedtable.dll and I have mapped all the tables of database and it's Ok.
My problem is when I try to execute executequery. Here my code.
Imports Microsoft.VisualBasic
Imports System.Data.Linq
Imports Prototype.NamedTable.Data
Imports Prototype.NamedTable.Utility

    Public Class tipos

        Private _conexion As String = "conexion"

        Public Sub New()

        End Sub

        ...........

        Public Function getConsulta(byval tableName as String) As IList(Of TIPOS)

            Dim context As New DataContext(_conexion)

            sql = " select COD, NAME from " & tableName

            Dim a = context.ExecuteQuery(Of TIPOS)(sql)

            Return sql.ToList

        End Function
    End Class

but I have an error: "El tipo 'TIPOS' debe declarar un constructor predeterminado (sin parámetros) para que pueda construirse durante la asignación." that in English is:
"The type 'Type TIPOS' must declare a default (parameterless) constructor in order to be constructed during mapping"
I have defined "TIPOS" in other file:
Public Interface TIPOS
    <Column(CanBeNull:=False)> Property COD Integer
    <Column(CanBeNull:=False)> Property NAME As String
End Interface

Public Class ITIPO : Implements TIPO
    Private _cod As Integer
    Private _name As String

    Public Property COD As Integer Implements TIPO.COD
        Get
            Return _cod
        End Get
        Set(ByVal value As Integer)
            _cod = value
        End Set
    End Property

    Public Property NAME As String Implements TIPO.NAME
        Get
            Return _name
        End Get
        Set(ByVal value As String)
            _name = value
        End Set
    End Property

End Class

I need help!
Sorry for my English.

A: The solution can be found on codeproject.com in article "Dynamic Table Mapping for LINQ-to-SQL." Below is a static class you can use. Please see the article for instructions on what you must do to use the 4 different generic methods.  Here is an invocation example:
public interface IResult
{
    [Column(IsPrimaryKey = true)]
    int Id { get; set; }

    [Column]
    string Name { get; set; }

    [Column]
    double Value { get; set; }
}

public void TestThis()
{
    var connectionString = "Data Source=.\SQLEXPRESS;Initial Catalog=YourDatabaseName;Integrated Security=True;Pooling=False";
    var context = new DataContext(connectionString);
    var table = context.GetTable<IResult>("YourTableName");
    var query = from r in table where r.Id == 108 select r;
    var list = query.ToList();
}

Class Code:
namespace Prototype.NamedTable
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;

/// <summary>
/// The utility.
/// </summary>
public static class Utility
{
    #region Constants and Fields

    /// <summary>
    /// The named types.
    /// </summary>
    private static readonly Dictionary<string, Type> NamedTypes = new Dictionary<string, Type>();

    /// <summary>
    /// The _assembly builder.
    /// </summary>
    private static AssemblyBuilder _assemblyBuilder;

    /// <summary>
    /// The _module builder.
    /// </summary>
    private static ModuleBuilder _moduleBuilder;

    #endregion

    #region Properties

    /// <summary>
    /// Gets or sets a value indicating whether Verbose.
    /// </summary>
    public static bool Verbose { get; set; }

    #endregion

    #region Public Methods

    /// <summary>
    /// The clear.
    /// </summary>
    public static void Clear()
    {
        _assemblyBuilder = null;
        NamedTypes.Clear();
    }

    /// <summary>
    /// Retrieve a table from the data context which implements ITable<TEntity> by T and use ITable<TBack>
    /// </summary>
    /// <typeparam name="TEntity">
    /// Entity Type
    /// </typeparam>
    /// <typeparam name="TBack">
    /// Backing Type
    /// </typeparam>
    /// <param name="context">
    /// Data Context
    /// </param>
    /// <returns>
    /// </returns>
    public static ATable<TEntity> GetTable<TEntity, TBack>(this DataContext context) where TEntity : class
        where TBack : class
    {
        // Create the backup table
        Table<TBack> refer = context.GetTable<TBack>();

        // Prepare the cloning method
        Delegate cloneFrom = CompileCloning(typeof(TEntity), typeof(TBack));

        // Construct the table wrapper
        return new ATable<TEntity>(refer, cloneFrom);
    }

    /// <summary>
    /// Retrieve a table from the data context which implements ITable<TEntity> uses specific backing table
    /// </summary>
    /// <typeparam name="TEntity">
    /// Entity Type
    /// </typeparam>
    /// <param name="context">
    /// Data context
    /// </param>
    /// <param name="name">
    /// Table name
    /// </param>
    /// <returns>
    /// </returns>
    public static ATable<TEntity> GetTable<TEntity>(this DataContext context, string name) where TEntity : class
    {
        // Create/Retrieve a type definition for the table using the TEntity type
        Type type = DefineEntityType(typeof(TEntity), name);

        // Create the backup table using the new type
        ITable refer = context.GetTable(type);

        // Prepare the cloning method
        Delegate cloneFrom = CompileCloning(typeof(TEntity), type);

        // Construct the table wrapper
        return new ATable<TEntity>(refer, cloneFrom);
    }

    /*
    /// <summary>
    /// The log.
    /// </summary>
    /// <param name="format">
    /// The format.
    /// </param>
    /// <param name="args">
    /// The args.
    /// </param>
    public static void Log(string format, params object[] args)
    {
        if (!Verbose)
        {
            return;
        }

        Console.Write("*** ");

        if ((args == null) || (args.Length == 0))
        {
            Console.WriteLine(format);
        }
        else
        {
            Console.WriteLine(format, args);
        }
    }*/

    #endregion

    #region Methods

    /// <summary>
    /// Clone an attribute
    /// </summary>
    /// <param name="attr">
    /// </param>
    /// <returns>
    /// </returns>
    private static CustomAttributeBuilder CloneColumn(object attr)
    {
        Type source = attr.GetType();
        Type target = typeof(ColumnAttribute);

        var props = new List<PropertyInfo>();
        var values = new List<object>();

        // Extract properties and their values
        foreach (PropertyInfo prop in source.GetProperties())
        {
            if (!prop.CanRead || !prop.CanWrite)
            {
                continue;
            }

            props.Add(target.GetProperty(prop.Name));
            values.Add(prop.GetValue(attr, null));
        }

        // Create a new attribute using the properties and values
        return new CustomAttributeBuilder(
            target.GetConstructor(Type.EmptyTypes), new object[0], props.ToArray(), values.ToArray());
    }

    /// <summary>
    /// Make a delegate that copy content from "source" to "dest"
    /// </summary>
    /// <param name="source">
    /// Source Type
    /// </param>
    /// <param name="dest">
    /// Destination Type
    /// </param>
    /// <returns>
    /// Executable delegate
    /// </returns>
    private static Delegate CompileCloning(Type source, Type dest)
    {
        // Input parameter
        ParameterExpression input = Expression.Parameter(source);

        // For every property, create a member binding
        List<MemberBinding> binds =
            source.GetProperties().Select(
                prop =>
                Expression.Bind(
                    dest.GetProperty(
                        prop.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly),
                    Expression.MakeMemberAccess(input, prop))).Cast<MemberBinding>().ToList();

        // Expression of creating the new object
        MemberInitExpression body = Expression.MemberInit(
            Expression.New(dest.GetConstructor(Type.EmptyTypes)), binds);

        // The final lambda
        LambdaExpression lambda = Expression.Lambda(body, input);

        // MJE
        //Log("{0}", lambda.ToString());

        // Return the executable delegate
        return lambda.Compile();
    }

    /// <summary>
    /// Create a class based on the template interface
    /// </summary>
    /// <param name="template">
    /// </param>
    /// <param name="name">
    /// </param>
    /// <returns>
    /// </returns>
    private static Type DefineEntityType(Type template, string name)
    {
        // Prepare the builders if not done
        if (_assemblyBuilder == null)
        {
            _assemblyBuilder =
                AppDomain.CurrentDomain.DefineDynamicAssembly(
                    new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.Run);

            _moduleBuilder = _assemblyBuilder.DefineDynamicModule("Types");
        }

        // Check if there is already a type created for that table
        if (NamedTypes.ContainsKey(name))
        {
            return NamedTypes[name];
        }

        // Create the new type
        TypeBuilder tbuilder = null;
        if (template.IsInterface)
        {
            tbuilder = DefineInterfaceChild(name, template);
        }
        else
        {
            tbuilder = DefineOverriddenChild(name, template);
        }

        Type final = tbuilder.CreateType();

        NamedTypes[name] = final;

        return final;
    }

    /// <summary>
    /// The define interface child.
    /// </summary>
    /// <param name="name">
    /// The name.
    /// </param>
    /// <param name="template">
    /// The template.
    /// </param>
    /// <returns>
    /// </returns>
    private static TypeBuilder DefineInterfaceChild(string name, Type template)
    {
        TypeBuilder tbuilder = _moduleBuilder.DefineType(
            name, TypeAttributes.Public, typeof(Object), new[] { template });

        // Default constructor
        tbuilder.DefineDefaultConstructor(MethodAttributes.Public);

        // Attach Table attribute
        var abuilder = new CustomAttributeBuilder(
            typeof(TableAttribute).GetConstructor(Type.EmptyTypes),
            new object[0],
            new[] { typeof(TableAttribute).GetProperty("Name") },
            new object[] { name });
        tbuilder.SetCustomAttribute(abuilder);

        List<PropertyInfo> properties = template.GetProperties().ToList(); // May require sorting

        // Implement all properties));
        foreach (PropertyInfo prop in properties)
        {
            // Define backing field
            FieldBuilder fbuilder = tbuilder.DefineField(
                "_" + prop.Name, prop.PropertyType, FieldAttributes.Private);

            // Define get method
            MethodBuilder pgbuilder = tbuilder.DefineMethod(
                "get_" + prop.Name,
                MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
                | MethodAttributes.Virtual | MethodAttributes.Final,
                prop.PropertyType,
                Type.EmptyTypes);

            // Define get method body { return _field; }
            ILGenerator ilg = pgbuilder.GetILGenerator();
            ilg.Emit(OpCodes.Ldarg_0);
            ilg.Emit(OpCodes.Ldfld, fbuilder);
            ilg.Emit(OpCodes.Ret);

            // Define set method
            MethodBuilder psbuilder = tbuilder.DefineMethod(
                "set_" + prop.Name,
                MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
                | MethodAttributes.Virtual | MethodAttributes.Final,
                null,
                new[] { prop.PropertyType });

            // Define set method body { _field = value; }
            ILGenerator ils = psbuilder.GetILGenerator();
            ils.Emit(OpCodes.Ldarg_0);
            ils.Emit(OpCodes.Ldarg_1);
            ils.Emit(OpCodes.Stfld, fbuilder);
            ils.Emit(OpCodes.Ret);

            // Define the property
            PropertyBuilder pbuilder = tbuilder.DefineProperty(
                prop.Name, PropertyAttributes.None, CallingConventions.Standard, prop.PropertyType, null);

            // Set get/set method
            pbuilder.SetGetMethod(pgbuilder);
            pbuilder.SetSetMethod(psbuilder);

            // Attach Column attribute
            foreach (object attr in prop.GetCustomAttributes(false))
            {
                if (attr is ColumnAttribute || attr is AlterColumnAttribute)
                {
                    // MJE
                    //Log("Create column attribute for {0}", prop.Name);
                    pbuilder.SetCustomAttribute(CloneColumn(attr));
                    break;
                }
            }
        }

        return tbuilder;
    }

    /// <summary>
    /// The define overridden child.
    /// </summary>
    /// <param name="name">
    /// The name.
    /// </param>
    /// <param name="template">
    /// The template.
    /// </param>
    /// <returns>
    /// </returns>
    private static TypeBuilder DefineOverriddenChild(string name, Type template)
    {
        TypeBuilder tbuilder = _moduleBuilder.DefineType(name, TypeAttributes.Public, template);

        // Default constructor
        tbuilder.DefineDefaultConstructor(MethodAttributes.Public);

        // Attach Table attribute
        var abuilder = new CustomAttributeBuilder(
            typeof(TableAttribute).GetConstructor(Type.EmptyTypes),
            new object[0],
            new[] { typeof(TableAttribute).GetProperty("Name") },
            new object[] { name });
        tbuilder.SetCustomAttribute(abuilder);

        List<PropertyInfo> properties = template.GetProperties().ToList(); // May require sorting

        // Implement all properties));
        foreach (PropertyInfo prop in properties)
        {
            // Define get method
            MethodBuilder pgbuilder = tbuilder.DefineMethod(
                "get_" + prop.Name,
                MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
                | MethodAttributes.Virtual | MethodAttributes.Final,
                prop.PropertyType,
                Type.EmptyTypes);

            // Define get method body { return _field; }
            ILGenerator ilg = pgbuilder.GetILGenerator();
            ilg.Emit(OpCodes.Ldarg_0);
            ilg.Emit(OpCodes.Call, template.GetMethod("get_" + prop.Name));
            ilg.Emit(OpCodes.Ret);

            // Define set method
            MethodBuilder psbuilder = tbuilder.DefineMethod(
                "set_" + prop.Name,
                MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig
                | MethodAttributes.Virtual | MethodAttributes.Final,
                null,
                new[] { prop.PropertyType });

            // Define set method body { _field = value; }
            ILGenerator ils = psbuilder.GetILGenerator();
            ils.Emit(OpCodes.Ldarg_0);
            ils.Emit(OpCodes.Ldarg_1);
            ils.Emit(OpCodes.Call, template.GetMethod("set_" + prop.Name));
            ils.Emit(OpCodes.Ret);

            // Define the property
            PropertyBuilder pbuilder = tbuilder.DefineProperty(
                prop.Name, PropertyAttributes.None, CallingConventions.Standard, prop.PropertyType, null);

            // Set get/set method
            pbuilder.SetGetMethod(pgbuilder);
            pbuilder.SetSetMethod(psbuilder);

            // Attach Column attribute
            foreach (object attr in prop.GetCustomAttributes(false))
            {
                if (attr is ColumnAttribute || attr is AlterColumnAttribute)
                {
                    // MJE
                    //Log("Create column attribute for {0}", prop.Name);
                    pbuilder.SetCustomAttribute(CloneColumn(attr));
                    break;
                }
            }
        }

        return tbuilder;
    }

    #endregion

    /// <summary>
    /// A table wrapper implements ITable<TEntity> backed by other ITable object
    /// </summary>
    /// <typeparam name="TEntity">
    /// </typeparam>
    public class ATable<TEntity> : ITable<TEntity>
        where TEntity : class
    {
        #region Constants and Fields

        /// <summary>
        /// Cloning method
        /// </summary>
        private readonly Delegate _clone;

        /// <summary>
        /// Backing table
        /// </summary>
        private readonly ITable _internal;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ATable{TEntity}"/> class.
        /// Construct from backing table
        /// </summary>
        /// <param name="inter">
        /// </param>
        /// <param name="from">
        /// </param>
        public ATable(ITable inter, Delegate from)
        {
            this._internal = inter;
            this._clone = from;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets ElementType.
        /// </summary>
        public Type ElementType
        {
            get
            {
                // Use the backing table element
                return this._internal.ElementType;
            }
        }

        /// <summary>
        /// Gets Expression.
        /// </summary>
        public Expression Expression
        {
            get
            {
                // Use the backing table expression
                return this._internal.Expression;
            }
        }

        /// <summary>
        /// Gets Provider.
        /// </summary>
        public IQueryProvider Provider
        {
            get
            {
                // Use the backing table provider
                return this._internal.Provider;
            }
        }

        #endregion

        #region Implemented Interfaces

        #region IEnumerable

        /// <summary>
        /// The get enumerator.
        /// </summary>
        /// <returns>
        /// </returns>
        /// <exception cref="NotImplementedException">
        /// </exception>
        IEnumerator IEnumerable.GetEnumerator()
        {
            throw new NotImplementedException();
        }

        #endregion

        #region IEnumerable<TEntity>

        /// <summary>
        /// The get enumerator.
        /// </summary>
        /// <returns>
        /// </returns>
        /// <exception cref="NotImplementedException">
        /// </exception>
        public IEnumerator<TEntity> GetEnumerator()
        {
            throw new NotImplementedException();
        }

        #endregion

        #region ITable<TEntity>

        /// <summary>
        /// The attach.
        /// </summary>
        /// <param name="entity">
        /// The entity.
        /// </param>
        /// <exception cref="NotImplementedException">
        /// </exception>
        public void Attach(TEntity entity)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// The delete on submit.
        /// </summary>
        /// <param name="entity">
        /// The entity.
        /// </param>
        public void DeleteOnSubmit(TEntity entity)
        {
            // Directly invoke the backing table
            this._internal.DeleteOnSubmit(entity);
        }

        /// <summary>
        /// The insert on submit.
        /// </summary>
        /// <param name="entity">
        /// The entity.
        /// </param>
        public void InsertOnSubmit(TEntity entity)
        {
            // Input entity must be changed to backing type
            object v = this._clone.DynamicInvoke(entity);

            // Invoke the backing table
            this._internal.InsertOnSubmit(v);
        }

        #endregion

        #endregion
    }

    /// <summary>
    /// The alter column attribute.
    /// </summary>
    public class AlterColumnAttribute : Attribute
    {
        #region Constants and Fields

        /// <summary>
        /// The _can be null.
        /// </summary>
        private bool _canBeNull = true;

        /// <summary>
        /// The _update check.
        /// </summary>
        private UpdateCheck _updateCheck = UpdateCheck.Always;

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets AutoSync.
        /// </summary>
        public AutoSync AutoSync { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether CanBeNull.
        /// </summary>
        public bool CanBeNull
        {
            get
            {
                return this._canBeNull;
            }

            set
            {
                this._canBeNull = value;
            }
        }

        /// <summary>
        /// Gets or sets DbType.
        /// </summary>
        public string DbType { get; set; }

        /// <summary>
        /// Gets or sets Expression.
        /// </summary>
        public string Expression { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether IsDbGenerated.
        /// </summary>
        public bool IsDbGenerated { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether IsDiscriminator.
        /// </summary>
        public bool IsDiscriminator { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether IsPrimaryKey.
        /// </summary>
        public bool IsPrimaryKey { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether IsVersion.
        /// </summary>
        public bool IsVersion { get; set; }

        /// <summary>
        /// Gets or sets UpdateCheck.
        /// </summary>
        public UpdateCheck UpdateCheck
        {
            get
            {
                return this._updateCheck;
            }

            set
            {
                this._updateCheck = value;
            }
        }

        #endregion
    }
}
}

A: Linq-to-Sql cannot materialize interfaces. It needs a class specification to know what instances it should create from a query. The exception message is elusive, to say the least. I don't know why it isn't more to the point.
Note that the class you want to materialize must have been mapped, or: it must be in the dbml. I say this because your ITIPO class is not partial, which makes me wonder how you can make it implement an interface (well, maybe you just slimmed down the code).
Side note: don't use all capitals for class names, and prefix an interface specification with "I", not a class.


Q: android kotlin shared preferences unresolved reference getSharedPreferences error I am learning Kotlin by trying to build a small app that find and and remember last connected BLE device. To recognize the last connected device I decide to save its MAC address using shared preferences (is that the best way to do that is also a question). I use a tutorial online and it worked well (I didn't remember the page) but today when I open the project to continue the job it gives me error - unresolved reference getSharedPreferences. My question is what is the problem - I get lost :) Here is the class where I have the error row 23.
import android.content.Context
import android.content.SharedPreferences
interface PreferencesFunctions {
fun setDeviceMAC(deviceMAC: String)
fun getDeviceMAC(): String
fun setLastConnectionTime(lastConnectionTime: String)
fun getLastConnectionTime(): String
fun clearPrefs()

}
class PreferenceManager(context: ScanResultAdapter.ViewHolder) : PreferencesFunctions{
private val PREFS_NAME = "SharedPreferences"
private var preferences: SharedPreferences

init {
    preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
}

override fun setDeviceMAC(deviceMAC: String) {
    preferences[DEVICE_MAC] = deviceMAC
}

override fun getDeviceMAC(): String {
    return preferences[DEVICE_MAC] ?: ""
}

override fun setLastConnectionTime(lastConnectionTime: String) {
    preferences[LAST_CONNECTION_TIME] = lastConnectionTime
}

override fun getLastConnectionTime(): String {
    return preferences[LAST_CONNECTION_TIME] ?: ""
}

override fun clearPrefs() {
    preferences.edit().clear().apply()
}

companion object{

    const val DEVICE_MAC = "yyyyyyy"
    const val LAST_CONNECTION_TIME = "zzzzzzz"

}

}

A: Your arguement context is not a acitivity or fragment, and you need those two to call getSharedPreferences method.
class PreferenceManager(context: Context) : PreferencesFunctions{


Q: MvvmCross throwing InvalidStackFrameException I am using MvvmCross to develop an ios app. Everything worked fine until suddenly I got the following exception:
Mono.Debugger.Soft.InvalidStackFrameException: The requested operation cannot be completed because the specified stack frame is no longer valid.
  at Mono.Debugger.Soft.VirtualMachine.ErrorHandler (System.Object sender, Mono.Debugger.Soft.ErrorHandlerEventArgs args) [0x00076] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/VirtualMachine.cs:301
  at Mono.Debugger.Soft.Connection.SendReceive (CommandSet command_set, Int32 command, Mono.Debugger.Soft.PacketWriter packet) [0x000f9] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs:1448
  at Mono.Debugger.Soft.Connection.StackFrame_GetValues (Int64 thread_id, Int64 id, System.Int32[] pos) [0x00026] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs:2225
  at Mono.Debugger.Soft.StackFrame.GetValue (Mono.Debugger.Soft.LocalVariable var) [0x0005f] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/StackFrame.cs:122
  at Mono.Debugging.Soft.VariableValueReference.get_Value () [0x0001a] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugging.Soft/VariableValueReference.cs:68
  at Mono.Debugging.Evaluation.ValueReference.OnCreateObjectValue (Mono.Debugging.Client.EvaluationOptions options) [0x00033] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugging/Mono.Debugging.Evaluation/ValueReference.cs:138
  at Mono.Debugging.Evaluation.ValueReference.CreateObjectValue (Mono.Debugging.Client.EvaluationOptions options) [0x00059] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugging/Mono.Debugging.Evaluation/ValueReference.cs:106 Mono.Debugger.Soft.InvalidStackFrameException: The requested operation cannot be completed because the specified stack frame is no longer valid.
  at Mono.Debugger.Soft.VirtualMachine.ErrorHandler (System.Object sender, Mono.Debugger.Soft.ErrorHandlerEventArgs args) [0x00076] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/VirtualMachine.cs:301
  at Mono.Debugger.Soft.Connection.SendReceive (CommandSet command_set, Int32 command, Mono.Debugger.Soft.PacketWriter packet) [0x000f9] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs:1448
  at Mono.Debugger.Soft.Connection.StackFrame_GetValues (Int64 thread_id, Int64 id, System.Int32[] pos) [0x00026] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/Connection.cs:2225
  at Mono.Debugger.Soft.StackFrame.GetValue (Mono.Debugger.Soft.LocalVariable var) [0x0005f] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/StackFrame.cs:122
  at Mono.Debugging.Soft.VariableValueReference.get_Value () [0x0001a] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugging.Soft/VariableValueReference.cs:68
  at Mono.Debugging.Evaluation.ValueReference.OnCreateObjectValue (Mono.Debugging.Client.EvaluationOptions options) [0x00033] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugging/Mono.Debugging.Evaluation/ValueReference.cs:138
  at Mono.Debugging.Evaluation.ValueReference.CreateObjectValue (Mono.Debugging.Client.EvaluationOptions options) [0x00059] in /Users/builder/data/lanes/monodevelop-lion-license-sync/c5f82958/source/monodevelop/main/external/debugger-libs/Mono.Debugging/Mono.Debugging.Evaluation/ValueReference.cs:106

It is important to say that this only happens on the device, everything works perfectly on the simulator...
I have fiddled with the code to come to a conclusion once I removed the following code everything worked:
var source = new MvxSimpleTableViewSource (MainTable, RecomendationTemplate.Key, RecomendationTemplate.Key);
            MainTable.Source = source;
            var set = this.CreateBindingSet<MainPage, MainPageViewModel> ();
            set.Bind (source).To (vm => vm.Recomendations);
            set.Apply ();

After that I have tried to use a difference cell template. I started with an empty one and it worked. but once I added the DelayBind mehtod I kept on getting the following exception... I have no idea how to move forward from here.


Q: Sql Server Stored Procedure not executing from MVC I am trying to execute a stored procedure in my Sql Server Database from an Asp.Net MVC project. I have set it up in a way that I can use it for testing purposes, which is why the variable "procedureTest" is a constant value (I know that "2044" is an existing record in my database). I will change this once I accomplish a successful run. Also, I know that my stored procedure works because I have executed it in Sql Server Management Studio successfully. The procedure has the task of adding ID from one table to another, but I have yet to see it appear in this table. I am not receiving an error in my catch block so I am kind of lost at the moment. I could definitely use your help.
try
{
    using (var connection = new SqlConnection(connectionString))
    {
        connection.Open();

        int procedureTest = 2044;

        var command = new SqlCommand("SELECT ID FROM Images WHERE ID = @id", connection);
        var paramDate = new SqlParameter("@id", procedureTest);
        command.Parameters.Add(paramDate);
        var reader = command.ExecuteReader();

        while (reader.Read())
        {
            var storedProcCommand = new SqlCommand("EXEC addToNotificationTable @ID", connection);
            var paramId = new SqlParameter("@ID", reader.GetInt32(0));
            storedProcCommand.Parameters.Add(paramId);
            command.ExecuteNonQuery();
        }
    }
}
catch (Exception e)
{
    string exceptionCause = String.Format("An error occurred: '{0}'", e);
    System.IO.File.WriteAllText(@"C:\Users\Nathan\Documents\Visual Studio 2013\Projects\MVCImageUpload\uploads\exception.txt", exceptionCause);
}

Stored Procedure:
CREATE PROCEDURE addToNotificationTable @ID int
AS
Insert NotificationTable (ID)
SELECT ID
FROM Images
Where ID = @ID

A: Change you code like this
while (reader.Read())
        {
            var storedProcCommand = new SqlCommand("EXEC addToNotificationTable @ID", connection);
            var paramId = new SqlParameter("@ID", reader.GetInt32(0));
            storedProcCommand.Parameters.Add(paramId);
            storedProcCommand.ExecuteNonQuery();
        }

A: First of all, you missed to specify the command type. Also using EXEC in SqlCommand is not a proper way.
Please try with the below code
while (reader.Read())
        {
            using(SqlCommand storedProcCommand = new SqlCommand("addToNotificationTable", connection)) //Specify only the SP name
            {
                storedProcCommand.CommandType = CommandType.StoredProcedure; //Indicates that Command to be executed is a stored procedure no a query
                var paramId = new SqlParameter("@ID", reader.GetInt32(0));
                storedProcCommand.Parameters.Add(paramId);
                storedProcCommand.ExecuteNonQuery()
            }
        }

Since you are calling the sp inside a while loop, wrap the code in using() { } to automatically dispose the command object after each iteration


Q: How to insert special HTML-symbols with HAML When I'm saying:
%p= item.price + " dollars"

I'm getting

50&nbsp ;dollars

instead of having non-breakable space symbol.
How to insert this and another special symbols using HAML ?

A: How about
%p= item.price + " dollars".html_safe

A: This answer is for a slightly different question but I found this question searching for it...
If you have a submit tag %input{ :type => "submit", :value => " dollars", :name => "very_contrived" } even if you throw an html_safe on the :value it will not evaluate the html.
The solution is to use the rails helper... duh
= submit_tag " dollars".html_safe

this is pretty obvious but it tripped me up.  Legacy code + rails upgrade = this kind of stuff :P

A: Use != instead of =
See "Unescaping HTML" in the haml reference: http://haml.info/docs/yardoc/file.REFERENCE.html#unescaping_html

A: The interpolation option:
%p= "#{item.price} dollars".html_safe

A: I tried using html_safe in different ways, but none worked. Using \xa0 as suggested by ngn didn't work, either, but it got me to try the Unicode escape of the non-breaking space, which did work:
"FOO\u00a0BAR"

and .html_safe isn't even needed (unless something else in the string needs that, of course).
The Ruby Programming Language, first edition, says: "In Ruby 1.9, double-quoted strings can include arbitrary Unicode escape characters with \u escapes.  In its simplest form, \u is followed by exactly four hexadecimal digits ..."

A: You could use \xa0 in the string instead of  .  0xa0 is the ASCII code of the non-breaking space.

A: I prefer using the character itself with the escaped HTML method with most symbols other than the whitespace characters. That way i don't have to remember all the html codes. As for the whitespace characters i prefer to use CSS, this is a much cleaner way.
%p&= "#{item.price} $%&#*@"


Q: Trying to replace values in a data frame with other values I have a list of vectors, L1, and a data frame, df2. I want to take values from df2 and replace the values of L1 with these. For example, when ABCC10 of L1 says "TCGA_DD_A1EG", I want to replace this with the value, 2.193205, from row 1 (ABCC10), column 3 (TCGA.DD.A1EG). I want to do this with every value.
L1 looks like this:
$ABCC10
[1] "TCGA_DD_A1EG" "TCGA_FV_A3R2" "TCGA_FV_A3I0" "TCGA_DD_A1EH" "TCGA_FV_A23B"

$ACBD6
[1] "TCGA_DD_A1EH" "TCGA_DD_A3A8" "TCGA_ES_A2HT" "TCGA_DD_A1EG" "TCGA_DD_A1EB"

df2 looks like this:
       TCGA.BC.A10Q TCGA.DD.A1EB TCGA.DD.A1EG TCGA.DD.A1EH TCGA.DD.A1EI TCGA.DD.A3A6 TCGA.DD.A3A8
ABCC10     2.540764    0.4372165     2.193205     3.265756    0.6060301     2.927072    0.6799514
ACBD6      1.112432    0.4611697     1.274129     1.802985   -0.0475743     1.071064    0.4336301
       TCGA.ES.A2HT TCGA.FV.A23B TCGA.FV.A3I0 TCGA.FV.A3R2
ABCC10  -0.08129554    2.2963764     3.196518    0.8595943
ACBD6    1.76935812    0.3644397     1.392206    1.0282030

A: One approach could be like
df1 = list(ABCC10 = c("TCGA_DD_A1EG", "TCGA_FV_A3R2", "TCGA_FV_A3I0", "TCGA_DD_A1EH", "TCGA_FV_A23B"),
           ACBD6 = c("TCGA_DD_A1EH", "TCGA_DD_A3A8", "TCGA_ES_A2HT", "TCGA_DD_A1EG", "TCGA_DD_A1EB"))

df2 = data.frame(TCGA.BC.A10Q = c(2.540764, 1.112432),
                 TCGA.DD.A1EB = c(0.4372165, 0.4611697),
                 TCGA.DD.A1EG = c(2.193205, 1.274129),
                 TCGA.DD.A1EH = c(3.265756, 1.802985),
                 TCGA.DD.A1EI = c(0.6060301, -0.0475743),
                 TCGA.DD.A3A6 = c(2.927072, 1.071064),
                 TCGA.DD.A3A8 = c(0.6799514, 0.4336301),
                 TCGA.ES.A2HT = c(-0.08129554, 1.76935812),
                 TCGA.FV.A23B = c(2.2963764, 0.3644397),
                 TCGA.FV.A3I0 = c(3.196518, 1.392206),
                 TCGA.FV.A3R2 = c(0.8595943, 1.0282030),
                 row.names = c('ABCC10', 'ACBD6'))

for(i in 1:length(df1)){
  for(j in 1:length(df1[[1]])){
    df1[names(df1)[i]][[1]][j] = df2[names(df1)[i],gsub("_",".",df1[names(df1)[i]][[1]][j])]
  }
}

Output is:
$ABCC10
[1] "2.193205"  "0.8595943" "3.196518"  "3.265756"  "2.2963764"

$ACBD6
[1] "1.802985"   "0.4336301"  "1.76935812" "1.274129"   "0.4611697"

Hope this helps!

A: Maybe the following will do it.
First, make up some data, a list and a data.frame.
df1 <- list(A = letters[1:3], B = letters[5:7])

df2 <- data.frame(a = rnorm(2), b = rnorm(2), c = rnorm(2),
                  e = rnorm(2), f = rnorm(2), g = rnorm(2))
row.names(df2) <- c('A', 'B')

Now the code.
for(i in seq_along(df1)){
    x <- gsub("_", ".", df1[[i]])
    inx <- match(x, names(df2))
    df1[[i]] <- df2[i, inx]
}
df1

In my tests it did what you want. If it doesn't fit your real problem, just say so.


Q: Binding value in JSP page I have a XML value in controller and i'm passing that value to jsp page and binding as shown in the below code.
 <input type="hidden" id="thisField" name="inputName" value='${xml}'/>

It is binding the value as shown in the below.
 <input type="hidden" id="thisField" name="inputName" value='
    <?xml version="1.0" encoding="UTF-8"?>
    <Esign AuthMode="1" aspId="ASPRBLBMUMTEST043" ekycId="448988431774" ekycIdType="A" ekycMode="U" organizationFlag="N" preVerified="n" responseSigType="pkcs7" responseUrl="http://10.80.49.41" sc="Y" ts="2018-01-19T11:42:55" txn="UKC:eSign:6539:20180119114250963" ver="2.0">
        <Docs>
            <InputHash docInfo="Signing pdf" hashAlgorithm="SHA256" id="1">30e3ed7f512da50206b8720d52457309c87f4edfee85d08f937aef3f955fb7af</InputHash>
        </Docs>
        <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
            <SignedInfo>
                <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
                <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
                <Reference URI="">
                    <Transforms>
                        <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
                    </Transforms>
                    <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
                    <DigestValue>kQEB9r4dd5hhdaPxc4sjPMG3SGM=</DigestValue>
                </Reference>
            </SignedInfo>
            <SignatureValue>MSgEXK2+GpwnRBr3vLNncqc9FOY0oDhjlhfyihOjrUPFZAL8eBms6jXdhoWGlrypaF6hE70ZltDQbQTArrk/mfCmoVvna7yEJN9gDh6gAHbh9Zj4BEBdWhd85DKbAdtSy8zYTKIeIjhFBzOItUAhSN7lFrEFVrTLV5wO38hswD7LlaY4ZBSNMWbpHPx+Io6ukdP8b4n95dqoB9iiqKxg3nK0RslhLRcPoe4B2AsdoiZ42iY/tZ4disOzyOCyCdE8nRxipJbP9HZS3psCSCar3CPSigXiNk6fY7+bDEFbJrfoqhHBk1hasx2m0TbxZVeOIPSUPRYpekHCm0sm4RvZhA==</SignatureValue>
            <KeyInfo>
                <X509Data>
                    <X509SubjectName>CN=AAA Bank Test,OU=AAA Bank IT Dept,O=AAA Bank,L=Delhi,ST=Delhi,C=91</X509SubjectName>
                    <X509Certificate>MIIDkTCCAnmgAwIBAgIEZNl4CjANBgkqhkiG9w0BAQsFADB5MQswCQYDVQQGEwI5MTETMBEGA1UECBMKTWFoYXJhc3RyYTEPMA0GA1UEBxMGTXVtYmFpMREwDwYDVQQKEwhSYmwgQmFuazEZMBcGA1UECxMQUkJMIEJhbmsgSVQgRGVwdDEWMBQGA1UEAxMNUmJsIEJhbmsgVGVzdDAeFw0xNzAzMDIxNDA4MTBaFw0xODAyMjUxNDA4MTBaMHkxCzAJBgNVBAYTAjkxMRMwEQYDVQQIEwpNYWhhcmFzdHJhMQ8wDQYDVQQHEwZNdW1iYWkxETAPBgNVBAoTCFJibCBCYW5rMRkwFwYDVQQLExBSQkwgQmFuayBJVCBEZXB0MRYwFAYDVQQDEw1SYmwgQmFuayBUZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsjsF71lv96Y+2DbuSgk1U/Bp3P+jPpKp9GpwiVuIAf4SsBc1bqR3x4JSnY4COdUlq2IkHYSGnufGkPS6tH4edoFpZrSBAiTo1D0WQQ4KoRWBzn9xptMGsJBoV7dcSovjjD1HhUJGNnfoxjBh3AmIe8ZySWhuouEA8cRtFcHoWunpSB1FOJreIZ1P/ZnJ7C4gu+E1ccXjkFPqCGI9RcdUSE72K+ovtI/yWIUPwXdj3O/k30iX2owxUVFKnCmIDFnKDJ/b96RDzlIB9FiH5IVQm4mcU6HiQKqknDI3bPKlwvfFfB+YI69vjRQf3dvsca2nZQsYT3iSgkxBwoiugsD59QIDAQABoyEwHzAdBgNVHQ4EFgQUwFYILDVGVtIJgYveFqZ9YRrRq4AwDQYJKoZIhvcNAQELBQADggEBAKygyzVE1sOaBxuj4IjGDmo2y5UOhPOzklRocZbsqycEApcBn5m/dVauvewqw7An1vrkvjTYbTUCjUKghNW/MdtiWbKKRDy3fA8DyEACcYuK0PpaaXMTJFjIjKxXko6Rmmp6CKFcmERgetiwrFreMfFjvCv9H1fk7FSR87d/17l/LsmAndFIvpZTF3Ruz4lZsoL2qWtBF+wnVjFW+yqf6nXDqE/Swxhiq7dZ+Dl0ilgEsh3Q1WOO/S/TBDkeURIHfIkc886p5M4u5iQdkO1fndptUhBNbaM1idMOW/5QUWFeIEChdSo3mrVVTWyvhQEkYls0GYJUSVSdaITcyE3xkJA=</X509Certificate>
                </X509Data>
            </KeyInfo>
        </Signature>
    </Esign>'/>

But i want to bind like below without spaces.
<input type="hidden" id="thisField" name="inputName" value='<?xml version="1.0" encoding="UTF-8"?><Esign AuthMode="1" aspId="ASPRBLBMUMTEST043" ekycId="448988431774" ekycIdType="A" ekycMode="U" organizationFlag="N" preVerified="n" responseSigType="pkcs7" responseUrl="http://10.80.49.41" sc="Y" ts="2018-01-19T11:42:55" txn="UKC:eSign:6539:20180119114250963" ver="2.0"><Docs><InputHash docInfo="Signing pdf" hashAlgorithm="SHA256" id="1">30e3ed7f512da50206b8720d52457309c87f4edfee85d08f937aef3f955fb7af</InputHash></Docs><Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/><Reference URI=""><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><DigestValue>kQEB9r4dd5hhdaPxc4sjPMG3SGM=</DigestValue></Reference></SignedInfo><SignatureValue>MSgEXK2+GpwnRBr3vLNncqc9FOY0oDhjlhfyihOjrUPFZAL8eBms6jXdhoWGlrypaF6hE70ZltDQbQTArrk/mfCmoVvna7yEJN9gDh6gAHbh9Zj4BEBdWhd85DKbAdtSy8zYTKIeIjhFBzOItUAhSN7lFrEFVrTLV5wO38hswD7LlaY4ZBSNMWbpHPx+Io6ukdP8b4n95dqoB9iiqKxg3nK0RslhLRcPoe4B2AsdoiZ42iY/tZ4disOzyOCyCdE8nRxipJbP9HZS3psCSCar3CPSigXiNk6fY7+bDEFbJrfoqhHBk1hasx2m0TbxZVeOIPSUPRYpekHCm0sm4RvZhA==</SignatureValue><KeyInfo><X509Data><X509SubjectName>CN=Rbl Bank Test,OU=AAA Bank IT Dept,O=AAA Bank,L=Delhi,ST=Delhi,C=91</X509SubjectName><X509Certificate>MIIDkTCCAnmgAwIBAgIEZNl4CjANBgkqhkiG9w0BAQsFADB5MQswCQYDVQQGEwI5MTETMBEGA1UECBMKTWFoYXJhc3RyYTEPMA0GA1UEBxMGTXVtYmFpMREwDwYDVQQKEwhSYmwgQmFuazEZMBcGA1UECxMQUkJMIEJhbmsgSVQgRGVwdDEWMBQGA1UEAxMNUmJsIEJhbmsgVGVzdDAeFw0xNzAzMDIxNDA4MTBaFw0xODAyMjUxNDA4MTBaMHkxCzAJBgNVBAYTAjkxMRMwEQYDVQQIEwpNYWhhcmFzdHJhMQ8wDQYDVQQHEwZNdW1iYWkxETAPBgNVBAoTCFJibCBCYW5rMRkwFwYDVQQLExBSQkwgQmFuayBJVCBEZXB0MRYwFAYDVQQDEw1SYmwgQmFuayBUZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsjsF71lv96Y+2DbuSgk1U/Bp3P+jPpKp9GpwiVuIAf4SsBc1bqR3x4JSnY4COdUlq2IkHYSGnufGkPS6tH4edoFpZrSBAiTo1D0WQQ4KoRWBzn9xptMGsJBoV7dcSovjjD1HhUJGNnfoxjBh3AmIe8ZySWhuouEA8cRtFcHoWunpSB1FOJreIZ1P/ZnJ7C4gu+E1ccXjkFPqCGI9RcdUSE72K+ovtI/yWIUPwXdj3O/k30iX2owxUVFKnCmIDFnKDJ/b96RDzlIB9FiH5IVQm4mcU6HiQKqknDI3bPKlwvfFfB+YI69vjRQf3dvsca2nZQsYT3iSgkxBwoiugsD59QIDAQABoyEwHzAdBgNVHQ4EFgQUwFYILDVGVtIJgYveFqZ9YRrRq4AwDQYJKoZIhvcNAQELBQADggEBAKygyzVE1sOaBxuj4IjGDmo2y5UOhPOzklRocZbsqycEApcBn5m/dVauvewqw7An1vrkvjTYbTUCjUKghNW/MdtiWbKKRDy3fA8DyEACcYuK0PpaaXMTJFjIjKxXko6Rmmp6CKFcmERgetiwrFreMfFjvCv9H1fk7FSR87d/17l/LsmAndFIvpZTF3Ruz4lZsoL2qWtBF+wnVjFW+yqf6nXDqE/Swxhiq7dZ+Dl0ilgEsh3Q1WOO/S/TBDkeURIHfIkc886p5M4u5iQdkO1fndptUhBNbaM1idMOW/5QUWFeIEChdSo3mrVVTWyvhQEkYls0GYJUSVSdaITcyE3xkJA=</X509Certificate></X509Data></KeyInfo></Signature></Esign>'/>

Is there any way to bind like as shown in the above?

A: You can perform a manipulation of the xml string in your controller with a little regex to eliminate the newlines and whitespace.
Here is a little java app to show the regex in work against your xml string.
public class StripXmlWhitespace {

       public static void main (String [] args) {
           String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "    <Esign AuthMode=\"1\" aspId=\"ASPRBLBMUMTEST043\" ekycId=\"448988431774\" ekycIdType=\"A\" ekycMode=\"U\" organizationFlag=\"N\" preVerified=\"n\" responseSigType=\"pkcs7\" responseUrl=\"http://10.80.49.41\" sc=\"Y\" ts=\"2018-01-19T11:42:55\" txn=\"UKC:eSign:6539:20180119114250963\" ver=\"2.0\">\n" +
                "        <Docs>\n" +
                "            <InputHash docInfo=\"Signing pdf\" hashAlgorithm=\"SHA256\" id=\"1\">30e3ed7f512da50206b8720d52457309c87f4edfee85d08f937aef3f955fb7af</InputHash>\n" +
                "        </Docs>\n" +
                "        <Signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\">\n" +
                "            <SignedInfo>\n" +
                "                <CanonicalizationMethod Algorithm=\"http://www.w3.org/TR/2001/REC-xml-c14n-20010315\"/>\n" +
                "                <SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"/>\n" +
                "                <Reference URI=\"\">\n" +
                "                    <Transforms>\n" +
                "                        <Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\"/>\n" +
                "                    </Transforms>\n" +
                "                    <DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"/>\n" +
                "                    <DigestValue>kQEB9r4dd5hhdaPxc4sjPMG3SGM=</DigestValue>\n" +
                "                </Reference>\n" +
                "            </SignedInfo>\n" +
                "            <SignatureValue>MSgEXK2+GpwnRBr3vLNncqc9FOY0oDhjlhfyihOjrUPFZAL8eBms6jXdhoWGlrypaF6hE70ZltDQbQTArrk/mfCmoVvna7yEJN9gDh6gAHbh9Zj4BEBdWhd85DKbAdtSy8zYTKIeIjhFBzOItUAhSN7lFrEFVrTLV5wO38hswD7LlaY4ZBSNMWbpHPx+Io6ukdP8b4n95dqoB9iiqKxg3nK0RslhLRcPoe4B2AsdoiZ42iY/tZ4disOzyOCyCdE8nRxipJbP9HZS3psCSCar3CPSigXiNk6fY7+bDEFbJrfoqhHBk1hasx2m0TbxZVeOIPSUPRYpekHCm0sm4RvZhA==</SignatureValue>\n" +
                "            <KeyInfo>\n" +
                "                <X509Data>\n" +
                "                    <X509SubjectName>CN=AAA Bank Test,OU=AAA Bank IT Dept,O=AAA Bank,L=Delhi,ST=Delhi,C=91</X509SubjectName>\n" +
                "                    <X509Certificate>MIIDkTCCAnmgAwIBAgIEZNl4CjANBgkqhkiG9w0BAQsFADB5MQswCQYDVQQGEwI5MTETMBEGA1UECBMKTWFoYXJhc3RyYTEPMA0GA1UEBxMGTXVtYmFpMREwDwYDVQQKEwhSYmwgQmFuazEZMBcGA1UECxMQUkJMIEJhbmsgSVQgRGVwdDEWMBQGA1UEAxMNUmJsIEJhbmsgVGVzdDAeFw0xNzAzMDIxNDA4MTBaFw0xODAyMjUxNDA4MTBaMHkxCzAJBgNVBAYTAjkxMRMwEQYDVQQIEwpNYWhhcmFzdHJhMQ8wDQYDVQQHEwZNdW1iYWkxETAPBgNVBAoTCFJibCBCYW5rMRkwFwYDVQQLExBSQkwgQmFuayBJVCBEZXB0MRYwFAYDVQQDEw1SYmwgQmFuayBUZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsjsF71lv96Y+2DbuSgk1U/Bp3P+jPpKp9GpwiVuIAf4SsBc1bqR3x4JSnY4COdUlq2IkHYSGnufGkPS6tH4edoFpZrSBAiTo1D0WQQ4KoRWBzn9xptMGsJBoV7dcSovjjD1HhUJGNnfoxjBh3AmIe8ZySWhuouEA8cRtFcHoWunpSB1FOJreIZ1P/ZnJ7C4gu+E1ccXjkFPqCGI9RcdUSE72K+ovtI/yWIUPwXdj3O/k30iX2owxUVFKnCmIDFnKDJ/b96RDzlIB9FiH5IVQm4mcU6HiQKqknDI3bPKlwvfFfB+YI69vjRQf3dvsca2nZQsYT3iSgkxBwoiugsD59QIDAQABoyEwHzAdBgNVHQ4EFgQUwFYILDVGVtIJgYveFqZ9YRrRq4AwDQYJKoZIhvcNAQELBQADggEBAKygyzVE1sOaBxuj4IjGDmo2y5UOhPOzklRocZbsqycEApcBn5m/dVauvewqw7An1vrkvjTYbTUCjUKghNW/MdtiWbKKRDy3fA8DyEACcYuK0PpaaXMTJFjIjKxXko6Rmmp6CKFcmERgetiwrFreMfFjvCv9H1fk7FSR87d/17l/LsmAndFIvpZTF3Ruz4lZsoL2qWtBF+wnVjFW+yqf6nXDqE/Swxhiq7dZ+Dl0ilgEsh3Q1WOO/S/TBDkeURIHfIkc886p5M4u5iQdkO1fndptUhBNbaM1idMOW/5QUWFeIEChdSo3mrVVTWyvhQEkYls0GYJUSVSdaITcyE3xkJA=</X509Certificate>\n" +
                "                </X509Data>\n" +
                "            </KeyInfo>\n" +
                "        </Signature>\n" +
                "    </Esign>";
           String output = xmlString.replaceAll(">\\s+<", "><");
           System.out.println(xmlString);
           System.out.println(output);

       }

}

All you need in your controller is the regex.
xml = xmlString.replaceAll(">\\s+<", "><");

Essentially unformat the xml before you send it bind it to the view.  I hope that helps.


Q: REGEX to extract multiple name/value tokens (vbscript) Given a template that looks like this:
{*}Street Address:

     ^^ might be a space here, might not        ^^ always a space here

I need to read the name=value pairs out of the comment, plus the whole string so it can be replaced. Names could be any alpha-numeric with no spaces, values could contain anything except double quotes, will be short as possible, and will always be surrounded by double-quotes.
So, possible formats:

I've tried a dozen different variations, but the most successful I've been so far is to get the first name="value" pair and nothing else, or I get the whole page worth of stuff. So the desired matches are
[1]
[2] drinks
[3] yes, please
[4] breadsticks
[5] garlic, butter (lots); cheese

The closest I've come so far is

but it only returns the last pair, not all of them.

A: Implementation of the 2 step processes @sln mentioned in VBScript:
Option Explicit

Dim rCmt : Set rCmt = New RegExp
rCmt.Global = True
rCmt.Pattern = ""
Dim rKVP : Set rKVP = New RegExp
rKVP.Global = True
rKVP.Pattern = "(\w+)=""([^""]*)"""
Dim sInp : sInp = Join(Array( _
    "{*}Street Address:	" _
  , "" _
  , "" _
 , "	" _
 , "" _
), vbCrLf)

WScript.Echo sInp
WScript.Echo "-----------------"
WScript.Echo rCmt.Replace(sInp, GetRef("fnRepl"))
WScript.Quit 0

Function fnRepl(sMatch, nPos, sSrc)
  Dim d : Set d = CreateObject("Scripting.Dictionary")
  Dim ms : Set ms = rKVP.Execute(sMatch)
  Dim m
  For Each m In ms
      d(m.SubMatches(0)) = m.SubMatches(1)
  Next
  fnRepl = "a comment containing " & Join(d.Keys)
End Function

output:
cscript 45200777-2.vbs
{*}Street Address:

-----------------
{*}Street Address:

a comment containing template for prev

a comment containing pipapo rof prev

As Mr. Gates Doc for the .Replace method sucks, see 1, 2, 3.


Q: find out what instructions write to this memory address olly dbg cheat engine Is there an option in ollydbg to find out what pieces of code write to a memory address ? Just like Cheat Engine shows all the assembly instructions that write to a specific address.
"breakpoint --> memory" does not work.

A: Yes,
With olly open and debugging a certain program, go to View tab>Memory or Alt+M
then, find the memory address (first you have to choose the memory part of the program like .data or .bss) and then click on the address (or addresses selecting multiple with Shift) with the right mouse button and hover to Breakpoint then you'll be able to choose the to break the program when it writes or reads the address
A good thing to do is first find the address on cheatEngine then use the breakpoint on ollydbg.


Q: setNeedsDisplay not resulting in dirtyRect filling entire view I am having a confusing issue.  I try to draw a graph, and call setNeedsDisplay each time new data is added to the graph.
The graph receives new data via addData:(NSNotification*)theNote, which then tries several ways to call setNeedsDisplay to redraw the view.  The data does not get redrawn properly, however, at this time.  If I drag the window to another screen, or if I click on the graph and call setNeedsDisplay from mouseDown then the view is redrawn correctly.  By monitoring the size of dirtyRect using NSLog, I have tracked the problem to a too small dirtyRect.  But I cannot even guess how to correct this.  Any ideas out there?
//
//  graphView.m
//  miniMRTOF
//
//  Created by シューリ ピーター on 8/1/16.
//  Copyright © 2016 シューリ ピーター. All rights reserved.
//

#import "graphView.h"

@implementation graphView

- (id)initWithFrame:(NSRect)frame{
    self = [super initWithFrame:frame];
    if (self) {

        NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
        [nc addObserver:self selector:@selector(addData:) name:AddDataNotification object:nil];

        theData = [[NSMutableArray alloc] init];

        NSLog(@"graphView initialized");

    }
    return self;
}

-(void)addData:(NSNotification*)theNote{
    NSLog(@"graphView has gotten the note");

    NSMutableArray *theThermalArray = [[NSMutableArray alloc] init];

    theThermalArray = [[theNote userInfo] objectForKey:@"theThermals"];
    float ave = 0;
    int n = 0;
    for (int i=0; i<16; i++){
        float f_i = [[theThermalArray objectAtIndex:i] floatValue];
        ave += f_i;
        if(f_i != 0) n++;
    }
    ave /= n;

    [theData addObject:[NSNumber numberWithFloat:ave]];
    NSLog(@"graphView has added %0.3f and now has %lu components", ave, (unsigned long)[theData count]);
    [self setNeedsDisplay:YES];
    [[self.window contentView] setNeedsDisplay:YES];
    [self performSelectorOnMainThread:@selector(redraw) withObject:nil waitUntilDone:YES];
}

-(void)redraw{
    [self setNeedsDisplay:YES];
    [[self.window contentView] setNeedsDisplay:YES];

}

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];
    // Drawing code here.

    NSLog(@"dirtyRect: x:%0.2f, y:%0.2f, w:%0.2f, h:%0.2f", dirtyRect.origin.x, dirtyRect.origin.y, dirtyRect.size.width, dirtyRect.size.height);

    float xScale = ([self bounds].size.width)/((float)[theData count]+1e-3);//(maxX - minX);
    float yScale = [self bounds].size.height/(maxT - minT);

    [[NSColor whiteColor] set];
    NSRect fillArea = [self bounds];
    [NSBezierPath fillRect:fillArea];

    if(dirtyRect.size.height < 100){
        NSLog(@"small dirtyRect");
        [[NSColor grayColor] set];
        [NSBezierPath fillRect:dirtyRect];
    }
    dirtyRect = [self bounds];

    int dataCount = (int)[theData count];

    NSBezierPath *pathForFrame = [[NSBezierPath alloc] init];

    NSPoint P0 = {1,1};
    NSPoint P1 = {1, [self bounds].size.height};
    NSPoint P2 = {[self bounds].size.width, 1};

    [pathForFrame moveToPoint:P0];
    [pathForFrame lineToPoint:P1];
    [pathForFrame moveToPoint:P0];
    [pathForFrame lineToPoint:P2];

    [[NSColor redColor] set];
    [pathForFrame stroke];

    NSLog(@"drawing %i points", dataCount);

    NSBezierPath *pathForPlot = [[NSBezierPath alloc] init];
    if(dataCount<maxRawPlotData){
        if(dataCount>1){

            NSPoint p1;
            p1.y = [[theData objectAtIndex:0] floatValue];
            p1.x = (0-minX)*xScale;
            p1.y = (p1.y-minT)*yScale;
            [pathForPlot moveToPoint:p1];
            NSLog(@"point: %0.1f, %0.1f", p1.x, p1.y);
        }
        for(int i=1; i<dataCount; i++){

            NSPoint p;
            p.y = [[theData objectAtIndex:i] floatValue];
            p.x = (i-minX)*xScale;
            p.y = (p.y-minT)*yScale;
            [pathForPlot lineToPoint:p];
            NSLog(@"point: %0.1f, %0.1f", p.x, p.y);
        }
    }

    [[NSColor blackColor] set];
    [pathForPlot stroke];

    [txtMaxX setStringValue:[NSString stringWithFormat:@"%0.0f",maxX]];

}

-(void)controlTextDidEndEditing:(NSNotification *)obj{
    NSLog(@"controlTextDidEndEditing");
    if([[obj object] isEqualTo:txtMaxT]){
        maxT = [txtMaxT floatValue];
        [txtMidT setStringValue:[NSString stringWithFormat:@"%0.1f",0.5*(maxT+minT)]];
    }
    else if([[obj object] isEqualTo:txtMinT]){
        minT = [txtMinT floatValue];
        [txtMidT setStringValue:[NSString stringWithFormat:@"%0.1f",0.5*(maxT+minT)]];
    }
    else if([[obj object] isEqualTo:txtMaxX]){
        maxX = [txtMaxX floatValue];
    }
    else if([[obj object] isEqualTo:txtMinX]){
        minX = [txtMinX floatValue];
    }
    else NSLog(@"How'd we get here?");

    [[[obj object] window] makeFirstResponder:[[obj object] window].contentView];
    [self setNeedsDisplay:YES];
    [self display];
}

-(void)mouseDown:(NSEvent *)theEvent{
    NSLog(@"mousedown");
    [self setNeedsDisplay:YES];
}

@end


Q: JIRA Xray Cloud - Import Execution Results using REST API Hi I am using JIRA Cloud and trying to import execution result using REST API.
End Point URL - https://xray.cloud.getxray.app/api/v1/import/execution
Request Type - POST
Content-Type - application/json
Authorization: Bearer ""
Body -
{
"info" : {
"project": "QAUT",
"summary" : "Execution of automated tests using UFT",
"description" : "This execution is automatically created when importing execution results from UFT",
"startDate" : "2022-09-19T11:47:35+01:00",
"finishDate" : "2022-09-19T11:53:00+01:00",
"testPlanKey" : "QAUT-1"
},
"tests" : [
{
"testKey" : "QAUT-3",
"start" : "2022-09-19T11:47:35+01:00",
"finish" : "2022-09-19T11:50:56+01:00",
"actualResult" : "Successful execution",
"status" : "PASSED"
}
]
}
I am getting below errors:
Response code - 400
Response Body -
{
"error": "Result is not valid Xray Format"
}


Q: Unexpected behavior Using React useState, Very strange output I am a newbie in React. I was experimenting around to see how things work,
and I found a very strange Behavior of React or useState whatever you want to call it.
Please, Someone, explain, what is going on and how this piece of coding is working.

const {useState} = React;

let referceGiver = 0;
function giveNewRef() {
  let a = referceGiver;
  console.log("Making New Reference | Ref = ", a);
  referceGiver++;
  return a;
}

function App() {
  let v = "10";
  console.log("%cIniside Function", "background-color:red", `| v = ${v}`);

  let [val, setVal] = useState('30');

  const currentReference = giveNewRef();
  console.log("Outer Function Reference = ", currentReference)

  console.log("Value of UseState Val = ", val);

  function clicked() {
    v += ' 20';
    console.log("Inner Function Reference = ", currentReference);
    console.log("Value of V = ", v);
    setVal(v);
  }
  console.log("%cGoing To Return", "background-color:green");
  console.log('-----------------------------')

  return (

{val + " " + Math.random()}

      <button onClick={clicked} > Click </button>

  );
}

ReactDOM.render(<App/>, document.querySelector('#mount'));

Output of the above code
Tell me why:

*

*inner and outer reference is different

*useState does not change 2 times but changes a third time

*giveNewRef() increasing value by 2


Q: Changing the shape of a new assigned variable in Tensorflow if you change a tf.Variable using tf.assign with validate_shape=False the shape is not updated.
But if I use set_shape to set the new (correct) shape I get a ValueError.
Here a quick example:
import tensorflow as tf

a = tf.Variable([3,3,3])

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    # [3 3 3]
    print(sess.run(a))

    sess.run(tf.assign(a, [4,4,4,4], validate_shape=False))
    # [4 4 4 4]
    print(sess.run(a))

# (3,)
print(a.get_shape())

# ValueError: Dimension 0 in both shapes must be equal, but are 3 and 4. Shapes are [3] and [4].
a.set_shape([4])

How do I change the shape of the Variable?
Note: I am aware that the code works if I use a = tf.Variable([3,3,3], validate_shape=False) but in my context I will not be able to initialize the variable myself.

A: Tell the static part of the graph that the shape is unknown from the start as well.
a = tf.Variable([3,3,3], validate_shape=False)

Now, to get the shape, you cannot know statically, so you have to ask the session, which makes perfect sense:
print(sess.run(tf.shape(a)))


Q: How to remove backup logs on application startup I have a RotatingFileHandler with mode=w, maxBytes=20000000 and backupCount=10 as shown below:
[loggers]
keys=root

[logger_root]
level=INFO
handlers=file

[formatters]
keys=simple

[formatter_simple]
format=[%(levelname)s] %(asctime)s : %(name)s - %(message)s
datefmt=%H:%M:%s

[handlers]
keys=file

[handler_file]
class=handlers.RotatingFileHandler
formatter=simple
level=INFO
args=(log_directory,'w', 20000000, 10)

This means that after a period of time, 11 distinct log files will be present ( test.log, test.log.1, ..., test.log.10 ). My requirement is when the application is started, I want to delete all of the backup log files (test.log.1, ..., test.log.10). The content of test.log (current) log file will be removed anyway because mode is set to w.

A: That task is not under logging scope, you should "manually" delete them upon application start. Use os or shutil.


Q: How to debug Spring Cloud Kubernetes Configuration Watcher when it is not working as expectted There are two components in my k8s namespace.

*

*The first component is a simple Spring Boot Web Service with actuator/refresh endpoint exposed. I have mannualy make post request to the endpoint and it will trigger a configuration context refresh succesfully.

*The second component is Spring Cloud Kubernetes Configuration Watcher which I pull the image per official document guidance and make it run in my k8s env. Per official spring document, it should detect the changes on configmap with label spring.cloud.kubernetes.config="true" and make post request to the actuator/refresh endpoint of the application whose spring.application.name is equal to the configmap name.
The second component is not working as expectted, and I don't know how to trouble shoot the root cause.
My Springboot application is called spring-boot-demo, the configmap is also named as spring-boot-demo. But I never find any mentions of "spring-boot-demo" in Spring Cloud Kubernetes Configuration Watcher's log and nor can I assure if it has sent post request to related endpoint.
I can only see the logs showed up repeatedly below:
2021-11-22 02:58:53.332  INFO 1 --- [192.168.0.1/...] .w.HttpBasedConfigMapWatchChangeDetector : Added new Kubernetes watch: config-maps-watch-event
2021-11-22 02:58:53.332  INFO 1 --- [192.168.0.1/...] .w.HttpBasedConfigMapWatchChangeDetector : Kubernetes event-based configMap change detector activated
2021-11-22 03:34:06.555  WARN 1 --- [192.168.0.1/...] .f.c.r.EventBasedConfigMapChangeDetector : ConfigMaps watch closed

io.fabric8.kubernetes.client.WatcherException: too old resource version: 5491278743 (5554041906)
        at io.fabric8.kubernetes.client.dsl.internal.AbstractWatchManager.onStatus(AbstractWatchManager.java:263) [kubernetes-client-5.5.0.jar:na]
        at io.fabric8.kubernetes.client.dsl.internal.AbstractWatchManager.onMessage(AbstractWatchManager.java:247) [kubernetes-client-5.5.0.jar:na]
        at io.fabric8.kubernetes.client.dsl.internal.WatcherWebSocketListener.onMessage(WatcherWebSocketListener.java:93) [kubernetes-client-5.5.0.jar:na]
        at okhttp3.internal.ws.RealWebSocket.onReadMessage(RealWebSocket.java:322) [okhttp-3.14.9.jar:na]
        at okhttp3.internal.ws.WebSocketReader.readMessageFrame(WebSocketReader.java:219) [okhttp-3.14.9.jar:na]
        at okhttp3.internal.ws.WebSocketReader.processNextFrame(WebSocketReader.java:105) [okhttp-3.14.9.jar:na]
        at okhttp3.internal.ws.RealWebSocket.loopReader(RealWebSocket.java:273) [okhttp-3.14.9.jar:na]
        at okhttp3.internal.ws.RealWebSocket$1.onResponse(RealWebSocket.java:209) [okhttp-3.14.9.jar:na]
        at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174) [okhttp-3.14.9.jar:na]
        at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) [okhttp-3.14.9.jar:na]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_312]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_312]
        at java.lang.Thread.run(Thread.java:748) [na:1.8.0_312]
Caused by: io.fabric8.kubernetes.client.KubernetesClientException: too old resource version: 5491278743 (5554041906)
        ... 13 common frames omitted

2021-11-22 03:34:06.605  INFO 1 --- [192.168.0.1/...] .f.c.r.EventBasedConfigMapChangeDetector : Added new Kubernetes watch: config-maps-watch-event
2021-11-22 03:34:06.605  INFO 1 --- [192.168.0.1/...] .f.c.r.EventBasedConfigMapChangeDetector : Kubernetes event-based configMap change detector activated
2021-11-22 03:34:06.607  INFO 1 --- [192.168.0.1/...] s.c.k.f.c.Fabric8ConfigMapPropertySource : Loading ConfigMap with name 'spring-cloud-kubernetes-configuration-watcher' in namespace 'my-namespace'
2021-11-22 03:34:06.621  WARN 1 --- [192.168.0.1/...] o.s.c.k.f.config.Fabric8ConfigUtils      : config-map with name : 'spring-cloud-kubernetes-configuration-watcher' not present in namespace : 'my-namespace'
2021-11-22 03:34:06.625  WARN 1 --- [192.168.0.1/...] o.s.c.k.f.config.Fabric8ConfigUtils      : config-map with name : 'spring-cloud-kubernetes-configuration-watcher-kubernetes' not present in namespace : 'my-namespace'

The docker image I use is springcloud/spring-cloud-kubernetes-configuration-watcher:2.1.0-RC1
Any hint to debug this issue is appreciated.


Q: CSS mobile devices and hamburger menu I have designed a website that uses a CSS hamburger menu to activate a slidebar with a links to different webpages on the site.
I also have written an iPhone/andriod apps that need to have an hamburger menu that open a slider work that run swift and android code.
I want to add  to the iphone/android hamburger slidebar links to the website (which has it own hamburger menu)
How can I test on the website if it a mobile device or a PC, so I can turn off if "Website" hamburger if its a mobile, since I already have and need the hamburger menu on the mobile.
I have php on the website so I can remove the hamburger menu on the website if its a mobile.
This is the main page

<button class="w3-bar-item w3-button w3-large" onclick="w3_close()">Home</button>
Link 1
Link 2
Link 3

<button class="w3-button w3-teal w3-xlarge" onclick="w3_open()">☰</button>

My Page

Thanks

A: so there are a few ways of doing this, but a really simple one is something like this:
var width = $(window).width(); //jquery
var width = window.innerWidth; //javascript

if(width > 1000){do large screen width display)
else{handle small screen}

of course 1000 is just an arbitrary number. it gets tricky because when you consider tables, there really are screens of all sizes so its up to you to determine what belongs where

A:
How can I test on the website if it a mobile device or a PC, so I can
  turn off if "Website" hamburger if its a mobile,

If I understood you correctly, you could use CSS @media -rules, to setup CSS rules that only apply to smaller devices. Below is a simple code-snippet example of a CSS media-query.
@media (min-width: 700px), handheld
{
    .w3-sidebar
    {
        display: none;
    }
}


Q: NativeScript Typescript: JSON Array to Typescript Typed Array I need your help, I'm learning NativeScript, here I read the txt file which has JSON data below output. After I fetch them I want to assign it to Array countries. But no luck :(
public countries: Array
console.log(response)
console.log(JSON.parse(JSON.stringify(response)))
Output:
[
    {
        "name": "Afghanistan",
        "code": "AF"
    },
    {
        "name": "Albania",
        "code": "AL"
    }
]
Please help.
Regards,

A: This is an Array<any>:
[ { "name": "Afghanistan", "code": "AF" }, { "name": "Albania", "code": "AL" } ]
You need to convert it to a Array<Country>, Example:
result.forEach((e) => { countries.push(new Country(e.name, e.code))
That, or you can change the return of the function that reads the txt to Array<Country>

A: finally got it via below code...
                    let elements: Array<Country> = JSON.parse(JSON.stringify(response))
                    .map((item:Country) =>
                    {
                        console.log(item.name +  ' < - >' + item.code);
                    })

Thanks All :)


Q: jquery array confusion I have a web page with a bunch of tables decorated with the datatable jquery plugin. When the page is loaded, they're hidden. Then I have a function that toggles them based on the index:
function expand_job(i) {
    $(".dataTables_wrapper")[i].show();
}

But it didn't work. Browser complains that show() is not a function. As a work around, I'm doing something like this:
function expand_job(i) {
    $(".dataTables_wrapper").each( function(idx) {
        if ( i == idx ) {
            $(this).slideToggle(300);
        }
    });
}

That works fine but it's..... I just can't let this go.
So why did the first piece of code not work? Is it because [i] takes an jquery object into and normal JS object and as a result lost the jquery functionality?
Thanks,

A: Use .eq():
$(".dataTables_wrapper").eq(i).show();

jQuery arrays contain the underlying DOM elements at each index, so when you access them the DOM functions are available but not the jQuery methods.

A: $(".dataTables_wrapper")[i]

returns a std java script object, not a jQuery object so you could:
$($(".dataTables_wrapper")[i]).show()

or use nth child or similar