text:
Q: Когда может пригодится пространство имен System.Reflection.Emit? Когда может пригодится пространство имен System.Reflection.Emit ?
Вроде, в .NET предусмотрены классы, которые позволяют генерировать динамически сборки на высокоуровневом языке.
Зачем погружаться в низкий уровень?

A: Существующие ответы несколько устарели. В дополнение к ним следует отметить, что в .NET Core и .NET 5+ возможности System.Reflection.Emit (SRE) ограничены по сравнению с .NET Framework/Mono: генерировать динамические сборки в памяти можно, но сохранить их в исполняемый файл нельзя. Это значит, что если кто-то хотел бы использовать SRE как основу для кодогенерации в своем компиляторе, эту идею придется отбросить в условиях современного .NET. Использованию SRE для генерации сериализаторов/мапперов это не мешает, разве что теперь динамическую сборку нельзя кэшировать между разными запусками программы - ее нужно всегда генерировать заново, даже для одного и того же типа. Если нужно сохранять динамическую сборку в файл, в качестве альтернативы можно использовать Mono.Cecil или System.Reflection.Metadata.
Кроме того, в C# недавно появился новый функционал для динамической генерации кода, Source generators. В некоторых случаях, когда обычно использовался SRE/CodeDom/T4, теперь можно попробовать его.

A: Как уже сказано в предыдущем ответе, существует несколько способов кодогенерации. Часть из них позволяют генерировать код в дизайн-тайме, т.е. в IDE (T4). Другая - генерировать C# код во время исполнения (CodeDom), а третья - генерировать исполняемый код (т.е. IL) во время исполнения (Reflection.Emit).
И хотя может показаться, что последний случай довольно редкий, но это не так. Даже не задумываясь, вы этим делом пользуетесь постоянно.
Компилируемые регулярные выражения
Да, если вы создаете регулярное выражение следующим образом: var regex = new Regex("abc", RegexOptions.Compiled);, то среда исполнения сгенерирует класс со специализированным конечным автоматом с помощью Reflection.Emit, а не будет интерпретировать регулярное выражение каждый раз.
Сериализаторы
Да, большинство сериализаторов используют отражение, но это весьма медленная штука. Поэтому тот же XmlSerializer сгенерирует специальный класс сериализатора во время исполнения и сохранит его в специальной папке для последующего использования. Этот же подход используется и бинарным сериализатором, да и любимый всеми Newtonsoft.Json не брезгует кодогенерацией.
PostSharp и прочие AOP
Например, мы хотим сделать ран-тайм декоратор для логгирования. Если у нас есть виртуальный метод, помеченный атрибутом [LogMethod], то мы можем сгенерировать класс наследника, который переопределит этот виртуальный метод и будет логировать все аргументы метода, а уже потом вызывать базову реализацию.
Постшарп и другие AOP фреймворки построены непосредственно на технологии генерации кода во время исполнения.
Деревья выражений
Да, Expression Trees в C# - это высокоуровневая конструкция, но метод Expression.Compile на самом деле использует Reflection.Emit для генерации кода во время исполнения.
Object-to-object mappers
Всякие Automapper-ы используют Reflection.Emit для генерации соответствия между отображением экземпляров одного типа в другой.
ORM
Это частный случай мапперов и в них используется кодогенерация по полной программе. NHibernate, LINQ 2 SQL, Entity Fraework, все они генерируют классы во время исполнения для маппинга объектов друг на друга или для перехвата вызовов метода репозиториев.
Mock frameworks
Rhyno Mocks, Moq и другие, все они основаны либо на Expression Trees либо напрямую на Reflection.Emit-е (да, многие mock framework-и используют DynamicProxy, который уже использует Reflection.Emit) для генерации заглушек при тестировании.
WCF и прочие коммуникационные штуки
Да, и в них тоже генерируются различные прокси классы для инспекции вызовов и другой инструментации во время исполнения.
Application Insights и прочие логгеры/анализаторы
И снова, для того, чтобы сделать процесс логгирования наиболее простым, в подобных инструментах используется кодогенерация.
DLR - Dynamic Languagage Runtime
В CLR есть специальная функциональность для взаимодействия с динамически типизированными языками, типа Python, Ruby etc. Там на полную катушку используется DLR для повышения производительности.
Вы не поверите, но вы можете использовать Reflection.Emit (хоть и косвенно) даже для обхода стандартных проблем языка C#.
Возможно вы знаете, что new T() ограничение для дженериков - это страх и ужас. Там используется отражение, что серьезно сказывается на производительности, да еще и заворачивает исключения, возникшие при создании экземпляра, в TargetInvocationException. Я уже в нескольких проектах сталкивался, что этот метод существенно портит end-to-end время исполнения. Поэтому в этих проектах используется специализированный CustomActivactor:
public static class CustomActivator
{
    public static T CreateInstance<T>() where T : new()
    {
        return ActivatorImpl<T>.Factory();
    }

    private class ActivatorImpl<T> where T : new()
    {
        // Под колпаком используем Reflection.Emit!
        private static readonly
            System.Linq.Expressions.Expression<Func<T>> _expr = () => new T();
        public static readonly Func<T> Factory = _expr.Compile();
    }
}

Теперь наш активатор не страдает от проблем с производительностью и не оборачивает исключения из конструкторов в занудный TargetInvocationExpression.
З.Ы. На самом деле, я коснулся лишь части сценариев, тот же ASP.NET использует кодогенерацию по полной. Чтобы понять всю полноту картины можно попробовать поискать самому. Например, можно поискать тип ILGenerator или что-то еще из пространства имен System.Reflection.Emit:

*

*На гитхаб: найдено 40К ссылок на ILGenerator (там нет семантического поиска, поэтому многие ссылки будут не валидными, но дадут понять масштаб трагедии).

*в сорцах МС-а: десятки ссылок и примеров использования, большую часть которых я привел ранее.

UPDATE: данная тема вылилась в довольно длинный пост, посвященный тонкостям работы активатора, обобщений и кодогенерации - Dissecting the new() constraint in C#: a perfect example of a leaky abstraction.

A: Reflection.Emit — это для тех, кто хочет создавать динамические сборки (а не добавлять что-то в существующие) на чистом IL (хардкор короче). Подробнее ниже.
А может вам надо что-то другое и желательно попроще?

*

*Если вам просто нужен динамический тип, может вам просто подойдёт dynamic или ExpandoObject? И никакой генерации кода, правда о проверке на этапе компиляции можно забыть.

*Вам нужен метод (может также их группа), который будет принимать и анализировать лямбда выражения? Тогда используйте Expression Trees. Для простых случаев будет хорошо, но если вы надумали написать свой ORM, то это занятие совсем не из простых. При этом помните, что для Expression Trees поддерживаются только однострочные лямбда-выражения.

*Если вам нужен динамически генерируемый HTML (вдруг), а это не веб-приложение, то используйте RazorEngine. Также симулируя веб-приложение, можно добавить поддержку Intellisense.

