dimanche 19 avril 2015

Uk postcode regex producing false possitives

I'm trying to pick out post codes from an array. I am using the post office's regex to find the matches.



$postcodeRegex = "/(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2})/";

foreach( $content as $key => $line ){
if( preg_match($postcodeRegex, $line, $matches) !== false ) {
$points[] = $key;
}
}


But preg_match keeps is producing false positives. For example the line below is shown as a match.



HYPERLINK "mailto:email@address.com" email@address.com



My regex skills are very poor. How do i cut down on these false positives?


thanks


javascript pass by value instead of pass by reference having different javascript serialization string

I am using a javascript array as property of a javascript object. Whenever I modify the array it is affecting object property as it is passed by reference. So I cloned the object and set it as the object property.That problem is solved but now whenever I am trying to serialize the object I get different serialized string.



function Person(name, email, row) {
this.Name = name;
this.Email = email;

var clonedRow = $.extend(true,{}, row);
this.Row = clonedRow;
}

function FnClick() {
var arr = new Array();
arr[0] = "aaa";
arr[1] = "bbb";

var objPerson = new Person("Pallav", "P@abc.com", arr);
arr[0] = "xxx";
arr[1] = "zzz";

var serializedObj = JSON.stringify(objPerson); //Sys.Serialization.JavaScriptSerializer.serialize(objPerson);
var UserContext = new Array();
PageMethods.TestMethod(serializedObj,onSuccess,OnFailure,UserContext);

}


If I don't clone the row object and set it as it is the serializedObj string is


{"Name":"Pallav","Email":"P@abc.com","Row":["xxx","zzz"]}


and if I clone the object as above the serializedObj string is


{"Name":"Pallav","Email":"P@abc.com","Row":{"0":"aaa","1":"bbb"}}


Due to this the deserialized object in server side is different and row property of the object does not contain the 2 rows though it is in the serialized string.


How do I overcome this problem?


How to re-add tables based on models defined in ASP.NET MVC?

For some reason, all of my important tables have disappeared from the Database. I've deleted all of my migrations.cs files. Then, I executed a "Add-Migration Initial" and an "Update-Database", but received the following errors:



update-database -verbose
Using StartUp project 'DatingSiteInitial'.
Using NuGet project 'DatingSiteInitial'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'ContosoUniversity1' (DataSource: (LocalDb)\v11.0, Provider: System.Data.SqlClient, Origin: Configuration).
Applying explicit migrations: [201504191608070_test].
Applying explicit migration: 201504191608070_test.
IF object_id(N'[dbo].[FK_dbo.ProfileMeta_dbo.ProfileDetail_ID]', N'F') IS NOT NULL
ALTER TABLE [dbo].[ProfileMeta] DROP CONSTRAINT [FK_dbo.ProfileMeta_dbo.ProfileDetail_ID]
IF object_id(N'[dbo].[FK_dbo.ProfileMetaConversationMeta_dbo.ProfileMeta_ProfileMeta_ID]', N'F') IS NOT NULL
ALTER TABLE [dbo].[ProfileMetaConversationMeta] DROP CONSTRAINT [FK_dbo.ProfileMetaConversationMeta_dbo.ProfileMeta_ProfileMeta_ID]
IF object_id(N'[dbo].[FK_dbo.ProfileMetaMessageDetail_dbo.ProfileMeta_ProfileMeta_ID]', N'F') IS NOT NULL
ALTER TABLE [dbo].[ProfileMetaMessageDetail] DROP CONSTRAINT [FK_dbo.ProfileMetaMessageDetail_dbo.ProfileMeta_ProfileMeta_ID]
IF EXISTS (SELECT name FROM sys.indexes WHERE name = N'IX_ID' AND object_id = object_id(N'[dbo].[ProfileMeta]', N'U'))
DROP INDEX [IX_ID] ON [dbo].[ProfileMeta]
ALTER TABLE [dbo].[ProfileMeta] DROP CONSTRAINT [PK_dbo.ProfileMeta]
System.Data.SqlClient.SqlException (0x80131904): Cannot find the object "dbo.ProfileMeta" because it does not exist or you do not have permissions.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinTransaction(IEnumerable`1 migrationStatements, DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinNewTransaction(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClass30.<ExecuteStatements>b__2e()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.<Execute>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements, DbTransaction existingTransaction)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
ClientConnectionId:6efc46ea-dc76-45f9-b275-bb27809b50eb
Cannot find the object "dbo.ProfileMeta" because it does not exist or you do not have permissions.


How do I simply re-add the tables first before applying any foreign key restraints, etc...?


Create a SIMPLE ASP.NET WebForms app with role-based authentication

I've been looking into the two major options for user authentication in ASP.NET and after skimming over a few articles I am absolutely baffled. The last time I dabbled in ASP.NET, the .NET framework was only at v.2.0 which used the Membership system. I can't even really remember how that worked, let alone wrap my head around all this new Entity Framework and Identity stuff.


I like the sound of being able to use external logins (Facebook, Twitter, etc.) and roles, but seriously, why is this crap so damn complicated?! I thought ASP.NET was supposed to make a developer's life easier, but just learning how to use it seems like it will take me a week! I'm already behind schedule (this is for a uni project) and my supervisor is getting PO'ed at how long I'm taking to produce no results.


I just want a simple, easy-to-learn-and-use methodology for creating the following:



  1. A custom database schema with lots of extra user columns (survey questions that they have to answer) and maybe a model to go with it, although I'd be just as happy to use raw SQL (that seems to be easier to me!).

  2. A registration page that automatically hashes the entered password (preferably with 1000 iterations of PBKDF2, a 32-byte salt and whatever hash function you would recommend for strong security) and redirects to a customised "members" view of Default.aspx on successful registration, or posts back to itself and displays errors if any (depending upon custom validation logic).

  3. A login page that also redirects to the same customised Default.aspx and has the usual "Remember Me" checkbox.

  4. An "admin" role and "user" role, with registration adding to the users role. A single admin user will be created manually, but they will sign in through the same login form, then be presented with an admin page where they can view/delete users and all their info.


I currently have 1. and 2. implemented with nothing but HTML, CSS, jQuery and SQL, then I started on the login page and realised ASP.NET could probably do a lot of this for me. But how??


Maybe I haven't looked hard enough, or I'm too tired and overworked to fully take in what I've read, but I just want a simple, concise solution that covers all of these bases in one place! Scouring Google is getting me nowhere as it seems I have to read 5 different 2,000 word articles just to understand all of this stuff!


Anyone that can help me out will become my new god!


Find and replace a specific reference pattern by a regular expression (no.2)

Today, I was very happy that I get a solution for my first post here: Find and replace a specific reference pattern by a regular expression.


I'd like to replace following entries (and many more of these types in my document), so that the (number, if present, plus) the first three alpha-letters is written in the bracket after textit. The initial expression has to be appended. Examples:



\nobreakword{(vgl. 1. Johannes 4,16)} => \index[bibel]{@1. Johannes!\textit{1Joh 4,16}}\nobreakword{(vgl. 1. Johannes 4,16)}
\nobreakword{(vgl. Daniel 4,15.17.32f.)} => \index[bibel]{@Daniel!\textit{Dan 4,15.17.32f.}}\nobreakword{(vgl. Daniel 4,15.17.32f.)}


I have also ä/ö/ü characters inside the brackets:



\nobreakword{(vgl. 2. Könige 7,7)} => \index[bibel]{@2. Könige!\textit{2Köng 7,7}}\nobreakword{(vgl. 2. Könige 7,7)}


I'd like to include patterns in which the numerical part is written on the next line (because of copy paste) there is an ENTER (space/many blanck characters) between the text and numbers, e.g.:



\nobreakword{(vgl.
1. Korinther 13,4-7.8-12)} => \index[bibel]{@1. Korinther!\textit{1Kor 13,4-7.8-12}}\nobreakword{(vgl. 1. Korinther 13,4-7.8-12)}
\nobreakword{(vgl. 1.
Korinther 13,4-7.8-12)} => \index[bibel]{@1. Korinther!\textit{1Kor 13,4-7.8-12}}\nobreakword{(vgl. 1. Korinther 13,4-7.8-12)}
\nobreakword{(vgl. 1. Korinther
13,4-7.8-12)} => \index[bibel]{@1. Korinther!\textit{1Kor 13,4-7.8-12}}\nobreakword{(vgl. 1. Korinther 13,4-7.8-12)}


I have other text which should not be changed:



\index[stichwort]{Begriffe!Zeichen} => \index[stichwort]{Begriffe!Zeichen}
\index[stichwort]{Bilder [wörtl./bildhaft:Gleichnis,Symbol/beides]!Personen!Abraham} => \index[stichwort]{Bilder [wörtl./bildhaft:Gleichnis,Symbol/beides]!Personen!Abraham}


If possible I'd like again to use https://regex101.com


I tried (without success): \\nobreakword{(vgl. (\d+)(?:\.\s+))?(.{3})[\s\S]*?([a-z0-9.,-]+)}


Is it possible to use a single search pattern + single replace pattern with regular expression to replace all of the examples in one step?


Something strange with ASP.Net Webforms

I tried something by mistake and i do not understand why this is working:


I've created 2 asp.net web forms called page1.aspx and page2.aspx


On page1.aspx:



  • In code behind i declare a static string: field1.

  • I put a simple button.

  • When I click on this button:

    • field1="Hello world"

    • Response.Redirect("page2.aspx")




On page2.aspx, in Page_load, i display page1.field1 value. When page2.aspx is loaded, page1.aspx should not be loaded in memory. I do not understand why page1.field1 still contains "Hello world value !"


Can anyone explain me why this code works ? Is it a good thing to work this way ? Does asp store static fields in viewstate or session ?


Thanks


Here is page1.aspx:



<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="page1.aspx.cs" Inherits="WebApplication7.page1" %>

<!DOCTYPE html>

<html xmlns="http://ift.tt/lH0Osb">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>


Here is page1.aspx.cs:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication7
{
public partial class page1 : System.Web.UI.Page
{
public static string field1;

protected void Page_Load(object sender, EventArgs e)
{
}

protected void Button1_Click(object sender, EventArgs e)
{
field1 = "Hello world";
Response.Redirect("page2.aspx");
}
}
}


Here is page2.aspx.cs:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication7
{
public partial class page2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(page1.field1);
}
}
}

Prevent multiple users from viewing the same page

What's the optimal way to prevent multiple users from viewing the same page? I want to detect if another user is currently viewing, and if there is, display a message "Someone else is viewing this, please try again in a few minutes"


ASP.NET Button click event not firing in dynamic user control (VB)

I'm trying to make a self contained user control that is dynamically loaded to a page's UpdatePanel via links on the main page. The problem I am having is that I have never been able to fire the Click event of a button inside of the UserControl. The button should not affect the outer page at all and is simply trying to run a query against a DataGrid within the same UserControl


I have set the ChildrenAsTriggers property of the containing UpdatePanel to false as nothing inside any of these UserControl objects should manipulate anything outside of itself.


Here is what I have:



<asp:UpdatePanel ID="Updater" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="false">
<ContentTemplate>

</ContentTemplate>
</asp:UpdatePanel>


In addition, I have a simple asp:Button inside of the dynamically loaded UserControl that will eventually be contained in the UpdatePanel's ContentTemplate:



<asp:Button runat="server" ID="ButtonGo" Text="Go" />


And a click handler in the code behind:



Public Sub ButtonGo_Click() Handles ButtonGo.Click
//Trying to break here
End Sub


I've seen many questions regarding this that all deal with non-dynamic, XAML-in-place content, but can't find anything for my situation.


How do I access the click event of the button, or perhaps, what am I setting up incorrectly to prevent the event from occurring?


How to replace dashes with spaces, and double dashes with dashes?

I am writing a CRUD of people in Meteor, and I want pretty URLs like


http://ift.tt/1HI1TId.


(Actually, my real preference would be http://ift.tt/1It4TGn, but the implementation might be a bit more difficult.)


In order to accomplish that, I need to be able to translate from "John-Doe" to "John Doe" and from "John-Doe--Smith"John Doe-Smith".


I could of course use a preliminary replacement of "--" to some temporary character, but looking for a more elegant solution.


(Edit: after writing this, I just realized that I can sanitize the name to collapse multiple white spaces and dashes into one first; but I am now curious about the more generic answer).


How can i give line break in excel epplus asp.net c#

I am using Epplus library to convert dataTable in excel.I am using text area in my front end site.In which line break is also there.But the problem is when i convert this file to excel, Text is show in one line not in line break.How can I give line break in excel epplus. I am using following script.



using (ExcelPackage pck = new ExcelPackage(newFile))
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Accounts");
ws.Cells["A1"].LoadFromDataTable(dataTable, true);
pck.Save();
}

how to reference datatable names

Rather than referencing 0 and 1 for my rows. How do i reference the name of the columns in my data table?



txtCustomerRef.Text = dobj.GetCustomerData(selectedValue).Rows[0][0].ToString();
txtCustomerName.Text = dobj.GetCustomerData(selectedValue).Rows[1][1].ToString();

ValidationMessage asp.net mvc

I have a question about ModelState.AddModelError method and about the ValidationMessage method.


I am new to ASP.NET MVC and I am a little confused.


I wrote this code:



public ActionResult update(FormCollection collection)
{
int oos = 0;

try
{
oos = int.Parse(collection[0]);
}
catch
{
}

data d = new data();

TryUpdateModel(d , collection.ToValueProvider());

if (ModelState.IsValid)
{
return View("index",d);
}
else
{
ModelState.AddModelError("Date", "Wronge Date");
d.Id = 50;
return View("index",d);
}
}


and this code in the view side



@{

ViewBag.Title = "index";
}

<h2>index</h2>
@TempData["Hi"]


@Html.ValidationMessage("fullname")

@using (Html.BeginForm())
{
@Html.AntiForgeryToken() @Html.TextBox("id", 70)
@Html.TextBox("Date", "3/2/1991 12:00:00 ص")
@Html.ValidationMessage("Date","Please insert the correct Date Format")

<input type="submit">
}


My questions are, why the message Please insert the correct Date Format appears directly when I rune the index while still I did not submit the index, why when I submit the form with error in the date format the same message appear but not the message that I set to the Date Key in the update method which is Wronge Date.


maybe still I do not understand those two methods so I hope to find somebody to explain them to me.


explnation with example or reference would be appreciated


Merge CommandFields ASP.NET

This is the GridView :



<asp:GridView ID="grdProduct" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="sdsProducts" OnSelectedIndexChanged="grdProduct_SelectedIndexChanged" Width="1000px" BackColor="White" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" CellPadding="4" Font-Names="Arial" Font-Underline="False" ForeColor="Black">
<AlternatingRowStyle VerticalAlign="Middle" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID"/>
<asp:BoundField DataField="Name" HeaderText="Nom" SortExpression="Name" />
<asp:CommandField ButtonType="Image" CancelImageUrl="~/Images/dataG/cancel.png" DeleteImageUrl="~/Images/dataG/delete.png" EditImageUrl="~/Images/dataG/edit.png" InsertImageUrl="~/Images/dataG/insert.png" ShowEditButton="True" UpdateImageUrl="~/Images/dataG/update.png" />
<asp:CommandField ButtonType="Image" CancelImageUrl="~/Images/dataG/cancel.png" DeleteImageUrl="~/Images/dataG/delete.png" EditImageUrl="~/Images/dataG/edit.png" InsertImageUrl="~/Images/dataG/insert.png" ShowDeleteButton="True" UpdateImageUrl="~/Images/dataG/update.png" />
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" Font-Underline="False" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Center" VerticalAlign="Middle" />
<RowStyle HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />


It gives me this result :



--------------------------------
|ID | Name | | |
--------------------------------
| 1 | x | Edit | Delete|
| 2 | y | Edit | Delete|
| 3 | z | Edit | Delete|
--------------------------------


But i want it to be like this :



--------------------------------
|ID | Name | Action |
--------------------------------
| 1 | x | Edit Delete|
| 2 | y | Edit Delete|
| 3 | z | Edit Delete|
--------------------------------


Thank you :D


python Regular expression application (replace output which has(parentheses).)

I have written a function to printout output and some of the output has a (parentheses) that I preferred to re-intput some string into the (parentheses). Now I am trying to use python and regular expression .replace and finditer. But it seems not my cup of tea. So thank you for your help.



This is my output in my database:
interface fa(1)/(2)
ip address (1) (2)

this is my expected result after adding regular expression:

interface fa0/1
ip adress 192.168.1.1 255.255.255.0


This is my function



def readciscodevice(function, device)://here are some sqlite3 statement
conn = sqlite3.connect('server.db')
cur = conn.cursor()
if device == "switch":
cur.execute(
"SELECT DISTINCT command FROM switch WHERE function =? or function='configure terminal' or function='enable' ORDER BY key ASC",
(function,))
read = cur.fetchall()
return read
elif device == "router":
cur.execute(
"SELECT DISTINCT command FROM router WHERE function =? or function='configure terminal' or function='enable' ORDER BY key ASC",
(function,))
read = cur.fetchall()
return read;
elif device == "showcommand":
cur.execute(
"SELECT DISTINCT command FROM showcommand WHERE function =? or function='enable' ORDER BY key ASC",
(function,))
read = cur.fetchall()
return read;
a = input("function:") //First, I input function field from database
b = input("device:") //I need to input the name of my elif =="name"
p = re.compile('\(.*?\)') //I am not sure what it is doing...
s = "1"
iterator = p.finditer(s) //finditer is suitable to replace parentheses?
for match in iterator:
s = s[:match.start()] + s[match.start():match.end()].replace(match.group(), dict[match.group()]) + s[match.end()]
for result in readciscodevice(a,b):
print(result[0])

how to access object in asp.net

I have a scenario... I made a class RequestAndResponse in asp.net In App_Code folder. I want to access this in Default.aspx page but i am getting a problem Here is the code:



public partial class _Default : Page
{

RequestAndResponse request = new RequestAndResponse();

protected void Button1_Click(object sender, EventArgs e)
{
try
{

if (!String.IsNullOrEmpty(txtbox_query.Text.Trim()))
{

request.getParameter(txtbox_query.Text.Trim(), sourcePath,parameterValue);
request.BeginInvokeService(InvokeCompleted);

Response.Write(returnFromService);

}
else
{
//to do
}

}
catch (Exception error)
{
Response.Write(error.StackTrace);
}

}

public static void InvokeCompleted(IAsyncResult result)
{
returnFromService = request.EndInvokeService(result);
}


Now the scenario i hv created a object 'request' and want to access in InvokeCompleted method but i want able to do it. How will i do this??


Error: An object reference is required for the non-static field,method or property 'Default.request'


ASP.NET MVC 5.1 EnumHelper.EnumDropDownListFor on enum with Flags attribute

I want to make a dropdownlist of an enum property on my ViewModel.


I've been searching for examples like this and this where they use enums for displaying a select and radiobuttons controls if a form.


I have an enum like this



class MyViewModel
{
public JobCategory JobCategory {get; set;}
}

[Flags]
public enum JobCategory
{
/// <summary>
/// Ninguna
/// </summary>
[Display(Name = "N/A")]
None = 0,

/// <summary>
/// Diseño Grafico
/// </summary>
[Display(Name = "Diseño Gráfico")]
GraphicDesign = 1

...
}


And the form



@model MyViewModel

<div class="col-xs-3">
@(EnumHelper.IsValidForEnumHelper(Model.JobCategory.GetType())
? Html.EnumDropDownListFor(d => d.JobCategory, new { @class = "form-control" })
: Html.EditorFor(d => d.JobCategory, new { @class = "form-control" }))
</div>


When I remove the Flags attribute the method EnumHelper.IsValidForEnumHelper(Model.JobCategory.GetType()) returns true and displays a select otherwise returns false and the form displays a textbox.


Someone know how can I use this helper without removing the Flags attribute?


I am trying to parse a formula, and display it on screen. For example I should be able to take <path>T Q, where <path>T cannot change, and Q is a variable. It accepts it,however when printing it on screen again the only thing that will appear is T Q. I want <path>T Q to appear fully.


Other examples of accepted formulae are



(B & A)

~A

~(B&A)

<path>T (B & A)


etc


My code is something like this



var beginPartBUC = '^<path>\\(',
beginPart = '^\(',
unaryPart = '(?:~|<path>T)',
propOrBinaryPart = '(?:\\w+|\\(.*\\))',
subwffPart = unaryPart + '*' + propOrBinaryPart,
endPart = '\\)$';

// binary connective regexes

var conjRegEx = new RegExp(beginPart + '(' + subwffPart + ')&(' + subwffPart + ')' + endPart), // (p&q)
implRegEx = new RegExp(beginPart + '(' + subwffPart + ')->(' + subwffPart + ')' + endPart), // (p->q)
equiRegEx = new RegExp(beginPart + '(' + subwffPart + ')<->(' + subwffPart + ')' + endPart); // (p<->q)
// untilRegEx = new RegExp(beginPartBUC + '(' + subwffPart + ')U(' + subwffPart + ')' + endPart); //<path>(p U q))

How to hidden video url in asp.net mvc

I build a website on asp.net mvc 4. In this website, i will play video on youtube with link get from youtube, and I using jwplayer to play video.





<script>
jwplayer("box-live").setup(
{
file: "http://ift.tt/1Q5xAPf",
title: "CHAYDAN.COM", width: '728', height: '440',
logo: {
link: 'http://chaydan.com',
//file: '/Content/themes/frontend/images/logo-chaydan-mini.png',
position: 'bottom.right',
hide: 'false',
margin: '-35',
linktarget: '_blank',
hide: 'false',
over: '10',
out: '0.75'
},
});
function loadVideo(myFile, myImage) {
jwplayer().load([{ file: myFile, image: myImage }]);
jwplayer().play();
}
</script>



In javascript video url always show and end user can view source website to get video url. I don't users to be able to get this url.


How to fix it.


Thanks.


Calling Base Class Method using Reflection.Emit

I have set up my code to define a type, set the parent type as well as implement an interface. The problem I am having is that when I go to create the type it says that it cannot find the method implementations for the interface even though those methods are implemented on the parent type. From what I have seen you need to define pass through methods for a situation like this, here is my code to do that:



public interface IService<TDto, TId>
{
Task<TId> CreateAsync(TDto entity);
Task<bool> DeleteAsync(TId id);
Task<bool> UpdateAsync(TDto entity);
Task<List<TDto>> GetAllAsync();
Task<TDto> GetAsync(TId id);
TDto Get(TId id);
Task<IEnumerable<TDto>> GetAllPagedAsync(Int32 page, Int32 take);
Task<Int32> GetCountAsync();
Task<object> GetForIdsAsync(TId[] ids, Int32? page = null, Int32? pageSize = null);
object GetForIds(TId[] ids, Int32? page = null, Int32? pageSize = null);
Task<bool> DeleteForIdsAsync(TId[] ids);
Task<List<TDto>> CloneEntitiesAsync(List<TDto> dtos);
Task<IList> GetForTypesAndIdsAsync(List<string> types, List<object[]> typeIds);
Task<object> GetByConditionsAsync(Query query);
Task<object> ExceptIdsAsync(TId[] ids, Int32? page = null, Int32? pageSize = null);
bool Merge(TDto dto);
}

public Type[] CreateServiceType(Type dtoType, Type entityType, ModuleBuilder moduleBuilder)
{
string namespaceName = string.Format("Services.{0}", ProfileNamePlural);

TypeBuilder iserviceTypeBuilder =
moduleBuilder.DefineType(
string.Format("{0}.I{1}Service", namespaceName, ClassName),
TypeAttributes.Interface | TypeAttributes.Abstract);

var baseIServiceType = typeof (IService<,>).MakeGenericType(dtoType, entityType);
iserviceTypeBuilder.AddInterfaceImplementation(baseIServiceType);

Type iserviceType = iserviceTypeBuilder.CreateType();

var baseType = typeof(AService<,,>).MakeGenericType(dtoType, entityType, typeof(Guid));

string serviceClassName = string.Format("{0}.{1}Service", namespaceName, ClassName);

TypeBuilder serviceTypeBuilder =
moduleBuilder.DefineType(serviceClassName, TypeAttributes.Public);

serviceTypeBuilder.SetParent(baseType);

serviceTypeBuilder
.AddInterfaceImplementation(iserviceType);

var repositoryType = typeof(IRepository<>).MakeGenericType(entityType);

ConstructorBuilder ctorBuilder =
serviceTypeBuilder.DefineConstructor(
MethodAttributes.Public,
CallingConventions.Standard,
new[] { repositoryType });

var baseConstructor =
baseType.GetConstructor(
BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.Instance,
null,
new[] { repositoryType },
null);

var ilGenerator = ctorBuilder.GetILGenerator();

// Generate constructor code
ilGenerator.Emit(OpCodes.Ldarg_0); // push "this" onto stack.
ilGenerator.Emit(OpCodes.Ldarg_1);
ilGenerator.Emit(OpCodes.Call, baseConstructor);
ilGenerator.Emit(OpCodes.Ret);

DefinePassThroughs(ref serviceTypeBuilder, baseType, baseIServiceType);

return new[] { serviceTypeBuilder.CreateType(), iserviceType };
}

private void DefinePassThroughs(ref TypeBuilder typeBuilder, Type baseType, Type iServiceType)
{
var virtualMethods = iServiceType.GetMethods();
foreach (var imethod in virtualMethods)
{
var method = baseType.GetMethod(imethod.Name);
var paramTypes = method.GetParameters().Select(x => x.ParameterType).ToArray();

var passThroughMethod =
typeBuilder.DefineMethod(
method.Name,
MethodAttributes.Public,
CallingConventions.Standard,
method.ReturnType,
paramTypes);

var il = passThroughMethod.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
for (var i = 0; i < paramTypes.Length; i++)
{
il.Emit(OpCodes.Ldarg, i + 1);
}

il.EmitCall(OpCodes.Callvirt, method, null);
il.Emit(OpCodes.Ret);
typeBuilder.DefineMethodOverride(passThroughMethod, imethod);
}
}


When I try to create the type instance I get this error: "Signature of the body and declaration in a method implementation do not match." What am I missing here?


Remove unclosed brackets

How to remove unclosed brackets and its contents if after they have closed block. For example:



"(eaardf((eaar)(eaar" -> "eaardf((eaar)"


I do so, but I can not make a correct regex:



import re
str1 = '(eaardf((eaar)(eaar'
p = re.compile(r'\([a-z)]*.*')
p.sub('', str1)
>>> ''


Please help!


ItemCommand of DataList in UpdatePanel is not fired on Postback

I have a popup panel which contains an UpdatePanel, which contains a DataList. Table rows are populated using ItemTemplate and there is a LinkButton generated on each row for deleting this row. I would like to delete this record in the DataList's ItemCommand event handler and rebind the DataList.


However, after I click a "delete" button in the DataList, ItemCommand is not fired. I've already checked if IsPostBack in my Page_Load and only do Datalist.Databind() if it's not a postback. Normally I would expect first Page_Load and then list_ItemCommand being called after I click a delete button in the DataList, but list_ItemCommand is not called as expected. And nothing is then displayed in DataList which is inside the UpdatePanel.


And stranger, if I remove the IsPostBack check in Page_Load, that being said, rebind the DataList in every Page_Load, ItemCommand will be caught and list_ItemCommand is called. This is against the answers in many other posts "ItemCommand event will be canceled if DataList is rebinded during PostBack".


Code behind:



Protected records As New List(Of Record)

Protected Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Set some page properties...
If Not Page.IsPostBack Then
GetListOfRecordFromDatabase()
datalist.DataSource = records
datalist.DataBind()
End If
End Sub

Protected Sub datalist_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles datalist.ItemCommand
Select Case e.CommandName.ToLower
Case "delete"
For Each c As Record In records
If c.Id = e.CommandArgument Then
records.Remove(c)
Exit For
End If
Next
DeleteRecordFromDatabase(e.CommandArgument)
datalist.DataSource = records
datalist.DataBind()
End Select
End Sub


Controls:



<asp:Content ID="content1" runat="server" ContentPlaceHolderID="Content1PlaceHolder">
<asp:LinkButton ID="btnpopup" runat="server" OnClientClick="javascript:return popup()"></asp:LinkButton>
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server" EnableViewState="false" >
</asp:ScriptManagerProxy>

<asp:Panel ID="PanelPopup" runat="server" style="display:none;">

<asp:UpdatePanel ID="UPPopup" runat="server" UpdateMode="conditional" EnableViewState="false">
<ContentTemplate>
<div id="divPopup1" runat="server">

<table id="table1" cellpadding="2" cellspacing="1" width="500" border="0" >
<asp:DataList ID="datalist" runat="server" OnItemCommand="datalist_ItemCommand">
<ItemTemplate>
<tr align="center">
<td><%#Container.ItemIndex +1 %></td>
<td><asp:Label ID="Label1" runat="server" Text='<%# eval("Name") %>'></asp:Label></td>
<td><asp:Label ID="Label2" runat="server" Text='<%# eval("Color") %>'></asp:Label></td>
<td><asp:LinkButton ID="Delete" CommandName="Delete" runat="server" Text="Delete" CommandArgument='<%# eval("Id") %>' ></asp:LinkButton></td>
</tr>
</ItemTemplate>
</asp:DataList>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<div style="text-align:center;"><br />
<asp:Button ID="BtnSavePopup" runat="server" Text="Save and Close"/>
</div>
</asp:Panel>

<script type="text/javascript">
function popup() {
return mypagehelper.openAsModalPopup("<% =PanelPopup.ClientID%>");
}
</script>
</asp:Content>


Further more, I tried to grab the ControlID and the Control who raised the event during Postback using this code:



If IsPostBack Then
Dim CtrlID As String = String.Empty
If Request.Form("__EVENTTARGET") IsNot Nothing And
Request.Form("__EVENTTARGET") <> String.Empty Then
CtrlID = Request.Form("__EVENTTARGET")
Dim postbackControl As System.Web.UI.Control = Page.FindControl(CtrlID)
Else
End If


And I found that I can get my CtrlID as "ctl00$datalist$ctl08$Delete" but the postbackControl is Nothing. While on my other normal pages I can get both the controlID and actual control(which is a LinkButton) who raised the event.


asp.net repeater "eval" not reading value from table containong 200 records?

My problem is the "place": '<%# Eval("placer") %>' in the repeater is not extracting data from table_quake(column: placer). the column placer in the quake table contain 200 records and all 200 record is fetch and place in the repeater. All eval works but only place is not extracting


notes: When i fetch little record like 10 the '<%# Eval("placer") %>' work fine but with 200 records it does not extract.


My sample data for the column placer is:



placer
6km WNW of The Geysers, California
10km S of Anza, California
19km SW of North Nenana, Alaska
...........
......


here is my asp.net script to create the repeater:



<%@ Page Language="VB" AutoEventWireup="false" CodeFile="earthquakemap.aspx.vb" Inherits="earthquakemap" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://ift.tt/kkyg93">

<html xmlns="http://ift.tt/lH0Osb">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<script src="http://ift.tt/11czYwS" type="text/javascript"></script>
<script src="http://ift.tt/1JVNPKo" type="text/javascript" ></script>
<script type="text/javascript">
var markers = [
<asp:Repeater ID="rptMarkers" runat="server">
<ItemTemplate>
{
"times": '<%# Eval("times") %>',
"lat": '<%# Eval("latitude") %>',
"lng": '<%# Eval("longitude") %>',
"dep": '<%# Eval("depth") %>',
"magni": '<%# Eval("magnitude") %>',
"magtype": '<%# Eval("mag_type") %>',


"place": '<%# Eval("placer") %>'


"typo": '<%# Eval("type") %>',

}
</ItemTemplate>
<SeparatorTemplate>
,
</SeparatorTemplate>
</asp:Repeater>
];
</script>


My code behind:



Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim dt As DataTable = Me.GetData("select * from table_quake")
rptMarkers.DataSource = dt
rptMarkers.DataBind()



End If
End Sub

Private Function GetData(ByVal query As String) As DataTable
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim cmd As New SqlCommand(query)
Using con As New SqlConnection(conString)
Using sda As New SqlDataAdapter()
cmd.Connection = con

sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Function

Asp QueryStringParameter Conversion failed when converting the nvarchar

I get this error when I run the following code the global s are static int, I have looked at quite a few articles but cannot see where this is going wrong:



Exception Details: System.Data.SqlClient.SqlException: Conversion failed when converting the nvarchar value 'glb.catID' to data type int.




<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:CommerceConnectionString %>"

SelectCommand="select CategoryID, CategoryName, ProductImage, Title, SubCatID
from Categories
JOIN Products
ON Categories.CategoryID= Products.CatID
WHERE CategoryID = @CategoryID AND SubCatID = @SubCatID ">
<SelectParameters>
<asp:QueryStringParameter Name="CategoryID" QueryStringField="CategoryID" DefaultValue="glb.catID" />
<asp:QueryStringParameter Name="SubCatID" QueryStringField="SubCatID" DefaultValue="glb.subcatID"/>
</SelectParameter

How to filter out part-of-speech tag?


var sentence = "/`` Do/VBP n't/RB cut/VB off/RP its/PRP$ power/NN ,/, "/'' he/PRP said/VBD ./. ;
var pattern = new Regex(@"/(?:[.,]|\p{Lu}+\b)");
var outcome = pattern.Replace(sentence, string.Empty);

//Output : "/`` Do n't cut off its$ power , "/'' he said .


How should I modify the pattern to produce expected output of:


"Don't cut off its power," he said.


Php case insensitive word replacement from a sentence

I need to replace the matching words from a sentence. I am using the below but it's case sensitive. I need case insensitive.



$originalString = 'This is test.';
$findString = "is";
$replaceWith = "__";

$replacedString = (str_ireplace($findString, $replaceWith, $originalString));
// output : Th__ __ test.


Then I've tried



$replacedString = preg_replace('/\b('.preg_quote($findString).')\b/', $replaceWith, $originalString);
// output : This __ test.


It's working fine as expected but if i use $findString = "Is" or "iS" or "IS" then it's not working. Can anybody suggest me what will be the regex. to get case insensitive replacement or any other way to achieve the desire result.



UPDATED



As per @nu11p01n73R answer I have changed below but in below example it's get fall.



$originalString = 'Her (III.1) was the age of 2 years and 11 months. (shoulder a 4/5)';
$findStringArray = array("age", "(III.1)", "2", "months", "4");
foreach($findStringArray as $key => $value) {
$originalString = preg_replace('/\b('.preg_quote($value).')\b/i', "__", $originalString);
}
//Output : Her (III.1) was the __ of __ years and 11 __. (shoulder a __/5)

//Output should be : Her __ was the __ of __ years and 11 __. (shoulder a 4/5)


And also it's stopped working if I add 4/5 on $findStringArray


How to make footer stick on asp.net page?

I have a master page in asp.net which will contain other pages content throw a ContentPlaceHolder. I want to have a footer in the master page that sticks at the bottom usin css not matter what is displayed in the pages the uses the content ContentPlaceHolder.


Here is my master page:



<body>
<form id="form1" runat="server" style="height:100%;">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
<Scripts>
<asp:ScriptReference Path="Scripts/jquery-1.11.2.min.js" />
<asp:ScriptReference Path="Scripts/CommonMethods.js" />
<asp:ScriptReference Path="Scripts/CommonProperties.js" />
<asp:ScriptReference Path="http://ift.tt/1fJwIAs" />
<asp:ScriptReference Path="Scripts/jquery.watermark.min.js" />
</Scripts>
</asp:ScriptManager>
<div id="header">
<h1>
SABIS® Educational Systems INC.
</h1>
</div>
<div id="nav">
</div>
<div id="section">
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
<div id="footer">
Copyright © Sabis.net
</div>
<asp:ContentPlaceHolder ID="cpClientScript" runat="server">
</asp:ContentPlaceHolder>
</form>


I tried lots of css but nothing works properly for me there is always a flow!!.


I'm working on a project in asp Webforms, but I am stuck and don't really know how to keep going. I have read and tried lot of things without any result, so I hope you can help me.


I have created my own Hyperlink class extended from "System.Web.UI.WebControls.HyperLink" with some new methods, witch will became a new asp tag <asp:***> . I would like to substitute my own tag for the original one using the same asp prefix: <asp:Hyperlink>.


Once I have added my namespace and the prefix to the web.config file and run my app I get the next error:



"The server tag 'asp:HyperLink' is ambiguous. Please modify the associated registration that is causing ambiguity and pick a new tag prefix."



Don't know how to fix it, how can I change asp's own tag with mine? Does someone knows where asp's own tags namespace is? I hope I have explained myself and someone can help me.


Thanks in Advance.


Asier


JavaScript Regex for capitalized letters with accents

In JavaScript, its easy to match letters and accents with this regex:



text.match(/[a-z\u00E0-\u00FC]+/i);


And only the lowercase letters and accents without the i option:



text.match(/[a-z\u00E0-\u00FC]+/);


But what is the correct regular expression to match only capitalized letters and accents?


Design decision: Matching cyrillic chars in JSON with PHP

I'm developing a plugin for a CMS and have an unanticipated problem: because the plugin is multilang-enabled, input can be of any of the unicode character sets. The plugin saves data in json format, and contains objects with properties value and lookup. For value everything is fine, but the lookup property is used by PHP to retrieve these entities, and at certain points through regexes (content filters). The problems are:



  1. For non-latin characters (eg. Экспорт), the \w (word-char) in a regex matches nothing. Is there any way to recognize cyrillic chars as word chars? Any other hidden catches?

  2. The data format being JSON, non-latin characters are converted to JS unicodes, eg for the above: \u042D\u043A\u0441\u043F\u043E\u0440\u0442. Is it safe not to do this? (server restrictions etc.)


And the big 'design' question I have stems from the previous 2 problems:


Should I either allow users with non-Latin alphabet languages to use their own chars for the lookup properties or should I force them to traditional 'word' chars, that is a,b,c etc. + underscore (thus an alphabet from another language)? I'd welcome a technical advice to guide this decision (not a UX one).


How to use bash(3.2.25)'s An additional binary operator:=~

I feel confused about how to use "=~" when I read the info of bash(3.2.25) at rhel5.5



# match the IP, and return true
[kevin@server1 shell]# [[ 192.168.1.1 =~ "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$" ]] && echo ok || echo fail
ok



# add double qoute
# return false, en ... I know.
[kevin@server1 shell]# [[ 192.168 =~ "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$" ]] && echo ok || echo fail
fail

# remove double qoute
# return ture ? Why ?
[kevin@server1 shell]# [[ 192.168 =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] && echo ok || echo fail
ok


So, should I qoute the string to the right of the operator ? And why the second command return true,apparently it should return false !


Here is what the info said:



An additional binary operator, =~', is available, with the same precedence as==' and !='. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex3)). The return value is 0 if the string matches the pattern, and 1 otherwise. If the regular expression is syntactically incorrect, the conditional expression's return value is 2. If the shell optionnocasematch' (see the description of shopt' in *Note Bash Builtins::) is enabled, the match is performed without regard to the case of alphabetic characters. Substrings matched by parenthesized subexpressions within the regular expression are saved in the array variableBASH_REMATCH'. The element of BASH_REMATCH' with index 0 is the portion of the string matching the entire regular expression. The element ofBASH_REMATCH' with index N is the portion of the string matching the Nth parenthesized subexpression.



Extract text string from URL using regex

Basically I have list of URLs that look like this:


http://ift.tt/1yHArZk


and I want to extract auctiondate_244003 How would I do that with regex.


Thank you for your time. I'm a new to regex so I appreciate your help.


Customizing the "Resource Description" section of a ASP.NET Web API help page

I'm using ASP.NET Web API and it conveniently automatically generates documentation for my API, but some of it doesn't make sense.


Take the below screenshot as an example.


Screenshot


This is an endpoint to GET a user by their ID, and in the Resource Description section it's showing a table which shows the user model's properties because my controller action has the [ResponseType(typeof(User))] annotation.


Firstly, in my actual controller action, I'm stripping out the Password property before displaying results to the user in order to not expose sensitive information. So the table given in the Resource Description section is incorrect, it's saying my API returns fields that it doesn't.


Secondly, under the Additional Information column it's showing the validation rules that go along with the User model. Handy, but not at all relevant in this case as this endpoint is for GETing a user, not POSTing one.


So, my question is how can I customize this Resource Description table to specify myself what fields get returned, and hide the EF validations?


I've currently commented my controller action like this:



/// <summary>
/// Get a single user identified by ID.
/// </summary>
/// <param name="userId">The ID of the user.</param>
/// <returns>A data collection about the user.</returns>
[ResponseType(typeof(User))]
[Route("api/v1/users/{userId}", Name="GetUser")]
[HttpGet]
public IHttpActionResult GetUser(int userId)
{
// ...
}


and I've configured the help pages to read the documentation from an XML file which gets built from these /// comments when I build the project.


Thanks!


Can we use a class other than Abstract class which is not Instantiated in c#?

I know and read about abstract class and interface but want to Know is it possible in c# that we can create a class which is not allowing me to instantiated ?


VS 2013 - ASP.NET Web Application Template

I've tried to create new Web API project using "Visual C#/Web/ASP.NET Web Application" template, but i found that some templates and core references are missing: enter image description here


.NET Framework 4.5 is selected


If I go to the "Visual C#/Web/Visual Studio 2012" I've got this:enter image description here


I know that I can create WebApi project by using MVC Template, but i don't know why some features are missing. I have got VS2013 Ultimate edition (with update 2).


How can I obtain other features inside this template?


Restructuring my application

I am handling a project which needs restructuring set of projects belonging to a website. Also it has tightly coupled dependency between web application and the dependent project referenced. Kindly help me with some ideas and tools on how the calls could be re factored to more maintainable code.


The main aspect is that there are calls to apply promotion (promotion class has more than 4 different methods available) consumed from various functions, which could not be stream lined easily.


Kindly help me here with best practices.


Sorry guys- i could not share much code due ot restriction, but hope the below helps


My project uses N-Hibernate for data access Project A- web project - aspx and ascx with code behind Project B- Contains class definition consumed by project C (data operation class) Project C - Business logic with saving to database methods (customer, order, promotion etc.)


The problem is with project C - which i am not sure if it does too many things or needs to be broken down.But there are already many other sub projects.


Project C supports like saving details to DB based on parameters some of the class methods in this calls the promotion based on some condition, I would like to make things more robust - sample code below


Project -C Class - OrderLogic



public void UpdateOrderItem(....)
{
....
....
...
}
Order order = itm.Order;
promoOrderSyncher.AddOrderItemToRawOrderAndRunPromosOnOrder(itm, ref order);
orderItemRepository.SaveOrUpdate(itm);


So just like the above class the promotion is called from may other places, i would like to streamline this calls to promotion class file. So i am looking for some concepts.


Highlight Non-breaking spaces in HTML page or WordPress editor

While editing in WordPress, I sometimes use non-breaking spaces in headers so that words stay together. When I save, the non-breaking spaces are there, but they look like normal spaces, so I can't see them. Also, WordPress creates non-breaking spaces when I type in the body of my post, which I have to remove somehow.


I thought it'd be easy to create a bookmarklet that uses jQuery to highlight non-breaking spaces in a web page or the editor. However, I'm no good with regular expressions, or maybe there's something else I'm doing wrong. Here's the jQuery code:



$('p').html($('p').html().replace(/ [\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]/g, '<span class="red">&nbsp;</span>'));


Here's a jFiddle: http://ift.tt/1cLc572


I'm open to other suggestions as well :-)


Regex to match middle name/s

Assume input of a string containing a full name. Full names are very diverse - ie. Joe Bloggs, Joe Bloggs-Phillips, Joe Bloggs Phillips, Joe Bloggs Adams Phillips, Joe van den Bloggs, Joe van-der Bloggs.


I want to match what I will call "middle names". That is everything between the first and last space. That is, as above - "Bloggs Adams", "van den" and "van-der". Names with hyphenated words are full surnames. What is the regex for this?


PS. I'm aware of the cultural diversity in names, eg. "van der" is not actually a middle name but the start of a surname. So, if there is logic to build in to this regex to accommodate, this would help. Otherwise, I want to assume:



  • First name - everything up to first space.

  • Middle name - from first space to last space.

  • Last name - from final space to end.


Many thanks.


RegEx to replace prefix and postfix

I would like to build a RegEx expression to replace the prefix and postfix of a string. the general string is built from



  1. a known prefix string

  2. some letter a-z or A-Z

  3. some unknown string with letters, hyphens, backslash, slash and numbers.

  4. a hyphen

  5. an integer number

  6. the symbols #.

  7. some string of letters


Examples:



KnownStringr/df-2e\d-3724#.Gkjsu
KnownStringEd\e4v-bn-824#.YKfg
KnownStringa-YK224E\yy-379924#.awws


I would like to replace the prefix and postfix of the NUMBER so that I get:



MyPrefix3724MyPostfix
MyPrefix824MyPostfix
MyPrefix379924MyPostfix

how to initialise connection property within ExecuteReader

I would like to know based on my code, how i can initialise the connection property into my ExecuteReader correctly?


Here is my connection class:



namespace DAL
{
public class connection
{
const string StrConnection = "CustomerHelperConnectionString";
internal static Database DB;
public static DbCommand DBCommand;
public static Database Connect()
{

try
{
DB = DatabaseFactory.CreateDatabase(StrConnection);
return DB;
}
catch (Exception ex)
{
throw (ex);
}
}
public static DbCommand Procedure(string procedure)
{

try
{
DBCommand = DB.GetStoredProcCommand(procedure);
return DBCommand;
}
catch (Exception ex)
{
throw (ex);
}
}
}
}


I am getting an error:



ExecuteReader: Connection property has not been initialized.


I have the following:



public static DataTable GetCustomer(string CustomerRef1)
{
{
{
DataTable table;
try
{
string returnValue = string.Empty;

DB = Connect();
DBCommand = connection.Procedure("getCustomer);
DB.AddInParameter(DBCommand, "@CustomerRef", DbType.String, CustomerRef1);


DbDataReader reader = DBCommand.ExecuteReader(DBCommand.Connection("StrConnection));
table = new DataTable();
table.Load(reader);
return table;
}
catch (Exception ex)
{
throw (ex);
}

}

}
}


How do I pass the connection into:



DbDataReader reader = DBCommand.ExecuteReader();

Checkbox not filled

In my database there's a bool filed called IsAvailable.In my edit function i wanted to fill that checkbox is IsAvailable or not but in here always checkbox not filled.



($("#chkcomp").prop('checked') == msg._prodlng[0].IsAvailable);


but



msg._prodlng[0].IsAvailable // thisone returns true or false correctly according to database value

Passing objects to layout in mvc 5

I'm passing objects to the Layout from the controller like this:



public ActionResult MyProfile() {
var roles = new List<int?>();
User.Roles.ForEach(r => roles.Add(r.ID));
return View(new ProfileModel() { LoginUser = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(string.IsNullOrEmpty(User.LastName) ? string.Empty : User.LastName.ToLower()), UserRole = new List<int?>(roles) });
}

public class ModelBase {

[DisplayFormat(ConvertEmptyStringToNull = false)]
public string LoginUser { get; set; }

public List<int?> UserRole { get; set; }

public ModelBase() {
UserRole = new List<int?>();
}
}

public class ProfileModel : ModelBase { }


This works but, I have to do this for all my Controller Action when returning a view.


Is there a way for me to do this just once, without having to repeat it in my actions?


I try adding to it to a base controller, but ROLES and LOGINUSER were always null.


I know this has been addressed a lot on SO, but they are all doing the something.


Thanks.


Python regular expression and my function error

I have tried to write a program that replaced my new input into my output which has been (parentheses).


and there are some mistakes in my program.



a = input("function:")
b = input("device:")
p = re.compile('\(.*?\)')
iterator = p.finditer(s)
for match in iterator:
s = s[:match.start()] + s[match.start():match.end()].replace(match.group(), dict[match.group()]) + s[match.end()]
for result in readciscodevice(a,b):
print(result[0])


After I input the name of function and device it shows that:



iterator = p.finditer(s)
NameError: name 's' is not defined


So what was happening ? Anyone could tell me where is the main problem of these error?


vbs reg ex extract block within text

I want to extract each "blocks" of sub text using regex. My reg ex expression gets the correct start but also returns everything to the end of my file.


I am using:


re.ignorecase = true


re.multiline = false


re.global = true


re.pattern = "\balias\s=\sX[\s\S]{1,}end"


An example of the file format is:


Metadata Begin



Easting Begin

alias = X

projection = "geodetic"

datum = "GDA94"

Easting End

Northing Begin

alias = Y

projection = "geodetic"

datum = "GDA94"

Northing End


Metadata End


I want to extract the text starting at alias up to the next End for each occurrence so I can deal with the details one alias at a time. e.g. alias = X projection = "geodetic" datum = "GDA94" Easting End


But this does not get the first End after the alias. Instead the [\s\S] is matching everything after that first alias upto the end of the file. But [\s\S] is the only trick I can think of get past the CrLf at the end of each line. Is there a regex that match upto the first End over multiple lines? Thank you.


Need to reverse php regex and see what needs to be matched

I am not very good in RegEx and saying that I am editing a website written in php. One of it's functions are failing because of this regex:



preg_match("/^minus\((\-?[\d\.]+)\)$/i",$val,$m)


I know it should be something like minus() but it doesn't seems to find any matches as I can't figure it out what needs to be inside the brackets.


Regular Expression Arabic characters and numbers only

I want Regular Expression to accept only Arabic characters and numbers.


Numbers are not required to be in Arabic.


I found the following expression:



^[\u0621-\u064A]+$


which accepts only only Arabic characters while I need both Arabic characters and numbers.


c# Asp.net multiple SQL

Problem: 1) I would like to add multiple SQL command, like this , how can i do?



command.CommandText = "select * from Department where Name ='" + TextBox1.Text + "' and Password ='" + TextBox2.Text + "'";





OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\sim\Desktop\Web.accdb";
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from Registration where Name ='" + TextBox1.Text + "' and Password ='" + TextBox2.Text + "'";

OleDbDataReader reader = command.ExecuteReader();
int count = 0;

while (reader.Read())
{
count = count + 1;
}
if (String.IsNullOrEmpty(TextBox1.Text))
{
MessageBox.Show("You have't input the Username.");
}
if (String.IsNullOrEmpty(TextBox2.Text))
{
MessageBox.Show("you havn't input the Password.");
}
if (count == 1)
{

Session["UserID"] = TextBox1.Text ;
Response.Write("Username and password is valid");
connection.Close();
connection.Dispose();
Response.Redirect("Purchase.aspx", true);

}
else
{
MessageBox.Show("Username or Password is not matched");
}

Regex to get text between final two slashes

Taking a string with the following three examples...



/Services/Research/Consumer-services/Mobile-Services/
/Services/Research/Consumer-services/Fixed-Broadband-and-Multi-Play/
/Services/Research/Consumer-services/Next-Generation-Services/


I need to:


a) Strip so I only have the string contained between the two final slashes (ie. "Mobile-Services" ... /.*/(.*)/ seems to accomplish this, though I don't fully understand ti.


b) Replace dashes in the remaining text with spaces. So, "Mobile-Services" becomes "Mobile Services" and "Fixed-Broadband-and-Multi-Play" becomes "Fixed Broadband and Multi Play"


Thank-you very much.


Java program to extract coefficents from quadratic equation

Problem: Java program to split the coefficients from a quadratic equation eg if input string is:



String str1;
str1 = "4x2-4x-42=0"


So I need to split the coefficients from the given input string and to get output as



a = 4 b = -4 c = -42


I tried this:



String equation = "ax2+bx-c=0";
String[] parts = equation.split("\\+|-|=");
for (int i = 0; i < parts.length - 2; i++) {
String part = parts[i].toLowerCase();
System.out.println(part.substring(0, part.indexOf("x")));
}
System.out.println(parts[2]);


But I got the output as 23x2 and 4x and 4. Actual output needed is 23 ,- 4 , 4.


In ASP.NET MVC5, how can I hide the Action name when an a tag is generated in Razor using Url.Action?

As the title says.


I have a route set up and working fine, which provides a default Action when none is specified. I just want to hide the action from the URL because it's unnecessary clutter.


Setting the "actioName" parameter as null, or "", will just result in the current page's action being substituted instead - which doesn't work.


I'm open to using @Html.ActionLink if that will get me what I need.


If all else fails, I suppose I can deal with writing out the hrefs manually, but this should not be a difficult thing for Razor to do.


Has anyone else come across this and knows what to do?


ASP.NET+ MVC AngularJS

I want to make mvc web page and user angularjs on it, do you know good tutorial? I tried http://ift.tt/1OtbYIQ this tutorials,but something is wrong can you help me?


samedi 18 avril 2015

Is Bootstrap already installed with VS.NET 2015?

I have the VS.NET 2015 CTP. I've created a web app and selected to install a nuget package. I select Twitter.Bootstrap.Less and install. I see a green check mark next to this package in the nuget window. I close this window but don't notice a content folder in my project.


When I open the wwwroot > lib folder, I see:



bootstrap
bootstrap-touch-carousel


Those were there before I installed the bootstrap package.


Does bootstrap come default with web apps in vs.net 2015?


I installed the bootstrap nuget but the content folder isn't there and I don't see any other package downloads. Any idea where the package content went?


Restructuring my application

I am handling a project which needs restructuring set of projects belonging to a website. Also it has tightly coupled dependency between web application and the dependent project referenced. Kindly help me with some ideas and tools on how the calls could be re factored to more maintainable code.


The main aspect is that there are calls to apply promotion (promotion class has more than 4 different methods available) consumed from various functions, which could not be stream lined easily.


Kindly help me here with best practices.


model data validation, checking date is less then a date X years ago

How can I add model validation to check that the inputted date is less then a date X years, X days, or whatever ago?


C# Regex get Group Matches list from html

I have html example



<a href="http://ift.tt/1DvoowN" class="same-class">CONTENT1</a>
<a href="http://ift.tt/1DvoowN" class="same-class">CONTENT2</a>


I tried some different regex matching in order to get all CONTENTs. I have managed to make a match at: https://regex101.com This is returning only the first match. But even this is not working in C#


I have this code:



var matches = Regex.Matches(html, @"andOfQS"" class=""same-class"">(.*)<\/a>", RegexOptions.IgnoreCase & RegexOptions.Multiline);
foreach (Match match in matches) {
}


But, it return 0 matches. Please help me to get all CONTENTs (1 to n).


Python regex - wierd behavior - findall doesnt match regex101

I need to extract some functions from files.


I have this code:



pattern = "^\s*[a-zA-Z_]?.*void\s+[a-zA-Z_][a-zA-Z_0-9]*\s*\((?s).*?\).*?$"
objekt = re.findall(re.compile(pattern,re.MULTILINE), string)


where string is



extern inline void
lineBreak ( void )

;


extern inline void debugPrintf
(
const int level,
const char * const format,
...)
{
return NULL;
}

extern void
debugPutc
(
const int level
,
const int c)
;


it returns however



extern inline void
lineBreak ( void )

;


extern inline void debugPrintf
(
const int level,
const char * const format,
...)
{
return NULL;
}

extern void
debugPutc
(
const int level
,
const int c)


while when I am debugging at regex101 it returns 3 functions that I need to extract.


regex101 demo


Does anyone know where is the problem please? Thank you.


Rewrite all root level pages using Regex

I'm looking to re-write all root level pages on my server bar a few. The code I currently have is as follows:



<rule name="front-end-global" stopProcessing="true">
<match url="^/([^/]+)?$" />
<action type="Rewrite" url="/y-essentialibiza-com/{R:1}" />
<conditions>
<add input="{REQUEST_FILENAME}" pattern="buy.asp" negate="true" />
<add input="{REQUEST_FILENAME}" pattern="buy-vip-submitted.asp" negate="true" />
<add input="{REQUEST_FILENAME}" pattern="m-buy-mtl.asp" negate="true" />
</conditions>
</rule>


But this isn't working. I'd also like to negate certain folders but can't find a way to do this.


Apologies for the basic nature of this question. I'm new to Regex.


Thanks in Advance,


PJ


logstash target of repeat operator is not specified:

I want to use logstash to ship my logs,so I download the logstash1.5.0 rc2 and run it in ubuntu use the command :



bin/logstash -f test.conf


then the console show the error:



The error reported is:
**target of repeat operator is not specified:** /;(?<Args:method>*);(?<INT:traceid:int>(?:[+-]?(?:[0-9]+)));(?<INT:sTime:int>(?:[+-]?(?:[0-9]+)));(?<INT:eTime:int>(?:[+-]?(?:[0-9]+)));(?<HOSTNAME:hostname>\b(?:[0-9A-Za-z][0-9A-Za-z-]{0,62})(?:\.(?:[0-9A-Za-z][0-9A-Za-z-]{0,62}))*(\.?|\b));(?<INT:eoi:int>(?:[+-]?(?:[0-9]+)));(?<INT:ess:int>(?:[+-]?(?:[0-9]+)));(?<Args:args>*)/m


I don't know how to solve this error,may be you can help me.


my test.conf is as follow:



input { stdin { } }

filter {
grok {
match => ["message" , "%{INT:type}"]}


if [type]=="10" {
grok {
patterns_dir => "./patterns"
match => ["message" , ";%{Args:method};%{INT:traceid:int};%{INT:sTime:int};%{INT:eTime:int};%{HOSTNAME:hostname};%{INT:eoi:int};%{INT:ess:int};%{Args:args}"]
}

date {
match => [ "sTime" , "UNIX_MS" ]
}
ruby {
code => "event['duration'] = event['eTime'] - event['sTime']"
}

}
if [type] =~ /3[1-6]/ {
grok {
patterns_dir => "./patterns"
match => [ "message" , ";%{Args:method};%{Args:sessionid};%{INT:traceID:int};%{INT:sTime:int};%{INT:eTime:int};%{HOSTNAME:hostname};%{INT:eoi:int};%{INT:ess:int};URL{%{HttpField:url}};RequestHeader{%{HttpField:ReqHeader}};RequestPara{%{HttpField:ReqPara}};RequestAttr{%{HttpField:ReqAttr}};SessionAttr{%{HttpField:SessionAttr}};ResponseHeader{%{HttpField:ResHeader}}"]
}
kv {
source => "ReqHeader"
field_split => ";"
value_split => ":"
target => "ReqHeader"
}
kv {
source => "ResHeader"
field_split => ";"
value_split => ":"
target => "ResHeader"
}
date {
match => [ "sTime" , "UNIX_MS" ]
}
ruby {
code => "event['duration'] = event['eTime'] - event['sTime']"
}
}
if [type] == "30" {
grok {
patterns_dir => "./patterns"
match => [ "message" ,";%{Args:method};%{Args:sessionid};%{INT:traceID:int};%{INT:sTime:int};%{INT:eTime:int};%{HOSTNAME:hostname};%{INT:eoi:int};%{INT:ess:int};URL{%{HttpField:url}};RequestHeader{%{HttpField:ReqHeader}};RequestPara{%{HttpField:ReqPara}};RequestAttr{%{HttpField:ReqAttr}};SessionAttr{%{HttpField:SessionAttr}}"
]
}
kv {
source => "ReqHeader"
field_split => ";"
value_split => ":"
target => "ReqHeader"
}
kv {
source => "ResHeader"
field_split => ";"
value_split => ":"
target => "ResHeader"
}
date {
match => [ "sTime" , "UNIX_MS" ]
}
ruby {
code => "event['duration'] = event['eTime'] - event['sTime']"
}
}

if [type]=="20" {
grok {
patterns_dir => "./patterns"
match => [ "message" , ";%{Args:method};%{INT:traceID:int};%{INT:sTime:int};%{INT:eTime:int};%{HOSTNAME:hostname};%{INT:eoi:int};%{INT:ess:int};%{INT:mtype};%{Args:DBUrl}"]
}
date {
match => [ "sTime" , "UNIX_MS" ]
}
ruby {
code => "event['duration'] = event['eTime'] - event['sTime']"
}
}
if [type]=="21" {
grok {
patterns_dir => "./patterns"
match => [ "message" , ";%{Args:method};%{INT:traceID:int};%{INT:sTime:int};%{INT:eTime:int};%{HOSTNAME:hostname};%{INT:eoi:int};%{INT:ess:int};%{INT:mtype};%{Args:sql};%{Args:bindVariables}"]
}
date {
match => [ "sTime" , "UNIX_MS" ]
}
ruby {
code => "event['duration'] = event['eTime'] - event['sTime']"
}
}
if [type]=="12" {
grok {
patterns_dir => "./patterns"
match => [ "message" , ";%{Args:method};%{INT:traceID:int};%{INT:sTime:int};%{INT:eTime:int};%{HOSTNAME:hostname};%{INT:eoi:int};%{INT:ess:int};%{Args:logStack}"]
}
date {
match => [ "sTime" , "UNIX_MS" ]
}
ruby {
code => "event['duration'] = event['eTime'] - event['sTime']"
}
}
if [type]=="11" {
grok {
patterns_dir => "./patterns"
match => [ "message" , ";%{Args:method};%{INT:traceID};%{INT:sTime:int};%{INT:eTime:int};%{HOSTNAME:hostname};%{INT:eoi:int};%{INT:ess:int};%{Args:errorStack}"]
}
date {
match => [ "sTime" , "UNIX_MS" ]
}
ruby {
code => "event['duration'] = event['eTime'] - event['sTime']"
}
}


if [type]=="50" {
grok {
patterns_dir => "./patterns"
match => [ "message" , ";%{INT:sTime:int};%{HOSTNAME:host};%{Args:JVMName};%{Args:GCName};%{INT:count:int};%{INT:time:int}"]
}
date {
match => [ "sTime" , "UNIX_MS" ]
}
}
if [type]=="51" {
grok {
patterns_dir => "./patterns"
match => [ "message" , ";%{INT:sTime:int};%{HOSTNAME:host};%{Args:JVMName};%{INT:maxheap};%{INT:currentheap};%{INT:commitheap};%{INT:iniheap};%{INT:maxnonheap};%{INT:currentnonheap};%{INT:commitnonheap};%{INT:ininonheap}"]
}
date {
match => [ "sTime" , "UNIX_MS" ]
}
}
if [type]=="52" {
grok {
patterns_dir => "./patterns"
match => [ "message" , ";%{INT:sTime:int};%{HOSTNAME:host};%{Args:JVMName};%{Args:iniloadedclasses};%{Args:currentloadedclasses};%{Args:iniunloadedclasses}"]
}
date {
match => [ "sTime" , "UNIX_MS" ]
}
}
}


output {
elasticsearch { host => "127.2.96.1"
protocol => "http"
port => "8080" }
stdout { codec => rubydebug
}
}

Regex for simply matching all words contains a certain subword in text

What is the regex for simply matching all words contains a certain subword in text( word and subword could be equal) ? I've done some searching but can't get a straight example of such a regex. This is for a program that I install so it has no bearing to any particular programming language and I can use only regex.


Example:


Word:



example



Text:



This is example. It is important that parents should set an example. examples help you to understand math.



Output words:



example, example, examples



MongoDB regex in Java cannot be parsed

I have the following filter for my mongodb:



"{'shortname': '/.*LKH.*/'}"


I use it with the following java code:



BasicQuery c = new BasicQuery(filter);
Iterable<Hospital> hospitals = template.find(c,Hospital.class);


I am getting no results, because of the surounding ' at the regular expression. If i execute the filter without the '' around the regex, i get results in mongodb. I tried different verisons but could not succeed. The filter i´m appliying must be generic, so i cannot have some parsing.


Has someone an idea how i can use a generic filter for MongoDB with the MongoTemplate in Java - or how i have to write my filter?


Thank you


How do I use the IsAlphabetic binary property in a Java regex match?

I'm using this pattern to check if a string starts with at least 2 alphabetic characters in front a colon:



string.matches("^\\p{IsAlphabetic}{2,}:")


but I get the following exception thrown at me:



java.util.regex.PatternSyntaxException: Unknown character property name {Alphabetic} near index 16
^\p{IsAlphabetic}{2,}:
^
at java.util.regex.Pattern.error(Pattern.java:1730)
at java.util.regex.Pattern.charPropertyNodeFor(Pattern.java:2454)
at java.util.regex.Pattern.family(Pattern.java:2429)
at java.util.regex.Pattern.sequence(Pattern.java:1848)
at java.util.regex.Pattern.expr(Pattern.java:1769)
at java.util.regex.Pattern.compile(Pattern.java:1477)
at java.util.regex.Pattern.<init>(Pattern.java:1150)
at java.util.regex.Pattern.compile(Pattern.java:840)
at java.util.regex.Pattern.matches(Pattern.java:945)
at java.lang.String.matches(String.java:2102)


even though the specification of the Pattern classes states:



Binary properties are specified with the prefix Is, as in IsAlphabetic. The supported binary properties by Pattern are



  • Alphabetic

  • Ideographic

  • Letter

  • ...



and the section Classes for Unicode scripts, blocks, categories and binary properties lists



\p{IsAlphabetic} An alphabetic character (binary property)



regex to match only local css files

I need to select local stylesheets from an html string in javascript, how can I turn the following into a regex: (file.indexOf('<link rel="stylesheet"') === 0) && (file.indexOf('href="http') === -1) ?


Locating a control inside ListView template field

I realize that this question may have been asked before... But I have a specific problem with this...


my code



foreach(ListViewItem item in listProducts.Items)
{
DropDownList dropList = listProducts.Items.FindControl("DropDownList1");
int SelectedID = Convert.ToInt32(listProducts.SelectedValue);
}
// now do something with that id...


The problem is that I lose the ID of the selected item from dropdown list once the foreach loop goes through the listview items...


I'm using this code in selectedindexchanged dropdown event to locate the desired ID and so that I may display the data to the user accordingly to what he selected from dropdown list...


So the idea is that when the user selects something from the drop down, i need to pick up the ID of the selected item and automatically display the product price when he selects it.


Can someone help me to solve this?


How to display an error message within the form

I have the following ASP.net page:



<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Tks.aspx.cs" Inherits="Dr.Tks" ValidateRequest="true" %>

<asp:TextBox ID="tbComments" ClientIDMode="Static" CssClass="tbTech" runat="server" TextMode="MultiLine" Columns="30" Rows="15"></asp:TextBox>
<asp:Button ID="SubmitForm" ClientIDMode="Static" runat="server" Text="Submit" OnClick="ValidateForm" CssClass="btnFancy orange logBtn btnLogIn lightLinks" UseSubmitBehavior="false" />


C#:



public void ValidateForm(object sender, EventArgs e)
{
try
{
string strTheBody = HttpUtility.HtmlEncode(tbComments.Text);
}
catch (Exception)
{
}
}


If I enter <script... in the textbox above, I get the following error:



Server Error in '/' Application.
--------------------------------------------------------------------------------
A potentially dangerous Request.Form value was detected from the client (tbComments="<script...").


How can I validate the textbox as I type, rather than display the default error message from ASP.net (which is not user friendly)


Creating a document with header using OpenXML SDK 2.5

I want to create a new document with headers and footers. This is the code I am trying but it is not showing any header in the document, whereas the body content is available.



using (WordprocessingDocument doc = WordprocessingDocument.Create(HttpContext.Current.Server.MapPath("~/QEC/Reports/reportXML.docx"), DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = doc.AddMainDocumentPart();

HeaderPart hdrPart = mainPart.AddNewPart<HeaderPart>();
hdrPart.Header = new Header();
Paragraph hdrPara = hdrPart.Header.AppendChild(new Paragraph());
Run paraRun = hdrPara.AppendChild(new Run());
paraRun.AppendChild(new Text("Hello"));

mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
Body body = mainPart.Document.AppendChild(new Body());
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text("Done"));

}

Sorting listview with values from dropdown asp.net

I have a listview which is populated from database and is manually binded in codebehind with BindGrid(). This works fine and gets all the right data.



SqlDataAdapter da = new SqlDataAdapter(query, constr);
DataTable dt = new DataTable();

da.Fill(dt);

listView.DataSource = dt;
listView.DataBind();


I have two dropdowns. One contains sorting through, ALL, Country, Price Low - High, Price High To Low.



<asp:DropDownList ID="DDLSorting" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DDLSorting_SelectedIndexChanged" >
<asp:ListItem Text="All" Value="All"></asp:ListItem>
<asp:ListItem Text="Country" Value="Country"></asp:ListItem>
<asp:ListItem Text="Price - Lowest to Highest" Value="PriceL"></asp:ListItem>
<asp:ListItem Text="Price - Highest to Lowest" Value="PriceH"></asp:ListItem>
</asp:DropDownList>


When Country is selected it should populate the second dropdown called ddlCountries with SELECT Distinct Countries otherwise it is disabled.



<asp:DropDownList ID="DDLCountries" runat="server" AutoPostBack="True" Enabled = "false" >
<asp:ListItem Text = "--Select Country--" Value = ""></asp:ListItem>
</asp:DropDownList>


Problems I am having:



  1. When I select anything from dropdown the listview doesn't rebind/refresh with the new sorted data? I have tried putting BindGrid(); in each of the if statement but that didn't work!

  2. Not sure of how to bind the countries when Country is selected to the second dropdown?


`



protected void ddlSorting_SelectedIndexChanged(object sender, EventArgs e)
{
string con = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlDataReader reader = null;
SqlConnection Con = new SqlConnection(con);
string query = string.Empty;
if (DDLSorting.SelectedValue == "All")
{
query = "SELECT * FROM Wines";
}
else if (DDLSorting.SelectedValue == "Country")
{
query = "SELECT DISTINCT Country FROM Wines";
DDLCountries.Enabled = true;
}
else if
{
query = "SELECT * FROM Wines ORDER BY price {0}";

if (DDLSorting.SelectedValue == "PriceL")
{
query = string.Format(query, "ASC");
}
else if(DDLSorting.SelectedValue == "PriceH")
{
query = string.Format(query, "DESC");
}
}

SqlCommand cmd = new SqlCommand(query, Con);
Con.Open();
BindGrid();
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}