Генерация кода
Если вкратце: если вам нужна всё же полноценная генерация кода, то используйте Roslyn. Потому что мощный и платформенно независимый. Возможно также будет полезен T4 (особенно если нужен не-C# и не-VB код).
Преимущества и недостатки Reflection.Emit
Преимущества

*

*создание динамической сборки на чистом IL: вы полностью контролируете код и можете писать высоко оптимизированный код. Преимущество тут ещё в том, что если есть какая-то возможность недоступная в C#, но доступная в CLR, вы тоже сможете её задействовать.

*хорошая производительность генерации кода. Созданный вами код сразу компилируется в сборку (в отличие от Microsoft.CodeDom, но c Roslyn всё хорошо, ибо он дёргает компилятор как сервис).

*платформенно-независимый подход (в отличие от Microsoft.CodeDom, который специфичен только для реализации Microsoft, но Roslyn тоже платформенно независим)

Недостатки

*

*приходится прописывать простейшие вещи вроде циклов (просто серия переходов). Вам приходится думать на низком уровне. Поэтому сложно создавать нетривиальные программы.

*вы обязаны генерировать новую сборку. Если вам это подходит, то это не недостаток. Но если вы хотите что-то добавить в существующую, то это невозможно средствами Reflection.Emit.

Исходя из этого решайте применять вам Reflection.Emit или нет. Но я полагаю, что это совсем хардкор.
Альтернативы

*

*Microsoft.CodeDom

*Roslyn

*T4

Microsoft.CodeDom vs Reflection.Emit
Способы программирования
Сгенерированный код с помощью Microsoft.CodeDom может быть частью решения (классы LINQ to SQL, WSDL, XSD сгенерированы таким способом). Вы также можете использовать partial классы для настойки сгенерированного кода. Когда используете Reflection.Emit вы обязаны создавать новую сборку.
Когда вы используете Reflecion.Emit вы программируете с помощью IL-команд. Когда вы программируете c помощью Microsoft.CodeDom вы создаёте команды C#.
Поэтому код Microsoft.CodeDom будет проще создавать, так вы программируете более высокоуровневыми командами. Код созданный на Reflecion.Emit будет сложней создать на IL (к примеру циклы надо будет создавать с помощью переходов), особенно когда вы программируете сложную логику.
Из этого следует, что возможностей на Reflection.Emit больше (так у IL больше возможностей, чем у C#). Однако для каждой привычной вещи на C# придётся писать намного больше кода.
Производительность
Код Microsoft.CodeDom будет медленней, чем Reflection.Emit, так как он компилируется, затем генерируется C#-код, затем этот сгенерированный код компилируеся. Reflection.Emit сразу компилируется в сборку.
Платформенная (не)зависимость
Как верно заметил @Grundy это платформенная независимость для Reflecion.Emit. А Microsoft.CodeDom доступен только на платформах от Microsoft.
Roslyn (основано на вопросе)
Однако я бы не использовал Microsoft.CodeDom. Ибо Roslyn мощней и выразительней.

*

*Roslyn есть на Mono (платформенно-независимый).

*Roslyn в отличии от Microsoft.CodeDom не просто является обёрткой на csc.exe, а может также анализировать код семантически, динамически компилировать и разбирать код. Это способ создавать любой инстумент для C# и VB. Поэтому есть возможности от форматирования код до нахождения всех ссылок в решении для данного символа.

T4
А что если вам не надо динамически генерируемую сборку, а нужно дополнить часть существующего решения?
Или если надо динамически сгенерированные файлы, но не C# или VB? К примеру, скажем JavaScript или CSS. (Для HTML рекомендую RazorEngine если что, но с помощью T4 тоже можно). Или вообще какого-то экзотического расширения. И ещё, усугубив задачу, этих файлов надо несколько, но количество известно только в момент исполнения кода.
Тогда вы можете использовать T4.
Это инструмент в Visual Studio (или просто консольная утилита), который используется для генерации кода любого языка. Также доступен и в MonoDevelop.
Сразу скажу, что Entity Framework (не .NET Core) использует T4.
Концептуально похоже на ASPX, только код между C#-вставками <# #> не обязательно HTML/CSS/JavaScript, а на языке программирования целевого файла. Мануалы.
Из минусов

*

*Нет встроенной поддержки подсветки синтаксиса и Intellisense в Visual Studio, поэтому приходится либо привыкать, либо устанавливать третьесторонние плагины для Visual Studio.


text:
Q: if(objc_getAssociatedObject(self, &Key)) return true for nil object How can I test that objc_getAssociatedObject is nil? The following says element is not nil but the associated object has never been set before nor been accessed.
static char orderedElementKey = 11;

if (objc_getAssociatedObject(self, &orderedElementKey) != nil)
{
    NSLog(@"element is not nil");
    return objc_getAssociatedObject(self, &orderedElementKey);
}
NSLog(@"elelement was nil !");

A: static char orderedElementKey = 11;
//objc_setAssociatedObject(self, &orderedElementKey, @"value", OBJC_ASSOCIATION_RETAIN);

if (objc_getAssociatedObject(self, &orderedElementKey) != nil)
{
    NSLog(@"Element: %@", objc_getAssociatedObject(self, &orderedElementKey));
}
else
{
    NSLog(@"element nil !");
}

prints "Element nil !" while removing the comment on objc_setAssociatedObject() prints "Element: value". How is your code different?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Show that the collection $\tau^*=\{(a,b]:a,b\in \mathbb{R},aShow that the collection $\tau^*=\{(a,b]:a,b\in \mathbb{R},a<b\}$ is a basis for a topology in $\mathbb{R}$.Help me on this.Thank you very much in advance..

A: Think about the properties that a basis for a topology in $\mathbb{R}$ must satisfy. For the intersection, you can prove it by cases.


text:
Q: Sending hidden input field values comes back null I have one input field that is hidden.  I'm using it as a placeholder to send the value to a scriptlet.  Like below, but the value of the hidden field is always null.  When I remove the hidden tag everything works correctly.
  <form method=post action="test.jsp">

  <input type="hidden" name="name" id="name" >

  <button class="button primary" type="submit">Submit</button></form>

Then in scriplet getting the value, but it is nullpointer exception
           <%
            String x = null;

            x  = request.getParameter("name");

            %>

A: You should specify a value for your input hidden field. Something like:
<input type="hidden" name="country" value="Norway">

Try it

A: It should come, only disabled fields data u will not getting in req.getParameters()
u missed value attribute


text:
Q: UI changes with ObservableObject just after switching tabs I have a ObservableObject that I use to update my UI when new data is sent from the server (an a class which contains an array of custom structs).
For some reason, when the data is sent, the ContentView's body is called, but the data isn't changed. I even added a print statement to check if the data that the array contains is right and it is.
When I try to switch to another tab on my TabView, and then switch back to the main view, the UI does get updated. Does anybody know why the UI updates just when I switch tabs, although the body gets recalled to update the UI when the data changed?
HomeView
struct HomeView: View {
    @ObservedObject private var fbData = firebaseData

    var body: some View {
        TabView {
            //Home Tab
            NavigationView {
                ScrollView(showsIndicators: false) {
                    ForEach(self.fbData.posts.indices, id: \.self) { postIndex in
                        PostView(post: self.$fbData.posts[postIndex])
                            .listRowInsets(EdgeInsets())
                            .padding(.vertical, 5)
                    }
                }
                .navigationBarTitle("MyPhotoApp", displayMode: .inline)
                .navigationBarItems(leading:
                    Button(action: {
                        print("Camera btn pressed")
                    }, label: {
                        Image(systemName: "camera")
                            .font(.title)
                    })
                , trailing:
                    Button(action: {
                        print("Messages btn pressed")
                    }, label: {
                        Image(systemName: "paperplane")
                            .font(.title)
                    })
                )
            } . tabItem({
                Image(systemName: "house")
                    .font(.title)
            })

            Text("Search").tabItem {
                Image(systemName: "magnifyingglass")
                    .font(.title)
            }

            Text("Upload").tabItem {
                Image(systemName: "plus.app")
                    .font(.title)
            }

            Text("Activity").tabItem {
                Image(systemName: "heart")
                    .font(.title)
            }

            Text("Profile").tabItem {
                Image(systemName: "person")
                    .font(.title)
            }
        }
        .accentColor(.black)
        .edgesIgnoringSafeArea(.top)
    }
}

FirebaseData:
class FirebaseData : ObservableObject {
    @Published var posts = [Post]()

    let postsCollection = Firestore.firestore().collection("Posts")

    init() {
        self.fetchPosts()
    }

    //MARK: Fetch Data
    private func fetchPosts() {
        self.postsCollection.addSnapshotListener { (documentSnapshot, err) in
            if err != nil {
                print("Error fetching posts: \(err!.localizedDescription)")
                return
            } else {
                documentSnapshot!.documentChanges.forEach { diff in
                    if diff.type == .added {
                        let post = self.createPostFromDocument(document: diff.document)
                        self.posts.append(post)
                    } else if diff.type == .modified {
                        self.posts = self.posts.map { (post) -> Post in
                            if post.id == diff.document.documentID {
                                return self.createPostFromDocument(document: diff.document)
                            } else {
                                return post
                            }
                        }
                    } else if diff.type == .removed {
                        for index in self.posts.indices {
                            if self.posts[index].id == diff.document.documentID {
                                self.posts.remove(at: index)
                            }
                        }
                    }
                }
            }
        }
    }

A: Your code example doesn't help to find the bug. Finally I've got how to demonstrate it. First, do it the "proper way" (copy - paste - try it yourself)
import SwiftUI

struct Data: Identifiable {
    let id = UUID()
    let text: String
}
class Model: ObservableObject {
    @Published var data: [Data] = [Data(text: "alfa"), Data(text: "beta")]
 }

struct ContentView: View {
    @ObservedObject var model = Model()
    var body: some View {
        TabView {
            View1(model: model).tabItem {
                Text("View 1")
            }
            View2(model: model).tabItem {
                Text("View 2")
            }
        }
    }
}

struct View1: View {
    @ObservedObject var model: Model
    var body: some View {
        VStack {
            Text("View 1").font(.largeTitle)
            DataView(data: model.data)
            Button(action: {
                self.model.data.append(Data(text: String("ABCDEFGH".shuffled())))
            }) {
                Text("Add random data")
            }
        }
    }
}
struct View2: View {
    @ObservedObject var model: Model
    var body: some View {
        VStack {
            Text("View 2").font(.largeTitle)
            DataView(data: model.data.filter({ (item) -> Bool in
                item.text.count < 4
                }))
                // to distinguish from other DataView !! it seems to be a bug in SwiftUI
                // try to remove it to see the difference
                .id("view2")
            Button(action: {
                self.model.data.append(Data(text: String("ABC".shuffled())))
            }) {
                Text("Add random data")
            }
        }
    }
}

struct DataView: View {
    var data: [Data]
    var body: some View {
        List {
            ForEach(data) { (item) in
                Text(item.text)
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

I works as it should, you can modify the data from each tab, you see refreshed data, etc.

removing "fixed - user defined" .id modifier, it changes the behaviour dramatically

This looks like a serious bug in SwiftUI ...

A: I think is SwiftUI bug. I solve this problem like this.
Instead of rendering your PostView(post: self.$fbData.posts[postIndex])
implement post view inside ForEach.
ForEach(self.fbData.posts.indices, id: \.self) { postIndex in
   Text(self.$fbData.posts[postIndex].comment)
   Text(self.$fbData.posts[postIndex].date)
   ....
}


text:
Q: Move :after element onto new line on text truncation I am building a table that has truncated headers and content using the :after selector.
I want to be able to move the :after content onto a new line only where the header text is truncated, is there a way of doing this only using CSS?
I am currently using jQuery and window.resize listeners to implement a solution similar to the one found here: HTML - how can I show tooltip ONLY when ellipsis is activated but would prefer to be able to do it without the extra overhead of the jQuery and the listeners
An example of the HTML and CSS is:

        I'm a very long table header that is going to get truncated in the browser
        small
        medium
        large

        1
        One
        Java
        01/01/2010

        2
        Two
        C
        01/02/2010

A: If you want your :after element content should come on next line then try following code.
th:after {
    content: ":";
    display:block;
    clear:both:
}


text:
Q: How to force the application to stop until an operation finish? I have an application that require a lot of compilations .Therefore,I need the application to wait until the operation ends .To be more specific , I work on Tkinter and Canvas.So,when I want to move an item it takes some seconds to do so and the widget would not respond .
Thanks for advance .


text:
Q: Why is a `catch` block called if there is no `throw`? The following:
catch :something do
  print true
end

will print true to the console. I thought the point of catch was that it was only called by a corresponding throw.
Less importantly, is there a one liner syntax? I was surprised that catch :something { print true } raises a SyntaxError.

A: *

*Why is a catch block called if there is no throw?
Perhaps there was throw before, and the programmer forgot to delete catch together when throw was deleted, or doesn't know how to use catch.
But more likely in this case is that you failed to ask "why is a catch block executed if there is no throw?" The answer to that question is that catch block is executed to the point a throw is raised. If throw is not raised, then the catch block will be fully executed.

*Is there a one liner syntax?
Yes. Don't omit the parentheses.
catch(:something){print true}


text:
Q: Bootstrap PHP Form Not Sending I am trying to create a very simple contact form for my personal website. This form worked perfect for another website I did so I'm not sure what the problem is here. I've spent the last few hours trying to figure it out and dipping into other form tutorials so its strayed from the original code. I guess the biggest difference between this and the other website is that this is in bootstrap.
I have three problems with this.
1) Is there anyway not to jump up to the top of the screen when I submit the form? I believe this has something for making the action the page itself.
2) Is there any way to not need the 'subject' variable for the mail function? I'd love to not have the subject input on my form.
3) The biggest problem is that while the form runs, I have not received any emails from the form.
The php before html on same doc:
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$human = intval($_POST['human']);
$from = 'Contact Form';
$to = 't*************@gmail.com';
$subject = $_POST['subject'];

$body ="From: $name\n E-Mail: $email\n Message:\n $message";
// Check if name has been entered
if (!$_POST['name']) {
  $errName = 'Please enter your name';
}

// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'],
FILTER_VALIDATE_EMAIL)) {
  $errEmail = 'Please enter a valid email address';
}

//Check if message has been entered
if (!$_POST['message']) {
  $errMessage = 'Please enter your message';
}
//Check if simple anti-bot test is correct
if ($human !== 5) {
  $errHuman = 'Your anti-spam is incorrect';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage && !$errHuman) {
if (mail ($to, $subject, $body, $from)) {
$result='
Thank You! I will be in
touch
';
} else {
$result='
Sorry there was an error
sending your message. Please try again later.
';
}
}
}
?>

The html/form:
 <form class="form-horizontal" role="form" method="post"
 action="pauline.php">

 Name

      <input type="text" class="form-control" id="name" name="name"
 placeholder="First & Last Name" value="<?php echo
 htmlspecialchars($_POST['name']); ?>">
      <?php echo "
$errName
";?>

    Email

      <input type="email" class="form-control" id="email"
name="email" placeholder="example@domain.com" value="<?php echo
htmlspecialchars($_POST['email']); ?>">
      <?php echo "
$errEmail
";?>

    Subject

      <input type="text" class="form-control" id="subject"
name="subject" placeholder="Message Subject" value="<?php echo
htmlspecialchars($_POST['subject']); ?>">
      <?php echo "
$errSubject
";?>

    Message

      <textarea class="form-control" rows="4" name="message"><?php
 echo htmlspecialchars($_POST['message']);?></textarea>
      <?php echo "
$errMessage
";?>

    2 + 3 = ?

      <input type="text" class="form-control" id="human"
 name="human" placeholder="Your Answer">
      <?php echo "
$errHuman
";?>

      <input id="submit" name="submit" type="submit" value="Send"
  class="btn btn-primary">

      <?php echo $result; ?>

  </form>

A:
1) Is there anyway not to jump up to the top of the screen when I submit the form? I believe this has something for making the action the page itself.

Because you're posting to the page and not providing a redirect, you'll always refresh the page, and you'll always reload the page at the top first. You could provide a Javascript function to scroll to a certain point, or redirect to an anchor tag on the page (though this would involve an unnecessary reload the way you're running it).

2) Is there any way to not need the 'subject' variable for the mail function? I'd love to not have the subject input on my form.

Sure! You can hardcode a subject into your PHP. Just replace your $subject = $_POST['subject']; with $subject = 'Message From Site'. Then remove the input from your form. You've already done this with your $from variable.

3) The biggest problem is that while the form runs, I have not received any emails from the form.

This is a more difficult issue. Emails from PHP scripts can be difficult to get through email provider spam filters. You may need to set some configuration or set specific headers in order to get emails sent to you.The mail() function accepts a set of headers as the fourth parameter, not just a "From" value - tweaking that may help. You can find TONS more info on debugging options aon the PHP docs, located here: http://php.net/manual/en/function.mail.php

A: I have your issues resolved with example code. See code comments for exact edits

*

*This is just a matter of setting an anchor to jump the back page
down on load

*Just set the subject to a blank, and not
have any html for the subject

*This was fixed on its own by cleaning up your undefined errors. Note
the issets() I used with shorthand if statements $if?$then:$else to define the variables as blank if there is nothing coming
from $_POST

I recommend you take care of your format needs on top to keep your code as organized as you can. Also use the variables you defined as opposed to calling $_POST repeatedly like your example.
 <?

    $name = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ""; ### shorthand if statements
    $email = isset($_POST['email']) ? htmlspecialchars($_POST['email']) : "";
    $message = isset($_POST['message']) ? htmlspecialchars($_POST['message']) : "";
    $human = isset($_POST['human']) ? intval($_POST['human']) : -1;
    $from = 'Contact Form';
    $to = 't*************@gmail.com';
    $subject = ""; ### send a blank subject. issue 2 solved
    $body = "From: $name\n E-Mail: $email\n Message:\n $message";
    $errName = $errEmail = $errMessage = $errHuman = $result = ""; ### defining these all as blank to stop the undefined error.

    if (isset($_POST["submit"])) {

        // Check if name has been entered
        if (!$name) {
            $errName = 'Please enter your name';
        }

        // Check if email has been entered and is valid
        if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errEmail = 'Please enter a valid email address';
        }

        //Check if message has been entered
        if (!$message) {
            $errMessage = 'Please enter your message';
        }
        //Check if simple anti-bot test is correct
        if ($human !== 5) {
            $errHuman = 'Your anti-spam is incorrect';
        }
        // If there are no errors, send the email
        if (!$errName && !$errEmail && !$errMessage && !$errHuman) {
            if (mail($to, $subject, $body, $from)) {
                $result = '
Thank You! I will be in
            touch
';
            }
            else {
                $result = '
Sorry there was an error
            sending your message. Please try again later.
';
            }
        }
    }
?>
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

<form class="form-horizontal" role="form" method="post"
      action="pauline.php#submit">

        Name

            <input type="text" class="form-control" id="name" name="name"
                   placeholder="First & Last Name" value="<?php echo $name; ?>">
            <?php echo "
$errName
"; ?>

        Email

            <input type="email" class="form-control" id="email"
                   name="email" placeholder="example@domain.com" value="<?php echo $email; ?>">
            <?php echo "
$errEmail
"; ?>

        Message

            <textarea class="form-control" rows="4" name="message">
                <?php echo $message; ?>
            </textarea>
            <?php echo "
$errMessage
"; ?>

        2 + 3 = ?

            <input type="text" class="form-control" id="human"
                   name="human" placeholder="Your Answer">
            <?php echo "
$errHuman
"; ?>

            <input id="submit" name="submit" type="submit" value="Send"
                   class="btn btn-primary">

            <?php echo $result; ?>

</form>


text:
Q: How to create Encryption Key for Encryption Algorithms? I want to use encryption algorithm available in .Net Security namespace, however I am trying to understand how to generate the key, for example AES algorithm needs 256 bits, that 16 bytes key, and some initialization vector, which is also few bytes.

*

*Can I use any combination of values in my Key and IV? e.g. all zeros in Key and IV are valid or not? I know the detail of algorithm which does lots of xors, so zero wont serve any good, but are there any restrictions by these algorithms?

*Or Do I have to generate the key using some program and save it permanently somewhere?
I want to store data in database after encryption, the secure profile data like username, password, phone number etc, and the key will be available to database user mentioned in connection string only, and to the administrator.

A: Use System.Security.Cryptography.RandomNumberGenerator to generate random bytes:
var rnd = new System.Security.Cryptography.RandomNumberGenerator.Create();
var key = new byte[50];
rnd.GetBytes(key);

A: You really ought to do this the correct way :)
1) Use a securely generated random IV
2) Use a securely generated random key
3) Don't use ECB mode - EVER
AesManaged aes = new AesManaged();
aes.GenerateKey();
aes.GenerateIV();

The code above will correctly and securely generate a random IV and random key for you.

A: Sounds like you need to read into the Rfc2898DeriveBytes class.
Rfc2898DeriveBytes.GetBytes();

It has a method(above) that allows you to tailor the size of byte arrays that are fed into the .Key and .IV properties on a symmetric encryption algorithm, simply by feeding an int value. The MS official 70-536 book suggests doing this pro-grammatically by dividing the KeySize property / 8.
I.e TripleDes or AESManaged. Whatever you use, the algorithm itself will have some pre-reqs that will need meeting first. I.e satisfying the key size conditions. The RunTime will automatically fill the properties and fields and etc the best and most strongest values for you. But the IV and Key needs to come from you. This how you can do the following:
RijndaelManaged myAlg = new RiRijndaelManaged();
byte[] salt = Encoding.ASCII.GetBytes("Some salt value");
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes("some password", salt);
myAlg.Key = key.GetBytes( myAlg.KeySize / 8);
myAlg.IV  = key.GetBytes( myAlg.BlockSize / 8);
// myAld should now fully set-up.

Above you can see what I mean by doing it pro-grammatically, as it should pretty much
do it all for you, without you even really having to bat an eye-lid as to meeting it's pre-reqs.
The Microsoft 70-536 book states that the .Key properties expect the byte arrays you supply
to them in bytes and not bits. The RFC class works in bytes where as an algorithms KeySize property works in bits. 1 byte = 8 bits. Can you see where this is going ... ?
This should give you an idea as to why the above sample peice of code is done the way it is! I studied it and it makes pretty darn good sense to me!
The above answer should allow you to create your algorithm object with supplied password and a static salt value that can be hard code at both ends. Only thing you need to do is worry about how you going to make sure that the byte arrays stored at .Key and .IV are safely transported to a recipient so that can successfully decrypt the message you encrypted. By safely reconstructing the same algorithm object.
OBTW:
AESManaged has a keysize req': 128Bits = 16 Bytes !!!
(8*8 = 64, 64Bit / 8bits per Byte = 8 Bytes) Therefore
64*2 = 128Bit, 8*2, ==> 16bytes key size !
256Bit = 32Bytes !!!!

According to the 70-536 official training kit book, Aes is limited to having keysize of 128bits in size. 256bits,192 and 128 key size for example can be used with the Rijndael class.

You could on the other hand completely forget all that crap and simply use .GenerateKey and GenerateIV methods instead  to save you all the hassle of sorting out a pre-shared and agreed password and static salt values. Your only concern is figuring out a way of storing and retrieving the key and IV byte arrays. Binary Formatter?                .

A: If you are using encryption to exchange data then you will need a key exchange protocol, but you don't make one yourself instead use one off-the-shelf like TLS or SSL.
If you use encryption to store data then you generate the IV using CryptGenRandom (or its .net equivalent RandomNumberGenerator.GetBytes) and save it along the document (in clear, no need to protect the IV). You never write down the key, the key is provided by the user. Usualy you derive the key from a password phrase using CryptDeriveKey, or its .Net equivalent PasswordDeriveKey.CryptDeriveKey.
Update
To store a secret in the database that is available only to the user and an administrator you need to use 3 keys:

*

*one to encrypt the data with (call it the DK key)

*one user key to encrypt the DK key (call it UK)

*one administrator key to encrypt the DK key (call it AK)

In theory you encrypt the data with DK and then encrypt the DK with UK and save it, and encrypt the DK with AK and save it. This way the user can use again the UK to decrypt the DK and then decrypt the data, and the administrator can use the AK to decrypt the DK and then decrypt the data. The big problem is the fact that the system is always automated, so the system needs access to the administrator's key which means is not truly a persnal key of the administrator, but instead is a system key (it cannot be used for purposes of non-repudiation for instance).
As a heads up, knowledge of what IV is or how to use AES from C# and how cryptography algorithm work will get you exactly 0 (zero) traction in solving this kind of problems. The issue is never what IV and key to use, the issue is always key provisioning. For actual crypto operations, just use the built-in support from the database, see Cryptography in SQL Server. I can easily argue that the only facility you need is TDE (Transparent Data Encryption) to protect against accidental loss of media.

A: Generate a random letters / hex code in a specific length.
This function (taken from here) return a random key in a specific length:
private static string CreateSalt(int size)
{
    //Generate a cryptographic random number.
    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
    byte[] buff = new byte[size];
    rng.GetBytes(buff);

    // Return a Base64 string representation of the random number.
    return Convert.ToBase64String(buff);
}

A: It really depends on what you ned to do with the key.
If the key is to be generated by the computer (and can be any random value) I generally take a SHA256 of a couple GUIDs. This is about as random as you're going to get without a hardware random number generator.
You can use keys with all 0s but obviously it won't be very secure.


text:
Q: GCM push notification Server side for asp.net I am new to .net and using .net as a server side for GCM push notification. I am using the below code and it working fine for single user(for below regId).My question is how to save all reg-id's in our .net server? I don't know whether it save in our server or not.If not saving the registered-id's then how to send push notifications to all registered users?
    protected void Button1_Click(object sender, EventArgs e)
            {

                string regId = "APA91bFUgrdgtdgfdgxxxxxxxxxxxxxxxxxxxxxxxxxx6t1QDCn-4IiIAtvBhEt328QeYeLKoDeDFOgumrgACdydLCLvM0wM59nAzm_fZse3ta_A";

//server api key
                var applicationID = "AIzaSDGjvbnviiuteuoidsgdfsdryiIfgA";

                var SENDER_ID = "77xxxxxx25";
                var value = Label1.Text;  //message box label
                WebRequest tRequest;
                tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
                tRequest.Method = "post";
                tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
                tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));

                tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));

                // string postData = "{ 'registration_id': [ '" + regId + "' ], 'data': {'message': '" + txtMsg.Text + "'}}";
                string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + regId + "";
                Console.WriteLine(postData);
                Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                tRequest.ContentLength = byteArray.Length;

                Stream dataStream = tRequest.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();

                WebResponse tResponse = tRequest.GetResponse();

                dataStream = tResponse.GetResponseStream();

                StreamReader tReader = new StreamReader(dataStream);

                String sResponseFromServer = tReader.ReadToEnd();

                Label3.Text = sResponseFromServer;
                tReader.Close();
                dataStream.Close();
                tResponse.Close();

            }

Now i am getting push notifications in my android device like this and how to send or get text messages like "hii","test"... rather than "you got tickle".please help me..

A: That's a mistake in android side. Finally solved.


text:
Q: js passing this to onclick function throught listenner I linked a function to onclick event inside a listener but I can't access constructor context to call its argument events
export class VueMapComponent {
constructor(public geolocation: Geolocation, public events: Events) {}

google.maps.event.addListener(infoWindow, 'domready', () => {
        let element = document.getElementById('flash');
        element.onclick = this.funct_flasher;
    });

funct_flasher() {
    console.log("funct_flasher", "funct_flasher called");
    //this.events.publish('flash_sended'); // Problem can't access
}}

Can you explain to me what's wrong, please ?


text:
Q: Change email templates workflow notifications I'm trying to change the mail template of workflow notifications, and I also can change the template with the file wf-email.html.ftl of Data Dictionary.
But the subject "You have been assigned a task", I don't know how can I change this.
How can I do this?


text:
Q: How do i sum all numbers using loop? For Example, I have number 1 + 6 + 7 + 12 + 13 + 18+.....+ n (n is the input from users which represent the number of elements)  the index of this number starts from 1 by this it means that if the index is an odd number (1,3,5...) I want to increment the element at that index by 5 and if the index is an even number I want to increment the element at that index by 1 until I reach the of n number of elements. What I want is to sum all those numbers.
Sorry, It may hard to understand because of my poor English So let me write some of my C code here:
using namespace std;

  int i, n, result = 0;

  cout << "Input number to sum: ";
  cin >> n;

  // Finding result
  for (i = 0; i <= n; i++){
    if (i % 2 == 0) {
      result +=i;
    } else {
      result += i * 5;
    }
  }

  // Make last number have equal sign "1+6+7+12 = 36"
  for (i = 0; i <= n; i++){
    if (i == n) {
      cout << i..?? << "=";
    } else {
      cout << i..?? << "+";
    }
  }

  // Print result out
  cout << result;
  return 0;
}

A: Combine the computation with the output (I usually preach the opposite, but in this case it actually simplifies matters).
for (int i = 0; i <= n; i++)
{
    int value = i % 2 == 0 ? i + 1 : i + 5;
    cout << (i > 0 ? " + " : "") << value;
    result += value;
}
cout << " = " << result;

A: I agree with the molbdnilo that combining calculations and output in this case, simplify the code.
I don't agree with the algorithm, though, given OP's description.
In the following the calculations are repeated to output the result
#include <iostream>

int main()
{
    int n;
    std::cout << "Input number to sum: ";
    std::cin >> n;

    auto update = [] (int i) { return i % 2 == 0 ? 1 : 5; };

    int result = 0;
    int value = 0;
    for (int i = 0; i < n; i++)
    {
        value += update(i);
        result += value;
    }

    std::cout << '\n';
    for (int i = 0, value = 0; i < n; i++)
    {
        value += update(i);
        std::cout << (i > 0 ? " + " : "") << value;
    }
    std::cout << " = " << result;
}

Testable here.

A: I agree with molbdnilo's answer. However the algorithm some changes.

*

*The index starts from 1 , so value check for i in for loop should be
for (int i = 0; i < n; i++)

*while updating the values, increment should be done on value and not on i.
Here is my solution:
using namespace std;

int main()
{
    int i, n, result, value = 0;
    cout << "Input number to sum: ";
    cin >> n;

    for (i = 0; i < n; i++)
    {
        value = i % 2 == 0 ? value + 1 : value + 5;
        cout << (i > 0 ? " + " : "") << value;
        result += value;
    }
    cout << " = " << result;

    return 0;
}

Testable here


text:
Q: What does this Magento base js line mean? This line of javascript is in the Magento base code in app/design/frontend/base/default/template/persistent/checkout/onepage/billing.phtml:
        $('billing-address-select') && billing.newAddress(!$('billing-address-select').value);

Here is the line in context:
    <script type="text/javascript">
//<![CDATA[
var billing = new Billing('co-billing-form',
                          '<?php echo $this->getUrl('checkout/onepage/getAddress') ?>address/',
                          '<?php echo $this->getUrl('checkout/onepage/saveBilling') ?>');
var billingForm = new VarienForm('co-billing-form');

/*billingForm.setElementsRelation('billing:country_id',
                                  'billing:region',
                                  '<?php echo $this->getUrl('directory/json/childRegion') ?>',
                                  '<?php echo $this->__('Select State/Province...') ?>');*/

$('billing-address-select') && billing.newAddress(!$('billing-address-select').value);

var billingRegionUpdater = new RegionUpdater('billing:country_id',
                                             'billing:region',
                                             'billing:region_id',
                                             <?php echo $this->helper('directory')->getRegionJson() ?>,
                                             undefined,
                                             'billing:postcode');
if ($('onepage-guest-register-button')) {
    Event.observe($('onepage-guest-register-button'), 'click', function(event) {
        var billingRememberMe = $('co-billing-form').select('#remember-me-box');
        if (billingRememberMe.length > 0) {
            if ($('login:guest') && $('login:guest').checked) {
                billingRememberMe[0].hide();
            } else if ($('login:register') && ($('login:register').checked || $('login:register').type == 'hidden')) {
                billingRememberMe[0].show();
            }
        }
    });
}
//]]>
</script>

It looks like it's comparing two values but doing nothing with the comparison. What is the purpose of it?

A: I did some research on this. I thought the && was a purely logical "and", but it can also be used as a shortcut for "if then".
In this case, if $('billing-address-select') is true, the newAddress function (in opcheckout.js) will be called with "!$('billing-address-select').value" as an argument. It's a weird way to programmatically show or hide the new address form on one page checkout.
Here's a Stack Overflow question where this is explained: https://stackoverflow.com/questions/3859433/an-explanation-of-shorthand-in-javascript
And a good explanation of & vs &&:
https://stackoverflow.com/questions/7310109/whats-the-difference-between-and-in-javascript


text:
Q: hangman in vb trying to display correct leters and wrong ones with "*" I need help trying to create a hang man game. I somehow cant display correct letters properly.I'm using a intGuessed array and a word array. compare the two and display the correct letters and "*" for incorrect letters.
code:
    For I As Integer = 0 To 9
        Console.WriteLine("Enter a letter please: ")
        strInput = Console.ReadLine()
        Console.WriteLine()
        Console.WriteLine()
        If [Char].TryParse(strInput, charInput) Then
            For G As Integer = 0 To word.Length - 1
                Select Case strInput
                    Case word(G)
                        ReDim Preserve aryGuessed(G + 1)
                        If Not aryGuessed.Contains(charInput) Then
                            aryGuessed(intGuessed) = charInput
                            intGuessed += 1
                        End If
                        For A As Integer = 0 To aryGuessed.Length - 1
                            For B As Integer = 0 To word.Length - 1
                                If aryGuessed(A) = word(B) Then
                                    Console.Write(word(B))
                                End If
                            Next
                        Next
                        If G >= word.Length Then
                            Console.Write("correct")
                        End If
                    Case Else
                        Console.Write("*")
                        If G >= word.Length Then
                            bolwrong = True
                        End If
                End Select
                Console.WriteLine()
            Next
        End If
        If bolwrong = True Then
            intScore += 1
            Console.WriteLine("incorrect")
            Console.WriteLine("your score is now " + intScore.ToString())
            Console.ReadLine()
            bolwrong = False
        End If

    Next

A: Rather than looping lots, I would suggest the following code. I've shuffled things around a bit to make more sense, but the main changes are that I've created a string with the same number of '*' as the original word, and replaced a chunk of code with something simpler and more efficient.
ultimately most of your For .. Select Case .. End Case .. Next block can be replaced with ..
For G As Integer = 0 To word.Length - 1
    If word(G) = charInput Then
        guessedWord = guessedWord.Remove(G, 1).Insert(G, strInput)
        boolWrong = False
    End If
Next

And the guess/completion checking logic can be move toward the end of the outer loop.
This is what your final code would look like ..
Dim guessedWord As New String("*"c, word.Length)
For I As Integer = 0 To 9
    Console.WriteLine("Enter a letter please: ")
    strInput = Console.ReadLine()
    Console.WriteLine()
    Console.WriteLine()
    boolWrong = True
    If Char.TryParse(strInput, charInput) Then
        aryGuessed(I) = strInput
        For G As Integer = 0 To word.Length - 1
            If word(G) = charInput Then
                guessedWord = guessedWord.Remove(G, 1).Insert(G, strInput)
                boolWrong = False
            End If
        Next
        Console.WriteLine()
        Console.WriteLine(guessedWord)
        ReDim Preserve aryGuessed(aryGuessed.Count)
    End If
    If guessedWord = word Then
        Console.Write("Correct!")
        Exit For
    End If
    If boolWrong = True Then
        intScore += 1
        Console.WriteLine("incorrect")
        Console.WriteLine("your score is now " + intScore.ToString())
    End If
Next

Incidentally, this line
guessedWord = guessedWord.Remove(G, 1).Insert(G, strInput)

is a rather neat way of accomplishing the removal of a character and inserting a character all on one line
Its the same as writing
guessedWord = guessedWord.Remove(G, 1)
guessedWord = guessedWord.Insert(G, strInput)


text:
Q: Why can't a reference an old object when creating a new one In the Chrome dev console, if I do this:
obj1 = Object({"a":"b"})

I can do this:
obj1.a
// -> "b"

But I can't do this:
Object({obj1.a:"c"})
// -> throws "Uncaught SyntaxError: Unexpected token ."

Why?

A: Syntax error is because the object key cannot be directly evaluated in that notation. You'd have to do something like this:
obj2 = {};
obj2[obj1.a] = 'c';
obj2[obj1.a];

For more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
What is going on at a deeper level is the { } syntax is using an object initializer to construct the object. The property name of the syntax requires a name, a number, or a string literal. Evaluation of another object does not meet this requirement.

A: Because thats awkward syntax. Obj1.c inside your last line wony be evaluated as a variable. It only accepts property names. Obj1.c is not a valid name for a property


text:
Q: Netgear smart switches - how view MAC address of devices connected to each port? Im setting a VLAN on a remote site i do not easy have access to.
There are 3 switches daisy chained (Netgear GS716Tv3, Netgear GS105Ev2, Netgear GS108PEv3, and a router (Draytek 2860) forming the LAN.
Im familiar with the network typology in terms of which switch daisy chains into the router and into each other, but i don't know which ports are used, so i don't know which ports to make Trunk ports.
I have the MAC addresses of all the switches and the router, but i couldn't find a way to view all the ports on the switch and see their connected devices MAC.
Is that possible on the Netgear switches ?
I tried to go to System > Device View on the web GUI but it says i need a Java browser plugin to be installed and Chrome on OSX dosn't allow Java plugins, nor dose Firefox or Safari.
Im on Mac OSX so i cant install the Netgear Plus Configuration utility.

A: I can tell only about M4300-52G. Perhaps you can find MAC addresses of connected devices by the following path by the menu: Switching -> Address table. There is a filter by VLAN and some other options.


text:
Q: c# Disable ScrollWheel on Trackbar How can I disable the valuechange with mouse wheel on trackbars?
When scrolling down on the interface users can change trackbar values by mistake
I'm using Windows forms c#.
I couldn't find no property to stop this event..

A: I solved the issue with this:
With normal event declaration..
Control = new TrackBar();
Control.MouseWheel += Control_MouseWheel;
private void Control_MouseWheel(object sender, MouseEventArgs e)
{
     ((HandledMouseEventArgs)e).Handled = true;
}

Using anonymous method
var Control = new TrackBar();
Control.MouseWheel += new MouseEventHandler(delegate(object sender, MouseEventArgs e)
{
    ((HandledMouseEventArgs)e).Handled = true;
});

What it does is to prevent further execution..
Edit:
Using Labda expression as said by Sriram Sakthivel
Control.MouseWheel += (sender, e) =>((HandledMouseEventArgs)e).Handled = true;


text:
Q: popping up a modal based on user input I have user input forms where user can enter a number and if the number is less than zero or greater than 4 then the javascript alert pops up. I am trying to replace my javascript alert with a bootstrap modal.
I have added this boostrap modal to my html code that currently can be popped up using a button. But as I said I want to trigger the modal based on invalid user input (less than zero or greater than 4) rather than clicking on the button.
<input type="number" class="form-control" id=22 onkeyup="a(this)">
<button type="button" class="btn btn-primary" data-toggle="modal" datatarget=".bd-example-modal-sm">Small modal</button>

        ...

 function a(c){
    var valueStr = c.value;
    var value = parseFloat(valueStr)
    if ((event.keyCode||event.which) >= 48 && (event.keyCode||event.which) <= 90 ){
        if (value <= 0 && value >= 4) {
            alert("Value must be between 0 and 4");
        }

    }
}

What's the best way to do it?

A: <!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">

  <input type="number" class="form-control" id="22" onkeyup="a()" data-target="#myModal">

Modal Heading

          <button type="button" class="close" data-dismiss="modal">×</button>

Value must be between 0 and 4

          <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>


text:
Q: unit testing sockets in java I have a class which is a socket client and I am trying to unit test its methods.  The tests require that I start a socket server before each test so I use:
@Before
public void setUp() {
    if (myServerSocket == null) {
    Thread myThread = new Thread() {
        public void run() {
            DataInputStream dis = null;
            DataOutputStream dos = null;
            try {
                ServerSocket myServer = new ServerSocket(port);
                myServerSocket = myServer.accept();
                dis = new DataInputStream(myServerSocket.getInputStream());
                dos = new DataOutputStream(myServerSocket.getOutputStream());
                byte[] bytes = new byte[10];
                dis.read(bytes);
                boolean breakLoop = false;
                do {
                    if (new String(bytes).length() != 0) {
                        dos.writeBytes(serverMessage + "\n");
                        dos.flush();
                        breakLoop = true;
                        dos.writeBytes("</BroadsoftDocument>" + "\n");
                        dos.flush();
                    }
                } while (!breakLoop);
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    myThread.start();
    }
}

After each test I try to close the server socket so I can reopen the server socket for the next test:
@After
public void tearDown() throws IOException, BroadsoftSocketException {
    System.out.println("@After");
    if (myServerSocket != null) {
        myServerSocket.close();
        myServerSocket = null;
            try {
                Thread.sleep(5000);
            }
            catch (InterruptedException e) {
                // do nothing.
            }
    }
}

However, I get "java.net.BindException: Address already in use: JVM_Bind" before each test starting with the second test.  I realize I am trying to use the same port for each test but shouldn't closing the socket free up the port?

A: Quite possibly your socket is still in TIME_WAIT state when you attempt to reconnect it. I would recommend mocking such external dependencies, but if you really do find yourself wanting to continue using a real socket then try setting rebind options. In your setup function, instead of ServerSocket myServer = new ServerSocket(port); do :
final ServerSocket myServer = new ServerSocket();
myServer.setReuseAddress(true);
myServer.bind(new java.net.InetSocketAddress(port));

A: *

*You already close your serversocket in "setUp" and you really should do it in a finally block.

*The port may not be freed immediately. You can avoid this by setting the ServerSocket's reuseAdress to true. See setReuseAddress.

And I second SimonC: maybe you are better off avoiding the socket in the first place.


text:
Q: Разница в коммутации каналов, пакетов, сообщений Например я передаю файл используя модель OSI.
он должен пройти по всем 7ми уровням.
на канальном уровне коммутация каналов
на транспортном - пакетов
Как файл должен определить по какой технологии передаваться, и обязательно ли он должен использовать все 3 вида?
A: Файл - это уже абстракция файловой системы. Файл, это, фактически, отметка Ос самой себе, что вот эта вот кучка байтов, находящяяся на определенном треке\цилиндре жесткого диска, являются некоей отдельной сущностью, к которой может производиться обращение, как к логической (ну и физической, раз уж на то пошло), единице.
Файл вообще не решает как он будет передаваться.
Вы сами организуете передачу байт.
Если вы передаете файл используя определенное API (к примеру, сокеты там, или пайпы), то вы работаете на высоком уровне. Скорее всего ваши данные (из вашего файла) будут засунуты в tcp, потом в ip пакет, потом еще во что-то, и под конец уже в Ethernet Frame.   Ethernet Frame, в свою очередь, будет засунут целиком либо по частям, по DMA, в буфер вашей Ethernet-карты (x26 модема или что у вас там), либо по байтику будет запихиваться в соотв. регистры.  Запись в регистры будет инициировать возбуждение физических сигналов на выходах порта вашей сетевой карты.
Поэтому как айл будет передаваться, зависит только от Вас, того, какое API\технологию передачи данных вы используете.
Сокеты и прочие ребята - уже, как правило, высокий уровень абстракции, работающий "над" или "по") TCP\IP. А это уже протокол сами знаете какого уровня пакетной передачи данных.
Чтобы контролировать то что "ниже", нужно соотвественно и спускаться ниже, т.е. на уровень вызовов драйверов и иже с ним.


text:
Q: detect if user touch outside keyboard I implemented this function to detect touches outside keyboard and hide the keyboard
extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

but how can I do callback when a user touches outside the keyboard? I want another action to happen. I don't want only the keyboard to be hidden.I want to do other function including hiding keyboard everytime the keyboard is hidden I wa=ish to have more actions.

A: It's super easy. just need to create a function inside the viewcontroller that you want to call and add UIViewController.dismissKeyboard() in it
@objc func dismissKeyboardAndOtherStuff(){
 UIViewController.dismissKeyboard()
 // do other stuff

}
in you extension change the selector to reflect your new function
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboardAndOtherStuff))

A: I usually create an extension for this case:
extension UIViewController {
    func hideKeyboard() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

    func dismissKeyboard() {
        view.endEditing(true)
    }
}

Basically you add a gesture to the view
and you can call it from any ViewController like this:
hideKeyboard()


text:
Q: Glue vs Automapper vs Emit vs ValueInjecter entity mappers I'm working on a DDD project where a lot of field mapping is going on. I'm looking for a fast and solid mapping library as opposed to writing all the mappings by hand and there seems to be a lot of options out there.
At the moment I'm leaning more towards Glue as it looks to offer quite a bit of functionality and is also built with unit testing in mind which is also important to the project I'm working on. On the down side its only been downloaded 200+ times which leads me to think that something like ValueInjecter might be a better choice as there's more support out there for it.
My question is, is Glue better or worse than any of the other mappers out there? Or are the differences between the mappers mentioned above negligible in terms of performance and usability?

A: Personally I would go with either AutoMapper or ValueInjector. I have used both before and they are extremely fast and stable. Depending on your needs there are things that ValueInjector does that AutoMapper does not (like easily left to right and right to left mappings), so I suspect that ValueInjector may be the most suitable.
The statement about Glue being built with unit testing in mind this shouldn't really influence your decisions as you will most likely be using the assemblies via NuGet and thus using the complied assemblies rather than building from the source code.


text:
Q: How to create custom queries with spring data, hibernate, for mapped entities? What I want is a query similar to :
SELECT s FROM First s WHERE s.x = :x and s.secondId.thirdId.id = :id;

I am trying to migrate this to spring data.
I can't figure out what should be the methodname in my repository.
My entities :
First{
    int x;
    @JoinColumn(name = "second_id", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Second secondId;
}

Second{
    int id;
    @JoinColumn(name = "third_id", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Third thirdId;
    int c;
}

Third {
    int id;
    // more data here
    int b;
    int c;
}

I tried : findByThirdIdAndX(int id, xval);
getting :

Invalid derived query! No property thirdId found for type First

How can I achieve this?

A: thirdId is a property of secondId that is a property of First. This is how you would specify that:
findBySecondIdThirdIdIdAndX(int id, int xval);

Here is the relevant doc for nested properties.


text:
Q: Get HTML file produced by JavaDocs I understand that Javadoc is a documentation generator from Sun Microsystems for generating API documentation in HTML format from Java source code.
I infer that the documentation is stored onto an HTML file.
Is there a way I can access it?
If yes where is it stored?

A: The word Javadoc can refer to

*

*special comments in Java source files (preceding a declaration, and of the form /** ... */)

*a program which converts these comments (as well as the declarations themselves) to readable output

*the output itself, usually in HTML form.

The Javadoc program is contained in Sun's (or now Oracle's) Java Development Kit (JDK).
If you have installed a JDK (which you should if you do Java development), you can call it on the command line, passing it the package names to document, or some source file names. You should also indicate the output directory, using the -d option.
I'm assuming the following directory (and package) structure in my example below:

*

*current directory

*

*source

*

*de

*

*dclj

*

*paul

*

*examples

*

*HelloWorld.java  [containing package de.dclj.paul.examples; and public class HelloWorld { ... }]

*docs

Then you use the following command line:
javadoc -sourcpath source -d docs de.dclj.paul.examples

It will then create a the documentation in the docs directory, with an index.html which you can open in your web browser, and other files reachable from it.
For more details have a look at the documentation linked above. For an example output, have a look at the Java Standard API Javadoc.
If you are using an IDE, you likely have a generate Javadoc button there, and the IDE might even show the formatted output of documentation of single classes or methods on the fly.


text:
Q: Scala Spark udf java.lang.UnsupportedOperationException I have created this currying function to check for null values for endDateStr inside an udf, the code is as follows:(Type of col x is ArrayType[TimestampType]):
    def _getCountAll(dates: Seq[Timestamp]) = Option(dates).map(_.length)
    def _getCountFiltered(endDate: Timestamp)(dates: Seq[Timestamp]) = Option(dates).map(_.count(!_.after(endDate)))

    val getCountUDF = udf((endDateStr: Option[String]) => {
      endDateStr match {
        case None => _getCountAll _
        case Some(value) => _getCountFiltered(Timestamp.valueOf(value + " 23:59:59")) _
      }
    })
    df.withColumn("distinct_dx_count", getCountUDF(lit("2009-09-10"))(col("x")))

But I am getting this exception while executing:

java.lang.UnsupportedOperationException: Schema for type
  Seq[java.sql.Timestamp] => Option[Int] is not supported

Can anyone please help me to figure out my mistake?

A: You cannot curry udf like this. If you want curry-like behavior you should return udf from the outer function:
def getCountUDF(endDateStr: Option[String]) = udf {
  endDateStr match {
    case None => _getCountAll _
    case Some(value) =>
      _getCountFiltered(Timestamp.valueOf(value + " 23:59:59")) _
  }
}

df.withColumn("distinct_dx_count", getCountUDF(Some("2009-09-10"))(col("x")))

otherwise just drop currying and provide both arguments at the same time:
val getCountUDF = udf((endDateStr: String, dates: Seq[Timestamp]) =>
  endDateStr match {
    case null => _getCountAll(dates)
    case _ =>
      _getCountFiltered(Timestamp.valueOf(endDateStr + " 23:59:59"))(dates)
  }
)

df.withColumn("distinct_dx_count", getCountUDF(lit("2009-09-10"), col("x")))


text:
Q: ObservableCollection Clear How can i Clear ObservableCollection when i load new data
ObservableCollection<shared> newsData = new ObservableCollection<shared>();

When i click button to load new data i used this code
newsData.Clear();

but not working very well, i have 15 Buttons and every buton clik load new data , i tryed clean before load data but it is after several button clicks
can some one help me to how can clean old data complately when i click to button
thank you


text:
Q: IBM CDC - Data Replication for Kafka (customization on LiveAudit) We are using IBM AS400 as a source table. What I would like to do is:

*

*use descriptive column_name (like "Closing Price") instead of system_column_name ("CPHKD001")

*convert timestamp format "2020-03-10 18:25:31.123456000000" to "2020-03-10T18:25:31.123Z"

I think I should deal with the file KcopLiveAuditSingleRowIntegrated.java.  For the timestamp, it is likely to have the solution there, but I don't think I can find an answer there.

A: The KCOP infrastructure allows you programatic control over the Kafka producer record.  For each operation on the source you may determine how many messages are written to Kafka, which topics they go too, and what the key and value bytes are.
In the KCOP, you can redefine the timestamp to be any format you like with java. This is because each call to createProducerRecords provides you with a suggested Avro generic record that has a schema which allows you to identify the table, the columns, and their types.
As per the Avro Generic Record behaviour, documented in the open source Avro documentation, you could then select the relevant values you were interested in and create a new Avro generic record with the transformed values.  Then pass this new Avro Generic Record onto the rest of the KCOP.
Note that the audit KCOPs include code that does this, the single row Avro audit KCOP is a good example.  You can find the code for all of our integrated KCOPs in the samples.jar file of your product install.
The single row Avro audit KCOP takes the before and after Avro generic records, and produces a new Avro Generic record that is a composite of them.  If, while you were copying values, you checked the type of column, you could identify timestamp ones and alter the value you were placing into the new composite Avro generic record.
However, we do offer some flexibility of pre-formatting, as per the following link
https://www.ibm.com/support/knowledgecenter/en/SSTRGZ_11.4.0/com.ibm.cdcdoc.mcadminguide.doc/refs/mirror_timestamp_write_format_Kafka.html
Note to employ this optional pre-formatter you need to "To enable this parameter, you must set the mirror_write_format parameter to DYNAMIC."
You will note that it is possible to set a datastore parameter that will allow typically desired customizations of the timestamp data your KCOP receives.
"AVRO (default)
Formats TIMESTAMP column values as the number of microseconds from the UNIX epoch, 1 January 1970 (ISO calendar). For the purpose of this calculation, the timestamps are assumed to be UTC.
For TIMESTAMP columns with precision greater than microseconds, the values are formatted as strings. You can specify the string format by using the timestamp_format datastore parameter. The default value of timestamp_format is yyyy-MM-dd HH:mm:ss.SSSNNNnnnppp.
TIMESTAMP WITH TIMEZONE column values are formatted as strings. You can specify the string format by using the timestamp_tz_format datastore parameter. The default value of timestamp_tz_format is yyyy-MM-dd HH:mm:ss.SSSNNNnnnppp T."
If this does not give you the exact format desired, then you can choose the closest format and modify the value of timestamp columns in the KCOP.
Modifying the KCOP is done as follows...
https://www.ibm.com/support/knowledgecenter/en/SSTRGZ_11.4.0/com.ibm.cdcdoc.mcadminguide.doc/tasks/createkafkacop.html
The question regarding column name is the same.  If the KCOP employed is using an Avro schema registry, then you can programatically change the schema registered with the schema registry.  If it is a JSON one, you can alter the JSON string after it is created, or make a change before invoking the Avro to JSON method.
Alternatively, if your source supports derived columns, I believe in the Management Console you can define a derived column with a new name that is simply the value of the original column.  My recollection then is that you can deselect the original column and thus your name will be changed.


text:
Q: How does is_owner works? So i am trying to add dev only commands me and my devs get confused on doing this as we need the is_owner but i do not know how to implement it any help here?
So currently i have a shutdown bot command for devs when it is needed:
@commands.command(pass_context=True)
@checks.isOwner()
async def shutdown(self, ctx):
    """Shuts the bot down"""
    fmt = 'Shutting down, I will miss you {0.author.name}'
    await self.bot.say(fmt.format(ctx.message))
    await self.bot.logout()
    await self.bot.close()

A: If you want to check if that the person using a command is an owner or developer of the bot, first you will need to set their ID as owner_id when you instance the bot:
bot = commands.Bot(command_prefix = '!', owner_id = 123345219197488900, intents = intents)

In case you are a group of developers and want to set more than one as owner_ids:
owners = [123345219197488900, 173545269197488974, 253345719197888931]
bot = commands.Bot(command_prefix = '!', owner_ids = set(owners), intents = intents)

Then you can use a command check to ensure that the user using this command is an owner.
@commands.command(pass_context=True)
@commands.is_owner()
async def shutdown(self, ctx):


text:
Q: How can I create a monit process for a Ruby program? I have these rake tasks that will occasionally fail. I want to use monit to monitor them and to restart them if necessary.
I have read the other ruby/monit threads on StackOverflow. My case is different in that these programs require my Rails environment in order to work. That's why I have them as rake tasks now.
Here is one of the tasks I need to monitor, in it's entirety:
task(process_updates: :environment) do
  `echo "#{Process.pid}" > #{Rails.root}/log/process_alerts.pid`
  `echo "#{Process.ppid}" > #{Rails.root}/log/process_alerts.ppid`
  SynchronizationService::process_alerts
end

My question is, do I leave this as a rake task, since SynchronizationService::process_alerts requires the Rails environment to work? Or is there some other wrapper I should invoke and then just run some *.rb file?

A: Monit can check for running pid, since you're creating pid when you run task you can create a monit config which should look something like this:
check process alerts with pidfile RAILSROOT/log/process_alerts.pid
  start program = "cd PATH_TO_APP; rake YOURTASK" with timeout 120 seconds
  alert your@mail.com on { nonexist, timeout }

Of course RAILSROOT, PATH_TO_APP, YOURTASK should correspond to your paths/rake task.
Monit then will check for running process in system using the pidfile value and will start the process using start program command if it can't find running process.


text:
Q: FEM code for PDE subdomain interface condition I have a simple problem to solve. I have two pde, one for $u_{1}$ and one for $u_{2}$, where the domain in space for  $u_{1}$ is $[-L_{0}, 0] $ , and for $u_{2}$ the space domain is $ [0,L_{0}] $.
I have at the interface a condition that is $$ D_{1} \dfrac{\partial u_{1}}{\partial x}=D_{2}\dfrac{\partial u_{2}}{\partial x} - V_{2}u_{2} \;\;\;\;\text{at}\;\;x=0$$
I must resolve this problem with FEM and with a second order lagrangian element in 1D. I try and search for set up this problem in COMSOL or in MATLAB but everything was fine until I want to setup the value at interface. I have not found any guide for setup this condition at interface. If anyone have a solution for this problem, even in python or C++ or other language please share a link for the solution.
Thank you


text:
Q: Scene Text Image Super-Resolution for OCR I am working on an OCR system.  A challenge that I'm facing for recognizing the text within ROI is due to the shakiness or motion effect shot or text that is not focus due to angle positions. Please consider the following demo sample

If you notice the texts (for ex. the mark as a red), in such cases the OCR system couldn't properly recognize the text. However, this scenario can also come on with no angle shot where the image is too blurry that the OCR system can't recognize or partially recognize the text. Sometimes they are blurry or sometimes very low resolution or pixelated. For example

Methods we've tried
Firstly we've tried various methods available on SO. But sadly no luck.

*

*How to improve image quality to extract text from image using Tesseract

*How to improve image quality? [closed]

*Image quality improvement in Opencv
Next, we've tried the following three most promising methods as below.
1.TSRN
A recent research work (TSRN) mainly focuses on such cases. The main intuitive of it is to introduce super-resolution (SR) techniques as pre-processing. This implementation looks by far the most promising. However, it fails to do magic on our custom dataset (for example the second images above, the blue text). Here are some example from their demonstration:

2. Neural Enhance
After looking at its illustration on its page, we believed it might work. But sadly it also couldn't address the problem. However, I was a bit confusing even with their showed example because I couldn't reproduce them too. I've raised an issue on github where I demonstrated this more in detail. Here are some example from their demonstration:

3. ISR
The last choice with minimum hope with this implementation. No luck either.
Update 1

*

*[Method]: Apart from the above, we also tried some traditional approaches such as Out-of-focus Deblur Filter (Wiener filter and also unsupervised Weiner filter). We also checked the Richardson-Lucy method. but no improvement with this approach either.

*[Method]: We've checked out a GAN based DeBlur solution. DeblurGAN I have tried this network. What attracted me was the approach of the Blind Motion Deblurring mechanism.
Lastly, from this discussion we encounter this research work which seems really good enough. Didn't try this yet.

Update 2

*

*[Method]: Real-World Super-Resolution via Kernel Estimation and Noise Injection
Tried this method. Promising. However, didn't work in our case. Code.

*[Method]: Photo Restoration
Comparative to the above all methods, it performs the best surprisingly in super text resolution for OCR. It greatly removes noise, blurriness, etc., and makes the image much clearer and which enhance model generalization better. Code.
My Query
Is there any effective workaround to tackle such cases? Any methods that could improve such blurry or low-resolution pixels whether the texts are in front or far away due to the camera angle?

A: Currently, there is one solution Real-World Super-Resolution via Kernel Estimation and Noise Injection. The author proposes a degradation framework RealSR, which provides realistic images for super-resolution learning. It is a promising method for shakiness or motion effect images super-resolution.
The method is divided into two stages. The first stage Realistic Degradation for Super-Resolution

is to estimate the degradation from real data and generate realistically
LR images.

The second stage Super-Resolution Model

is to train the SR model based on the constructed data.

You can look at this Github article: https://github.com/jixiaozhong/RealSR

A: I've also been working on this super-resolution field and found some promising results but haven't tried yet,
first paper (license plate base text) they implement the image enhancement first then do the super-resolution in a later stage.
second paper and github in this paper they use text prior to guide the super-resolution network.


text:
Q: how to maintaine cookies in between two Url's in asp.net i need pass the cookie values to another Url which have same domain.i have two url's with same domain name..one Url for Authentication another is for retrieve data.i executed first url its authenticated . with this authentication cookie i want to execute second url ..
How to do this...i unable to Add cookie to socond url
here is my code..
string url = "http://172.16.xx.xxx:8080/cms?login&username=santhu&password=welcome";
        string url1 = "http://172.16.xx.xxx:8080//cms?status=ProcessStatus";
        string result = null;
    try
    {
        WebClient client = new WebClient();
        WebClient client1 = new WebClient();
        result = client.DownloadString(url);
        TextBox1.Text = result.ToString();

        if (Response.Cookies["JSESSIONID"] != null)
            TextBox1.Text = Server.HtmlEncode(Response.Cookies["JSESSIONID"].Value);

            client1.Headers.Add("JSESSIONID", TextBox1.Text);
            result = client1.DownloadString(url1);
            TextBox2.Text = result.ToString();

    }
    catch (Exception ex)
    {

    }

A: Set the cookie.Domain = "domain.com" and it works on all url's with that domain.

A: Here's what you may try. Define a cookie aware web client:
public class WebClientEx : WebClient
{
    public CookieContainer CookieContainer { get; private set; }

    public WebClientEx()
    {
        CookieContainer = new CookieContainer();
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).CookieContainer = CookieContainer;
        }
        return request;
    }
}

and then use this client for both requests:
using (var client = new WebClientEx())
{
    var values = new NameValueCollection
    {
        { "username", "santhu" },
        { "password", "welcome" },
    };
    // Authenticate
    client.UploadValues("http://172.16.xx.xxx:8080/cms?login", values);

    // Download some secure resource
    var result = client.DownloadString("http://172.16.xx.xxx:8080//cms?status=ProcessStatus");
}


text:
Q: Zurb Foundation equalizer plugin - 'equalizer' is not an available method for this element? I am trying to use Zurb Foundation equalizer plugin for this grid layout below:

I have the plugin loaded:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.0/css/foundation.min.css">

And call the plugin:

But I get this error instead:
Uncaught ReferenceError: We're sorry, 'equalizer' is not an available method for this element.
    at r.fn.init.a [as foundation] (foundation.min.js:1)
    at HTMLDocument.<anonymous> (cdn.html:112)
    at j (jquery.min.js:2)
    at k (jquery.min.js:2)

Any ideas what i have missed?

A: Try with $(document).foundation(); to definition foundation.
With $(document).foundation('equalizer', 'reflow'); you are trying to refresh equalizer but you don't have already defined.


text:
Q: send email using javascript, html and ajax I have my form in HTML:
<form name="form" class="form" role="form" action="index.php" method="post">

              Seleziona Area:
              *
              <select class="form-control" id="sel1" name="region" required>
                                            <option selected="selected" disabled="disabled" value="">Seleziona la tua zona</option>
                                            <option value="region1">1 - Udine Centro</option>
                                            <option value="region2">2 - Rizzi / S. Domenico / Cormor / S. Rocco</option>
                                            <option value="region3">3 - Laipacco / San Gottardo</option>
                                            <option value="region4">4 - Udine sud</option>
                                            <option value="region5">5 - Cussignacco</option>
                                            <option value="region6">6 - S. Paolo / S. Osvaldo</option>
                                            <option value="region7">7 - Chiavris / Paderno</option>
                                    </select>

              Mail personale
              *
              <input name="mail" type="email" class="form-control" id="usr" placeholder="es. mariorossi@gmail.com" required>

            Nome e Cognome
            *

            <input pattern="^([ \u00c0-\u01ffa-zA-Z'\-])+$" title="Solo caratteri es. Mario Rossi" name="nome" type="text" class="form-control" id="usr" placeholder="es. Mario Rossi" required>

            Età
            *
            <input name="eta" type="number" min="16" max="99" class="form-control" id="usr" placeholder="es. 35" required>

              Inserisci la tua segnalazione o i tuoi spunti
              *
              <textarea name="commento" class="form-control" rows="7" id="comment" placeholder="Scrivi in questo campo" required></textarea>

* campi richiesti

<button name="submit" type="submit" class="btn" value="submit">Invia Segnalazione</button>

</form>

Then, I have connected my form in HTML with my email sender code in PHP:
<?php

            // L'INDIRIZZO DEL DESTINATARIO DELLA MAIL
            $to = "my@email.com";

            // IL SOGGETTO DELLA MAIL
            $subject = "Segnalazione da " . $_POST["nome"];

            // COSTRUIAMO IL CORPO DEL MESSAGGIO
            $body = "Contenuto della segnalazione:\n\n";

            $body .= "Mail: " . trim(stripslashes($_POST["mail"])) . "\n";

            $body .= "Nome: " . trim(stripslashes($_POST["nome"])) . "\n";

            $body .= "Età: " . trim(stripslashes($_POST["eta"])) . "\n";

            $val_select = trim(stripslashes($_POST["region"]));
            if ($val_select == "region1") {
                $val_select = "Udine Centro";
            } else if ($val_select == "region2") {
                $val_select = "Rizzi / S. Domenico / Cormor / S. Rocco";
            } else if ($val_select == "region3") {
                $val_select = "Laipacco / San Gottardo";
            } else if ($val_select == "region4") {
                $val_select = "Udine sud";
            } else if ($val_select == "region5") {
                $val_select = "Cussignacco";
            } else if ($val_select == "region6") {
                $val_select = "S. Paolo / S. Osvaldo";
            } else if ($val_select == "region7") {
                $val_select = "Chiavris / Paderno";
            }

            $body .= "Area: " . $val_select . "\n";

            $body .= "Messaggio: " . trim(stripslashes($_POST["commento"])) . "\n";

            // INTESTAZIONI SUPPLEMENTARI
            $header_from = "From: " . trim(stripslashes($_POST["nome"])) . " " . trim(stripslashes($_POST["mail"])) . " ";

            // INVIO DELLA MAIL
            if( $_POST["nome"] != "" && $_POST["commento"] != "" && $_POST["eta"] != "" && $_POST["region"] != ""){
                //echo "ciao!";
                //mail($to, $subject, $body, $header_from);
                mail($to, $subject, $body, 'Mail dal sito Prima Udine');
                //header("Location:https://www.google.com/");
                header( "Location: redirect.php");

            }
        ?>

But this method dont work. so I would like to change method. I would like to connect my form in HTML with a JavaScript code using Ajax to send the email.
How I can do that? If you need more info ask me, thanks.
ps. i'm newbie but I can code something ;)
UPDATE: I have tried to fix the php problem, check my answer.

A: I have tried to fix my php. For now, this works.  I have redirect to another page after submit:
code edited:

if(count($_POST) == 0) {

   // L'INDIRIZZO DEL DESTINATARIO DELLA MAIL
   $to = "llluca3.0@gmail.com";

   // IL SOGGETTO DELLA MAIL
   $subject = "Segnalazione da " . $_POST["nome"];

   // COSTRUIAMO IL CORPO DEL MESSAGGIO
   $body = "Contenuto della segnalazione:\n\n";

   $body .= "Mail: " . trim(stripslashes($_POST["mail"])) . "\n";

   $body .= "Nome: " . trim(stripslashes($_POST["nome"])) . "\n";

   $body .= "Età: " . trim(stripslashes($_POST["eta"])) . "\n";

    $val_select = trim(stripslashes($_POST["region"]));
   if ($val_select == "region1") {
    $val_select = "Udine Centro";
   } else if ($val_select == "region2") {
    $val_select = "Rizzi / S. Domenico / Cormor / S. Rocco";
   } else if ($val_select == "region3") {
    $val_select = "Laipacco / San Gottardo";
   } else if ($val_select == "region4") {
    $val_select = "Udine sud";
   } else if ($val_select == "region5") {
    $val_select = "Cussignacco";
   } else if ($val_select == "region6") {
    $val_select = "S. Paolo / S. Osvaldo";
   } else if ($val_select == "region7") {
    $val_select = "Chiavris / Paderno";
   }

   $body .= "Area: " . $val_select . "\n";

   $body .= "Messaggio: " . trim(stripslashes($_POST["commento"])) . "\n";

   // INTESTAZIONI SUPPLEMENTARI
   $header_from = "From: " . trim(stripslashes($_POST["nome"])) . " " . trim(stripslashes($_POST["mail"])) . " ";

   // INVIO DELLA MAIL
   if( $_POST["nome"] != "" && $_POST["commento"] != "" && $_POST["eta"] != "" && $_POST["region"] != ""){
    //echo "ciao!";
    //mail($to, $subject, $body, $header_from);
    mail($to, $subject, $body, 'Mail dal sito Prima Udine');
    //header("Location:https://www.google.com/");
    //header( "Location: redirect.php");
   }
  } else ( count($_POST) > 1 ) {

         /* ... process form here ... */

         /* prevent re-posting prompt
             by redirecting to same url with a 303 status */
         header("Location: redirect.php");
         exit;
        }

the new code is:

<?php

  if(count($_POST) == 0) {

    /* my old code */

    }
  } else ( count($_POST) > 1 ) {

         /* ... process form here ... */

         /* prevent re-posting prompt
             by redirecting to same url with a 303 status */
         header("Location: redirect.php");
         exit;
        }

  ?>


text:
Q: Subsetting data frame to include only one observation for average I have the code below, and currently it prints out all 150 observations with the same output for the three different types of species. I am trying to get the set to just print out 3 rows, one for each type of species. Can anyone help me subset this?
iris_summary <- function(irisdata) {
           newiris = data.frame(irisdata$Species,
                         MeanSepalLength = mean(irisdata$Sepal.Length),
                         MeanSepalWidth = mean(irisdata$Sepal.Width),
                           MeanPetalLength = mean(irisdata$Petal.Length),
                           MeanPetalWidth = mean(irisdata$Petal.Width))
        return(newiris)
       }
iris_summary(iris)

A: You can directly use dplyr summarise to get mean for all 3 species. Try this :
library(dplyr)
iris_avg <- iris %>% group_by(Species) %>% summarise_all(funs(mean))

> iris_avg
# A tibble: 3 x 5
Species    Sepal.Length Sepal.Width Petal.Length Petal.Width
1 setosa             5.01        3.43         1.46       0.246
2 versicolor         5.94        2.77         4.26       1.33
3 virginica          6.59        2.97         5.55       2.03


text:
Q: Find substring in string without includes/indexOf/Regex in Javascript I'd like to figure out if a substring is within a string without using the Javascript built in methods of includes, indexOf, (any similar to those), or regular expressions. Basically just looking to learn an algorithm approach.
This is what I have so far
function isSubstring(string, substring){
    substringIndex = 0;

    // loop through string
    for(let i = 0; i< string.length; i++){

       //check the current substring index if it matches
       if(string[i] === substring[substringIndex]){
           substringIndex++
          //continue searching... Would i then have to call another function recursively?
       }

    }

}

I'm having trouble understanding how to build the algorithm. Once it finds that first character that matches, I would just go to the next one and if it matches continue to the next index of the string? Would I then need a recursive function that is separate from the looping I am currently doing? I'm trying to get better at algorithmic thinking. Thanks.

A: Many approaches are possible. Here is one: Create a simpler function which will check if a first string is at concrete specified position, let's call it start, in a second string. It is quite simple: You compare first[i] with second[start+i] for all i in range 0 to length of first - 1.
Then the second step will be to repeat this function for all start positions from 0 to length of second string, while checking the boundaries (you cannot read after end of a string).
You can also do some optimizations later, when the first version will work. :-)

A: On each iteration over the length of the haystack, use slice to extract the characters from that index to (the index plus the length of the needle). If the sliced string matches the needle, return true:

function isSubstring(string, substring) {
  for (let i = 0; i < string.length; i++) {
    const sliced = string.slice(i, i + substring.length);
    if (sliced === substring) {
      return true;
    }
  }
  return false;
}
console.log(isSubstring('foobar', 'oob'));
console.log(isSubstring('foobar', 'baz'));

A: Here is an optimized example of the algorythm isSubstring. It iterates only through the minimum number of characters required.
For example, if the string is 20 characters long and the substring is only 5 characters long, when we get to the 16th position of the string we can assume that the substring doesn't exist within the string (16 + 5 = 21 > 20)

function isSubstring(str, sub){
  if(sub.length > str.length) return false;
  for(let i = 0; i < str.length - sub.length + 1; i++){
    if(str[i] !== sub[0]) continue;
    let exists = true;
    for(let j = 1; j < sub.length && exists; j++){
        if(str[i+j] === sub[j]) continue;
        exists = false;
    }
    if(exists) return true;
  }
  return false;
}

//expected true
console.log(isSubstring("hello world", "hello"));
console.log(isSubstring("hello world", "world"));
console.log(isSubstring("hello world", "d"));
console.log(isSubstring("hello world", "o w"));
console.log(isSubstring("hello world", "rl"));
console.log(isSubstring("hello world", ""));

//expected false
console.log(isSubstring("hello world", "hello world 1"));
console.log(isSubstring("hello world", "helloo"));

A: Since you expressed interest in a recursive method, here's something to consider. Clicking on the yellow markdown parts reveal the spoilers.
function f(str, sub, i=0, j=0){
  if (j && j == sub.length)

 return true;

  if (i == str.length)

 return false;

  if (str[i] == sub[j])
    return f(str, sub,

 i+1, j+1);

  return f(str, sub,

 i+1, 0);

}

A:     function isSubstring(str, sub) {
        return str.split(sub).length > 1
    }

No includes, no .indexOf, no RegExp. Just strings.

A: using only one loop pseudo code :

const containSubstr = (str, substr) => {
  let count = 0;
  let i = 0;
  let startIndex = 0;

  while (i < str.length) {
    if (substr[count] === str[i]) {
      if (count === substr.length - 1) {
        return true;
      }
      count++;
    } else {
      count = 0;
      i = startIndex;
      startIndex++;
    }
    i++;
  }
  return false;
};

console.log(containSubstr("ababad", "abad"));


text:
Q: How to Inject my service to ExceptionHandler I used my service in other places injected automaticaly by angular 2.
I want to use the same service in ExceptionHandler.
But service doesn't post data to server.
I went through debuger and my service invokes.
class MyExceptionHandler extends ExceptionHandler {
  rbJSLogger: RBLoggerService;

  constructor() {
    super(null,null);
    var injector = ReflectiveInjector.resolveAndCreate([
      RBLoggerService,
      JSONP_PROVIDERS,
      Http,
      ConnectionBackend,
      HTTP_PROVIDERS
    ]);
    this.rbJSLogger = injector.get(RBLoggerService);
  }
  call(error, stackTrace = null, reason = null){
    // console.error(stackTrace);
    this.rbJSLogger.searchBy("asd");
  }
}

A: update ExceptionHandler was renamed to ErrorHandler https://stackoverflow.com/a/35239028/217408
orgiginal
This code
var injector = ReflectiveInjector.resolveAndCreate([...]);

creates a new independent injector that doesn't know anything about services provided in your Angular applications.
You might want to inject the injector used by Angular in your application like
class MyExceptionHandler extends ExceptionHandler {
  rbJSLogger: RBLoggerService;

  constructor(injector:Injector) {
    super(null,null);
    this.rbJSLogger = injector.get(RBLoggerService);
  }
  call(error, stackTrace = null, reason = null){
    // console.error(stackTrace);
    this.rbJSLogger.searchBy("asd");
  }
}

or just
class MyExceptionHandler extends ExceptionHandler {
  rbJSLogger: RBLoggerService;

  constructor(private rbJSLogger:RBLoggerService) {
    super(null,null);
  }
  call(error, stackTrace = null, reason = null){
    // console.error(stackTrace);
    this.rbJSLogger.searchBy("asd");
  }
}


text:
Q: Repeater not working fine when passed a dataprovider (array) having a single element I am using a Repeater in an Accordian which does not appear to see a single element in userArray. If I add another entry to userArray then the Repeater works fine.
Thoughts??
    private function currUsersServiceHandler(event:ResultEvent):void{

                    if (event.result.currentUsers != null)
                    {
                        if (event.result.currentUsers.user is ArrayCollection) // if more than one elements are present
                        {
                            usersArray = event.result.currentUsers.user;
                        }
                        else if (event.result.currentUsers is ObjectProxy)
                        { //FIXIT usersArray populate by following line has some issue
                            usersArray = new ArrayCollection(ArrayUtil.toArray(event.result.currentUsers));
                        }
                    }
                }

        <mx:HTTPService id="currUsersService" url="currUsers.xml" result="currUsersServiceHandler(event)"/>

<mx:Accordion includeIn="UserList" x="10" y="10" width="554" height="242" >
        <mx:Repeater id="rep" dataProvider="{usersArray}">
            <mx:Canvas width="100%" height="100%" label="{rep.currentItem.firstName}" >
                    <mx:HBox>
                        <s:Label text="{rep.currentItem.firstName}"/>
                        <s:Label text="{rep.currentItem.lastName}"/>
                      <mx:/HBox>
            </mx:Canvas>
        </mx:Repeater>
</mx:Accordian>

Edit:
There is another thing I have just noticed i.e. that the accordian does show a single tab (when Array has a single element) but it's not labeled with the first name which I am setting. If I enter another user, two tabs appear and both are labeled with names I am setting. The first tab appears labeled too then.

A: It makes no sense to me that this would not work with 1 item in the dataProvider, but would work with two.
That said, tThis approach strikes me as convoluted and I tend to stay away from using repeaters at all.  I would suggest a different approach.
First create a component to display your data.  You can reuse you're existing code.  Conceptually something like this:
        <mx:Canvas width="100%" height="100%"  >
<mx:Script><[[
 public var user : Object;
]]></mx:Script>
                <mx:HBox>
                    <s:Label text="{user.firstName}"/>
                    <s:Label text="{user.lastName}"/>
                  <mx:/HBox>
        </mx:Canvas>

Then in your original component create the new instance of the component in ActionScript:
for each(var myUserObject : Object in usersArray){
  var newUserDisplayObject : UserDisplayObject = new UserDisplayObject();
  newUserDisplayObject.user = myUserObject;
  newUserDisplayObject.label = myUserObject.firstName
  accordian.addChild(newUserDisplayObject);
}