text:
Q: How to submit an HTML form without redirection If I have a form like this,
<form action="/Car/Edit/17" id="myForm" method="post" name="myForm"> ... </form>

how can I submit it without redirecting to another view by JavaScript/jQuery?
I read plenty of answers from Stack Overflow, but all of them redirect me to the view returned by the POST function.

A: In order to achieve what you want, you need to use jQuery Ajax as below:
$('#myForm').submit(function(e){
    e.preventDefault();
    $.ajax({
        url: '/Car/Edit/17/',
        type: 'post',
        data:$('#myForm').serialize(),
        success:function(){
            // Whatever you want to do after the form is successfully submitted
        }
    });
});

Also try this one:
function SubForm(e){
    e.preventDefault();
    var url = $(this).closest('form').attr('action'),
    data = $(this).closest('form').serialize();
    $.ajax({
        url: url,
        type: 'post',
        data: data,
        success: function(){
           // Whatever you want to do after the form is successfully submitted
       }
   });
}

Final solution
This worked flawlessly. I call this function from Html.ActionLink(...)
function SubForm (){
    $.ajax({
        url: '/Person/Edit/@Model.Id/',
        type: 'post',
        data: $('#myForm').serialize(),
        success: function(){
            alert("worked");
        }
    });
}

A: One-liner solution as of 2020, if your data is not meant to be sent as multipart/form-data or application/x-www-form-urlencoded:
<form onsubmit='return false'>

</form>

A: Since all current answers use jQuery or tricks with iframe, figured there is no harm to add method with just plain JavaScript:
function formSubmit(event) {
  var url = "/post/url/here";
  var request = new XMLHttpRequest();
  request.open('POST', url, true);
  request.onload = function() { // request successful
  // we can use server response to our request now
    console.log(request.responseText);
  };

  request.onerror = function() {
    // request failed
  };

  request.send(new FormData(event.target)); // create FormData from form that triggered event
  event.preventDefault();
}

// and you can attach form submit event like this for example
function attachFormSubmitEvent(formId){
  document.getElementById(formId).addEventListener("submit", formSubmit);
}

A: You need Ajax to make it happen. Something like this:
$(document).ready(function(){
    $("#myform").on('submit', function(){
        var name = $("#name").val();
        var email = $("#email").val();
        var password = $("#password").val();
        var contact = $("#contact").val();

        var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
        if(name=='' || email=='' || password=='' || contact=='')
        {
            alert("Please fill in all fields");
        }
        else
        {
            // Ajax code to submit form.
            $.ajax({
                type: "POST",
                url: "ajaxsubmit.php",
                data: dataString,
                cache: false,
                success: function(result){
                    alert(result);
                }
           });
        }
        return false;
    });
});

A: Place a hidden iFrame at the bottom of your page and target it in your form:

<form action="/Car/Edit/17" id="myForm" method="post" name="myForm" target="hiddenFrame"> ... </form>

Quick and easy. Keep in mind that while the target attribute is still widely supported (and supported in HTML5), it was deprecated in HTML 4.01.
So you really should be using Ajax to future-proof.

A: See jQuery's post function.
I would create a button, and set an onClickListener ($('#button').on('click', function(){});), and send the data in the function.
Also, see the preventDefault function, of jQuery!

A: You can achieve that by redirecting the form's action to an invisible . It doesn't require any JavaScript or any other type of scripts.

<form action="submitscript.php" target="dummyframe">

</form>

A: Okay, I'm not going to tell you a magical way of doing it because there isn't.
If you have an action attribute set for a form element, it will redirect.
If you don't want it to redirect simply don't set any action and set onsubmit="someFunction();"
In your someFunction() you do whatever you want, (with AJAX or not) and in the ending, you add return false; to tell the browser not to submit the form...

A: The desired effect can also be achieved by moving the submit button outside of the form as described here:
Prevent page reload and redirect on form submit ajax/jquery
Like this:
<form id="getPatientsForm">
    Enter URL for patient server

    <input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
    <input name="patientRootUrl" size="100"></input>

</form>

<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>

A: Using this snippet, you can submit the form and avoid redirection. Instead you can pass the success function as argument and do whatever you want.
function submitForm(form, successFn){
    if (form.getAttribute("id") != '' || form.getAttribute("id") != null){
        var id = form.getAttribute("id");
    } else {
        console.log("Form id attribute was not set; the form cannot be serialized");
    }

    $.ajax({
        type: form.method,
        url: form.action,
        data: $(id).serializeArray(),
        dataType: "json",
        success: successFn,
        //error: errorFn(data)
    });
}

And then just do:
var formElement = document.getElementById("yourForm");
submitForm(formElement, function() {
    console.log("Form submitted");
});

A: Fire and forget vanilla js + svelte
function handleSubmit(e) {
    const request = new Request(`/products/${item.ItemCode}?_method=PUT`, {
        method: 'POST',
        body: new FormData(e.target),
    });
    fetch(request)
}

Used in Svelte:
<form method="post" on:submit|preventDefault={handleSubmit}>

A: If you control the back end, then use something like response.redirect instead of response.send.
You can create custom HTML pages for this or just redirect to something you already have.
In Express.js:
const handler = (req, res) => {
  const { body } = req
  handleResponse(body)
  .then(data => {
    console.log(data)
    res.redirect('https://yoursite.com/ok.html')
  })
  .catch(err => {
    console.log(err)
    res.redirect('https://yoursite.com/err.html')
  })
}
...
app.post('/endpoint', handler)


text:
Q: Unable to read hidden field value from server side I have a aspx page (default.aspx), inside which I am loading a user control (tree.ascx).
inside the tree.ascx there is a hidden field.
<asp:HiddenField ID="HiddenField1" runat="server"/>

I am assigning a value to the hidden field using javascript.
document.getElementById('<%=HiddenField1.ClientID%>').value = "some text here";
alert(document.getElementById('<%=HiddenField1.ClientID%>').value);
document.getElementById('form1').submit();

The alert displays the value absolutely fine. which means the value gets inserted in the hidden field properly.
But when I am posting back to server and checking the value, it is always null.
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // do something.
        }
        else
        {
            string str = this.HiddenField1.Value;
        }
    }

My code is always getting a empty string here. somehow the postback is erasing the value from the hidden field.
What could be the reason?

A: Try using below syntax. It works for me even after postback.
ASPX code
<asp:HiddenField runat="server" ID="aspHiddenField" />
<input type="hidden" id="inputHidden" value='<%= aspHiddenField.ClientID %>' />

JavaScript Code
var inputHidden = document.getElementById('inputHidden');
$("#" + inputHidden.value).val("some text");

Code Behind
if (!string.IsNullOrEmpty(aspHiddenField.Value))
 {
//Your code goes here
}

A: Check if your control is within a master page, if it is, then you need to access it like that, 1st Master Page->within master page look for the control's value, it will work surely.

A: Place your hidden field in update panel   like :
<asp:UpdatePanel ID="UpnlHidden" runat="server">
<ContentTemplate>
<asp:HiddenField ID="HiddenField1" runat="server"/>
</ContentTemplate>
</asp:UpdatePanel>

This will work for you :-)

redpajama_set_name: RedPajamaStackExchange


text:
Q: WPF DataGrid validation when bound to a DataView I am attempting to validate input on a DataGrid which is populated by a DataView (e.g. myDataGrid.ItemsSource = myDataView). However, all the WPF DataGrid validation examples I have seen assume that the DataGrid source is a C# class. I can't figure out how to hook up a single cell (i.e. a column) to a code-behind validation.  Can someone give an example or point me to one?

A: Ok, I did some quick tests; I think the main impediment to really doing it manually is that the DataGridCell doesn't create any bindings for its content when assigning directly a DataView for display. However, if you're willing to jump through the hoops of assigning custom  DataGridTemplateColumns when creating the DataGrid, you can access the bindings on, say, the TextBox instances inside the template, and set custom validation errors on them.
Well actually, either this or override the default style of the textboxes generated by the DataGrid; you see, the default textbox style doesn't have any borders or anything, so setting a validation error on it doesn't have any effect. Making it into a normal textbox with DataTemplate or overriding its style would enable you to actually make something visible as an effect of setting the validation error.
However you'll need to do some research by yourself; I did a quick prototype and it works, but I can't create the binding correctly in the DataTemplate (either I forgot all the WPF I knew since I worked with it last, or I only know how to work with proper bindings :)). If you get somewhere with that it's easier going forward:
Somehow get access to a BindingExpression; what I did was attach a handler to the LostFocus event and checking if what lost focus was a textbox that was inside a DataGridCell; if so, I simply mark that binding as invalid (with t representing a TextBox instance):
var x = t.GetBindingExpression(TextBox.TextProperty);

Validation.MarkInvalid(x, new ValidationError(new ExceptionValidationRule(), x.ParentBinding, "error", new Exception("error")));

I must confess I'm not sure anymore what each argument's role is in the ValidationError constructor is (I think the exception message is displayed by default in the validation tooltip? Or is it the error content?), but I'm sure you can figure it out. Now if you don't mind, I think I'll take a break... like I said, it's not easy going against the flow :)

A: So I did some more research, and what I was basically missing was that I can specify the column name with the Path attribute of a Binding (or even use the column ordinal in brackets, e.g. Path="[0]"). After that realization, everything is basically the same as using a class property. So a typical DataGrid column definition I use follows:
<DataGridTextColumn Header="Regular" EditingElementStyle="{StaticResource ValidationErrorStyleBoxRA}" ElementStyle="{StaticResource ValidationErrorStyleBlockRA}" Width="60">
    <DataGridTextColumn.Binding>
        <Binding Path="HourlyRate" StringFormat="F3" ValidatesOnExceptions="True" ValidatesOnDataErrors="True" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <local:HourlyRatesAmountValidate ValidatesOnTargetUpdated="True" />
            </Binding.ValidationRules>
        </Binding>
    </DataGridTextColumn.Binding>
</DataGridTextColumn>


text:
Q: Java Servlet absolute paths outside webfolder [ Windows & Linux ] Disclaimer : At the moment, due to lack of a Linux dev/test server, I am currently unable to test this myself. Hence me asking the question here. I will have a Linux box eventually but am currently confined to using Windows.
I am designing a webapp that will run in Tomcat 7 on Windows & Linux.
Supposing on both systems the WAR is deployed in the following locations (respectively)
/opt/Tomcat/webapps/MyApp

C:/opt/Tomcat/webapps/MyApp

The Webapp has a Servlet which needs to process files from the OS file system in the following locations
/work/logs/<logfiles>

C:/work/logs/<logfiles>

On Windows I can specify C:/work/logs and the Servlet knows to pick up this absolute path and it works fine. I suspect because the C: at the start. I know this because I have tested this.
My real question is...
On Linux, in the absence of a drive letter, if I ask it to look in /work/logs will it try to look at a relative path :
/opt/Tomcat/webapps/MyApp/work/logs

or will it look in the file system (/work/logs) as I'd like it to?
I'm asking this now because it will ultimately affect the overall design.

A: Leading slash in Linux means "absolute path", so you can be sure that if you use path like /work/logs/<something> it will understand it as an absolute path.
BTW if you use the same path in Windows it will work and use current disk, i.e. if tomcat's working directory is on C: it will use C: drive, however if tomcat is running on D: this drive will be used.

A: I can recommend using CATALINA_HOME environment variable to find a folder in which you place your config. For my projects I have the following structure:
$CATALINA_HOME/appconfig/   <-- config
$CATALINA_HOME/webapps/somewar.war     <-- your webapps

Inside appconfig I will place a somewar.properties which functions as the configuration for that server.  (I also place log4j.properties, and any special certificates / other things that are specific to the server instance you run on, but I try to keep it to a minimum)
As there will always be a CATALINA_HOME set for your project it is reusable.
inside the somewar.properties I would then list
work.path=/work/logs

Using /work/logs will work on both linux and windows as @AlexR mentions (in his much more to the point answer) but you can get into trouble as on linux you would need root access to be allowed to create the /work folder. It depends on who is managing the server and how strict they are.
I prefer the configuration solution so if you end up working on a machine that won't let you use a certain location, you can switch. Ofcourse you do need to be allowed to write inside CATALINA_HOME ;)


text:
Q: "andr" tab completes to "_xrandr" instead of android or nothing I am running osx and installed oh-my-zsh as well, if that's relevant.
Anyway, if I type in something like "andr" and hit tab to complete it, it autocompletes to _xrandr instead of doing nothing (android isn't in my path). I'm not really sure why.
Any idea why that might be the case?

A: oh-my-zsh sets up completion to look for completions on the left side of the typed word if there are none on the right side.
This happens in ~/.oh-my-zsh/lib/completion.zsh:
## case-insensitive (all),partial-word and then substring completion
if [ "x$CASE_SENSITIVE" = "xtrue" ]; then
  zstyle ':completion:*' matcher-list 'r:|[._-]=* r:|=*' 'l:|=* r:|=*'
  unset CASE_SENSITIVE
else
  zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}' 'r:|[._-]=* r:|=*' 'l:|=* r:|=*'
fi

The important part here is 'l:|=* r:|=*'. If you dislike this behavior, you just have to remove this from zstyle ':completion:*' matcher-list. The best way to do this, is to create a file in ~/.oh-my-zsh/custom with extension .zsh, for example own-completion.zsh:
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}' 'r:|[._-]=* r:|=*'

This is for case insensitive completion, if you do not want this either, also remove 'm:{a-zA-Z}={A-Za-z}'.
You could change it in ~/.oh-my-zsh/lib/completion.zsh directly, but it will probably be overwritten once you update oh-my-zsh.


text:
Q: How do you create a function that takes an argument and returns a dictionary of character counts in Python 3.10? I would like to create a function that takes an argument and creates a dictionary where:
I) the keys are the individual characters of the argument, and
ii) the values represent the number of occurrences of that particular character in the argument.
I have been shown the example below, which although works - lines 4 and 5 don't seem instinctual to me.
Perhaps it's because I'm new to coding. Why should the code need to check an empty dictionary? Is there a more intuitive way?
def count_letters(text):
  result = {}
  for letter in text:
    if letter not in result:
      result[letter] = 0
    result[letter] += 1
  return result

print(count_letters("Python"))

A: If you don't check if letter is in result first, then
result[letter] += 1

will raise a KeyError, because there's no value to increment yet.

This is a common pattern (add a key if it doesn't exist yet, then do something with its value) captured by the defaultdict type.
from collections import defaultdict

def count_letters(text):
    result = defaultdict(int)
    for letter in text:
        # If letter isn't in result yet, implicitly execute
        # result[letter] = int() first.
        # int() returns 0.
        result[letter] += 1
    return result

Counting items in an iterable value is also a common pattern, so it might not be surprising that there's a type for that as well.
from collections import Counter

def count_letters(text):
    # Counter is a subclass of dict,
    # so you can do with it anything you
    # would do with the dict.
    return Counter(text)


text:
Q: How to persist column index of a WPF datagrid? I want to persist the index value of each column of my own datagrid but I don't know how to do it. Looks like the index can only be set thru the order of addition of the columns on the xaml code.
Any help will be great, thanks.

A: I found the solution, columns have a DisplayIndex property that I can bind to my column ViewModel.


text:
Q: Get reference to MainWindow in custom main() in WPF I am trying to write a custom Main() function for my WPF app so I can parse the command line and configure the GUI based on the command line. I can't figure out how to get a reference to the MainWindow instance created by the default implementation of Main(). The auto-generated implementation found in App.g.cs is below:
public void InitializeComponent() {
    if (_contentLoaded) {
        return;
    }
    _contentLoaded = true;

    #line 5 "..\..\..\App.xaml"
    this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative);

    #line default
    #line hidden
    System.Uri resourceLocater = new System.Uri("/MyApplication;component/app.xaml", System.UriKind.Relative);

    #line 1 "..\..\..\App.xaml"
    System.Windows.Application.LoadComponent(this, resourceLocater);

    #line default
    #line hidden
}

[System.STAThreadAttribute()]
public static void Main() {
    MyApplication.App app = new MyApplication.App();
    app.InitializeComponent();
    app.Run();
}

The problem I'm running into is  trying to get a reference to my MainWindow class after it is instantiated (however that is actually done via StartupUri). I'd expect to be able to do something like:
[System.STAThreadAttribute()]
public static void Main() {
    MyApplication.App app = new MyApplication.App();
    app.InitializeComponent();
    MyApplication.MainWindow w = (MyApplication.MainWindow)app.MainWindow;
    w.MyProgramIsAwesomeProperty = true;
    app.Run();
}

But, the app.MainWindow is always null. I've also tried the following and setting breakpoints on the Console.WriteLine lines, but the program never reaches those callbacks:
[System.STAThreadAttribute()]
public static void Main() {
    MyApplication.App app = new MyApplication.App();
    app.LoadCompleted += app_LoadCompleted;
    app.Activated += app_Activated;
    app.InitializeComponent();
    app.Run();
}

static void app_Activated(object sender, EventArgs e)
{
    Console.WriteLine("Activated");
}

static void app_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
    Console.WriteLine("LoadCompleted");
}

So, how can I get a reference to MyApplication.MainWindow after it's been instantiated in my Main function?

A: Actually, setting of StartupUri doesn't instantiate main window and doesn't set corresponding Application.MainWindow property. This happens later, after the call of Run method, that's why you're getting null.
The proper way is to avoid StartupUri and to override OnStartup method (while you can add event handler, as proposed, it doesn't make much sense in derived class). Then, in OnStartup, you may instantiate main window directly and set the property you want to set.

A: If you want to send something from the command line to the GUI, you're better off calling a method in your Application class and opening your GUI from that.
Open your App.xaml file, remove the StartupUri attribute from the Application element, and add a Startup attribute:
Startup="Application_Startup"

Then create an Application_Startup method in your Application class that reads the command line or whatever and sends that to your GUI:
private void Application_Startup(object sender, StartupEventArgs e)
{
    // e.Args contains command-line arguments.
    MainWindow mw = new MainWindow(Whatever(e.Args));
    mw.Show();
}


text:
Q: WBadmin script to backup System State into another partition failed? I tried numerous time but it is still failed like the following script on cmd prompt.
Is there any way to create automated script to backup system state on my Windows Server 2008 using WBAdmin into D drive inside a directory ?
any help would be greatly appreciated.

C:\Users\Administrator>wbadmin START
  SYSTEMSTATEBACKUP
  -backuptarget:D:\Admin\Backup wbadmin 1.0 - Backup command-line tool (C) Copyright 2004 Microsoft Corp.
Starting System State Backup
  [12/02/2011 4:22 AM] Retrieving volume
  information...
This would backup the system state
  from volume(s) SYS(C:) to
  D:\Admin\Backup. Do you want to start
  the backup operation? [Y] Yes [N] No Y
ERROR - Specified backup location
  could not be found.
C:\Users\Administrator>wbadmin START
  SYSTEMSTATEBACKUP
  -backuptarget:D:\Admin wbadmin 1.0 - Backup command-line tool (C) Copyright
  2004 Microsoft Corp.
Starting System State Backup
  [12/02/2011 4:22 AM] Retrieving volume
  information...
This would backup the system state
  from volume(s) SYS(C:) to D:\Admin. Do
  you want to start the backup
  operation? [Y] Yes [N] No Y
ERROR - Specified backup location
  could not be found.
C:\Users\Administrator>wbadmin START
  SYSTEMSTATEBACKUP
  -backuptarget:"D:\Admin\Backup" -quiet wbadmin 1.0 - Backup command-line tool
  (C) Copyright 2004 Microsoft Corp.
Starting System State Backup
  [12/02/2011 4:23 AM] Retrieving volume
  information...
This would backup the system state
  from volume(s) SYS(C:) to
  D:\Admin\Backup.
ERROR - Specified backup location
  could not be found.
C:\Users\Administrator>wbadmin START
  SYSTEMSTATEBACKUP -backuptarget:D:\
  -quiet wbadmin 1.0 - Backup command-line tool (C) Copyright 2004
  Microsoft Corp.
Starting System State Backup
  [12/02/2011 4:23 AM] Retrieving volume
  information...
This would backup the system state
  from volume(s) SYS(C:) to D:.
ERROR - Specified backup location
  could not be found.
C:\Users\Administrator>

A: it turns out that the "\" cause the problem, the final command is:
C:\Users\Administrator>wbadmin START SYSTEMSTATEBACKUP -backuptarget:D: without the back slash.


text:
Q: Visual Studio extension doesn't include Tasks.Extensions DLL in the VSIX file My extension depends on a NuGet package called Sentry.
Sentry depends on System.Threading.Tasks.Extensions 4.5.4.
When building, the System.Threading.Tasks.Extensions.dll doesn't get included in the vsix file. I assume it's because the DLL is supposed to be included as part of VS. The problem is that on VS2017 the binding only redirects to an older version of this DLL leading to a missing assembly error.
Is this a bug in VS2017/MSBuild/NuGet/Whatever, or am I doing something wrong?


text:
Q: Find integer solution in equation $3xy + 10x - 13y - 35=0$
Solve in integers.
to be honest I don't know what to do because it's the only way to factor like

$x (3 y + 10) = 13 y + 35$
   or    $(3 x - 13) y = 35 - 10 x$

A: Hint: Simon's favorite factoring trick, especially that 2nd example which explains how to deal with cases where the coefficient of the cross term is not 1 (like in this scenario).

 $0 = 9xy + 30x - 39y - 105 = (3x-13)(3y+10) +25 $.
$(3x-13)(3y+10) = - 25 $.
 So we just check the 6 factors of -25 to see if they are of that form.
 We get $(3x-13, 3y+10) = (5, -5), (-1, 25), (-25, 1)$ fitting the required form.

Thus, the only solutions are $(6, -5), (4,5), (-4, -3)$.

A: $$3xy + 10x - 13y - 35=0$$
$$x(3y+10)  = 13y + 35 $$
$$x = \frac{13y+35}{3y+10}$$
Since $x$ is an integer , $(3y+10)$ must divide $(13y + 35)$.
Also $$3(13y+35) = 13(3y+10) -25$$
So $3y+10$ must divide $-25$.
Looking at the possible factors of $-25$ ,
$$\begin{cases} 3y+10 = \pm1  \\3y+10 = \pm5 \\ 3y+10 = \pm25\end{cases}$$
Which yields $y=-3$ and $y = \pm5$
Inputting the values in $x$ gives the following the results :
$$(x,y) = \,(-4,-3) \,,(4,5) \,,(6,-5)$$

A: To have $x=\dfrac{13y+35}{3y+10}$ be an integer, note the following:
$4<x<5$ when $y<-8$
$x$ is not an integer when $y=-6$ or $-7$
$x$ is an integer $(6)$ when $y=-5$
$x$ is not an integer when $y=-4$
$x$ is an integer $(-4)$ when $y=-3$
$x$ is not an integer when $y\in\{-2,-1,0,1,2,3,4\}$
$x$ is an integer ($4$) when $y=5$
$4<x<5$ when $y>5$


text:
Q: Defining a scope on User model When searched for "john doe", I want to return users with names such as:
"john doe", "John Doe", "John Doe Jr.", "Mr. John doe" ...(and if possible "John Sr. Doe")
What I have done so far is that defined a named scope on my User model as:
scope :by_name, lambda { |name| where('UPPER(name) LIKE ?', name.upcase) }

And then in my /users/search:
name = params[:name]
@users = User.by_name(name).paginate(page: params[:page], per_page: 10)

But this is not working. I am getting back users with exactly the same name and in a case-sensitive manner - so "john doe" returns if one exists a user with name "john doe". What do I need to do??
I am using MySQL with Rails 3.2.3.
Please help!!

A: Try using
scope :by_name, lambda { |name| where('UPPER(name) LIKE %?%', name.upcase) }

A: scope :by_name, lambda { |name| where('UPPER(name) LIKE ?', "%#{name.upcase}%") }


text:
Q: .NET wcf call method freezes I have a problem with a WCF service method call that freeze and doesn't return a response if connection is done on the same process...
Here is the full code (very simplified to show only what is needed):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;

namespace TestProject
{

    [ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IBaseServiceCallback))]
    public interface IBaseService
    {
        [OperationContract]
        bool IsServiceInitiated();
    }

    public interface IBaseServiceCallback
    {
        [OperationContract]
        bool IsClientInitiated();
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, IncludeExceptionDetailInFaults = true, AutomaticSessionShutdown = false, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class BaseService : IBaseService
    {
        public bool IsServiceInitiated()
        {
            return true;
        }
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, IncludeExceptionDetailInFaults = true, AutomaticSessionShutdown = false, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class BaseServiceCallback : IBaseServiceCallback
    {
        public bool IsClientInitiated()
        {
            return true;
        }
    }

    public class CustomServer
    {
        private BaseService service;
        private ServiceHost host;

        public bool IsStarted
        {
            get { return host != null && host.State == CommunicationState.Opened; }
        }

        public CustomServer()
        {
            service = new BaseService();
            host = new ServiceHost(service, new Uri[] { new Uri("net.tcp://localhost:7780") });

            Type interfaceType = typeof(IBaseService);

            // Create service end point
            ServiceEndpoint endpointPipe = host.AddServiceEndpoint(interfaceType, new NetTcpBinding(), "CustomService");

            // Define TCP binding
            NetTcpBinding bindingPipe = (NetTcpBinding)endpointPipe.Binding;
            bindingPipe.MaxReceivedMessageSize = 5000000;
            bindingPipe.MaxBufferPoolSize = 5000000;
            bindingPipe.MaxBufferSize = 5000000;
            bindingPipe.ReaderQuotas.MaxDepth = 2048;
            bindingPipe.Security.Mode = SecurityMode.None;
            bindingPipe.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
            bindingPipe.Security.Message.ClientCredentialType = MessageCredentialType.None;

            // Increase MaxItemsInObjectGraph for all operations behaviors
            foreach (OperationDescription op in endpointPipe.Contract.Operations)
            {
                var dataContractBehavior = op.Behaviors.Find<DataContractSerializerOperationBehavior>();

                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                }
            }

            // In order to publish the service contract, it is important to publish the metadata
            ServiceMetadataBehavior smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>();

            if (smb == null)
            {
                smb = new ServiceMetadataBehavior();
            }

            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;

            host.Description.Behaviors.Add(smb);

            // Add MEX endpoint
            host.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexTcpBinding(), "net.tcp://localhost:7780/IDMmex");
        }

        public void Start()
        {
            // Open for listening
            host.Open();
        }

        public void Stop()
        {
            // Stop listening
            host.Close();
        }
    }

    public class CustomClient
    {
        public IBaseService ServiceProxy { get; private set; }
        private BaseServiceCallback callback;

        public CustomClient()
        {
            callback = new BaseServiceCallback();
        }

        public void Connect()
        {
            string serviceUrl = "net.tcp://localhost:7780/CustomService";

            // Create a channel in order to find the exact call back type.
            DuplexChannelFactory<IBaseService> sampleChannel = new DuplexChannelFactory<IBaseService>(callback, new NetTcpBinding(), new EndpointAddress(serviceUrl));

            Type duplexChannelFactory = typeof(DuplexChannelFactory<>).MakeGenericType(new Type[] { typeof(IBaseService) });

            object pipeFactory = Activator.CreateInstance(duplexChannelFactory, new object[] { callback, new NetTcpBinding(), new EndpointAddress(serviceUrl) });

            // Get the service end point
            ServiceEndpoint endpoint = (ServiceEndpoint)duplexChannelFactory.GetProperty("Endpoint").GetValue(pipeFactory, null);

            // Configure TCP binding
            NetTcpBinding tcpBinding = (NetTcpBinding)endpoint.Binding;
            tcpBinding.MaxReceivedMessageSize = 5000000;
            tcpBinding.MaxBufferPoolSize = 5000000;
            tcpBinding.MaxBufferSize = 5000000;
            tcpBinding.ReaderQuotas.MaxDepth = 2048;
            tcpBinding.Security.Mode = SecurityMode.None;
            tcpBinding.Security.Message.ClientCredentialType = MessageCredentialType.None;
            tcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
            tcpBinding.SendTimeout = TimeSpan.MaxValue;
            tcpBinding.ReceiveTimeout = TimeSpan.MaxValue;
            tcpBinding.OpenTimeout = TimeSpan.MaxValue;
            tcpBinding.CloseTimeout = TimeSpan.MaxValue;

            // Increase MaxItemsInObjectGraph for all operations behaviors
            foreach (OperationDescription op in endpoint.Contract.Operations)
            {
                var dataContractBehavior = op.Behaviors.Find<DataContractSerializerOperationBehavior>();

                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                }
            }

            // Create the channel to retrieve the pipe proxy object
            MethodInfo method = duplexChannelFactory.GetMethod("CreateChannel", new Type[0]);
            object pipeProxyObject = method.Invoke(pipeFactory, new object[] { });

            // Set the service proxy with the retrieved pipe proxy object
            ServiceProxy = (IBaseService)pipeProxyObject;
        }
    }
}

Then, I have a Windows Forms application that initiate a CustomServer, a CustomClient and that try to communicate:
CustomClient customClient = new CustomClient();
CustomServer customServer = new CustomServer();
customServer.Start();
customClient.Connect();

if (customClient.ServiceProxy.IsServiceInitiated()) // FREEZE HERE !!
{
    MessageBox.Show("Server initiated");
}

The connection is done, but when the "IsServiceInitiated" method is called, the application freezes.
But if a create an application dedicated for starting a server, and another application dedicated to a client that connect to the server, the method doesn't freeze and return true.
Any help is really needed.
Thanks a lot.
EDIT:
OK, I added a message inspector and dispatch inspector and output results of BeforeSendRequest and AfterReceiveRequest in the console. Here is the result:
Before send request: Action = http://tempuri.org/IBaseService/IsServiceInitiated Reply =
<s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:s="http://www.w3.org/2003/05/soap-envelope">
  <s:Header>
    <a:Action s:mustUnderstand="1">http://tempuri.org/IBaseService/IsServiceInitiated</a:Action>
    <a:MessageID>urn:uuid:d14b0af4-81c3-46c7-9b38-83a8fb092028</a:MessageID>
    <a:ReplyTo>
      <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
    </a:ReplyTo>
    <VsDebuggerCausalityData xmlns="http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink">uIDPoy1+4Je4rwBHkZsB8NCWGqQAAAAAAM8Ng9k570ayit0OK365Vn8yY2g0amdHlrkBcRNGylUACQAA</VsDebuggerCausalityData>
  </s:Header>
  <s:Body>
    <IsServiceInitiated xmlns="http://tempuri.org/" />
  </s:Body>
</s:Envelope>

After receive request: Action = http://tempuri.org/IBaseService/IsServiceInitiated Reply =
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
  <s:Header>
    <a:Action s:mustUnderstand="1">http://tempuri.org/IBaseService/IsServiceInitiated</a:Action>
    <a:MessageID>urn:uuid:d14b0af4-81c3-46c7-9b38-83a8fb092028</a:MessageID>
    <a:ReplyTo>
      <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
    </a:ReplyTo>
    <VsDebuggerCausalityData xmlns="http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink">uIDPoy1+4Je4rwBHkZsB8NCWGqQAAAAAAM8Ng9k570ayit0OK365Vn8yY2g0amdHlrkBcRNGylUACQAA</VsDebuggerCausalityData>
    <a:To s:mustUnderstand="1">net.tcp://localhost:7780/CustomService</a:To>
  </s:Header>
  <s:Body>
    <IsServiceInitiated xmlns="http://tempuri.org/">
    </IsServiceInitiated>
  </s:Body>
</s:Envelope>

I waited on the freezed method and finally got a CommunicationException:
The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal server error
NEW EDIT:
Amazing!!!
When using a separated application starting the server and the first application connect a client to this server, It works and the message inspector doesn't launch me the AfterReceiveRequest event, but I get the BeforeReceiveReply output :
Before receive reply: Action = http://tempuri.org/IBaseService/IsServiceInitiatedResponse Reply =
<s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:s="http://www.w3.org/2003/05/soap-envelope">
  <s:Header>
    <a:Action s:mustUnderstand="1">http://tempuri.org/IBaseService/IsServiceInitiatedResponse</a:Action>
    <a:RelatesTo>urn:uuid:bc055419-68d6-4f08-8170-0d1097e11d39</a:RelatesTo>
    <a:To s:mustUnderstand="1">http://www.w3.org/2005/08/addressing/anonymous</a:To>
  </s:Header>
  <s:Body>
    <IsServiceInitiatedResponse xmlns="http://tempuri.org/">
      <IsServiceInitiatedResult>true</IsServiceInitiatedResult>
    </IsServiceInitiatedResponse>
  </s:Body>
</s:Envelope>

EDIT AGAIN:
I notice that my service works perfectly if the server host is opened before a Windows Form is displayed ("Show" method), but if the host in opened after any Windows Form is displayed or within the constructor of a Windows Form, the WCF method call freeze....... Very strange...

A: Open up the host before the base window is initialized. This way the host will not associate itself with the form's SynchronizationContext and will run on a separate thread.
e.g:
ServiceHost host = new ServiceHost(typeof(BaseService));
host.Open();

Application.Run(new BaseForm()); // already exists

A: You seem to have several issues with your code.  The binding settings have issues, your service definition and interfaces have problems, etc.
Below is a working copy based off your code.  Make sure you adjust the bindings properly.
If this doesn't fix your issue, could you please paste the client callstack?
using System;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            CustomServer server = new CustomServer();
            server.Open();

            CustomClient client = new CustomClient();
            client.Connect();

            Console.WriteLine("Press Enter");
            Console.ReadLine();

            server.Close();
        }
    }

    [ServiceContract(CallbackContract = typeof(IBaseServiceCallback))]
    public interface IBaseService
    {
        [OperationContract]
        bool IsServiceInitiated();
    }

    public interface IBaseServiceCallback
    {
        [OperationContract]
        void TheCallback(string str);
    }

    //Change3
    //[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, IncludeExceptionDetailInFaults = true, AutomaticSessionShutdown = false, ConcurrencyMode = ConcurrencyMode.Multiple)]
    [CallbackBehavior]
    public class BaseServiceCallback : IBaseServiceCallback
    {
        public void TheCallback(string str)
        {
            Console.WriteLine(str);
        }
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, IncludeExceptionDetailInFaults = true, AutomaticSessionShutdown = false, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class BaseService : IBaseService
    {
        public bool IsServiceInitiated()
        {
            return true;
        }
    }

    public class CustomServer
    {
        private BaseService service;
        private ServiceHost host;

        public bool IsStarted
        {
            get { return host != null && host.State == CommunicationState.Opened; }
        }

        public CustomServer()
        {
            service = new BaseService();
            host = new ServiceHost(service, new Uri[] { new Uri("net.tcp://localhost:7780") });

            Type interfaceType = typeof(IBaseService);

            // Create service end point
            ServiceEndpoint endpointPipe = host.AddServiceEndpoint(interfaceType, new NetTcpBinding(), "CustomService");

            // Define TCP binding
            NetTcpBinding bindingPipe = (NetTcpBinding)endpointPipe.Binding;

            //Change1
            //bindingPipe.MaxReceivedMessageSize = long.MaxValue;
            //bindingPipe.MaxBufferPoolSize = long.MaxValue;
            //bindingPipe.MaxBufferSize = int.MaxValue;

            //bindingPipe.ReaderQuotas.MaxDepth = 2048;
            //bindingPipe.Security.Mode = SecurityMode.None;
            //bindingPipe.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
            //bindingPipe.Security.Message.ClientCredentialType = MessageCredentialType.None;

            // Increase MaxItemsInObjectGraph for all operations behaviors
            foreach (OperationDescription op in endpointPipe.Contract.Operations)
            {
                var dataContractBehavior = op.Behaviors.Find<DataContractSerializerOperationBehavior>();

                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                }
            }

            // In order to publish the service contract, it is important to publish the metadata
            ServiceMetadataBehavior smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>();

            if (smb == null)
            {
                smb = new ServiceMetadataBehavior();
            }

            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;

            host.Description.Behaviors.Add(smb);

            // Add MEX endpoint
            host.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexTcpBinding(), "net.tcp://localhost:7780/IDMmex");
        }

        public void Open()
        {
            if (host != null)
            {
                host.Open();
            }
        }

        public void Close()
        {
            if (host != null)
            {
                host.Close();
            }
        }
    }

    public class CustomClient
    {
        private IBaseService serviceProxy;
        private BaseServiceCallback callback;

        public CustomClient()
        {
            callback = new BaseServiceCallback();
        }

        public void Connect()
        {
            string serviceUrl = "net.tcp://localhost:7780/CustomService";

            // Create a channel in order to find the exact call back type.
            DuplexChannelFactory<IBaseService> sampleChannel = new DuplexChannelFactory<IBaseService>(callback, new NetTcpBinding(), new EndpointAddress(serviceUrl));

            Type duplexChannelFactory = typeof(DuplexChannelFactory<>).MakeGenericType(new Type[] { typeof(IBaseService) });

            object pipeFactory = Activator.CreateInstance(duplexChannelFactory, new object[] { callback, new NetTcpBinding(), new EndpointAddress(serviceUrl) });

            // Get the service end point
            ServiceEndpoint endpoint = (ServiceEndpoint)duplexChannelFactory.GetProperty("Endpoint").GetValue(pipeFactory, null);

            // Configure TCP binding
            //NetTcpBinding tcpBinding = (NetTcpBinding)endpoint.Binding;
            //tcpBinding.MaxReceivedMessageSize = long.MaxValue;
            //tcpBinding.MaxBufferPoolSize = long.MaxValue;
            //tcpBinding.MaxBufferSize = int.MaxValue;
            //tcpBinding.ReaderQuotas.MaxDepth = 2048;
            //tcpBinding.Security.Mode = SecurityMode.None;
            //tcpBinding.Security.Message.ClientCredentialType = MessageCredentialType.None;
            //tcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
            //tcpBinding.SendTimeout = TimeSpan.MaxValue;
            //tcpBinding.ReceiveTimeout = TimeSpan.MaxValue;
            //tcpBinding.OpenTimeout = TimeSpan.MaxValue;
            //tcpBinding.CloseTimeout = TimeSpan.MaxValue;

            // Increase MaxItemsInObjectGraph for all operations behaviors
            foreach (OperationDescription op in endpoint.Contract.Operations)
            {
                var dataContractBehavior = op.Behaviors.Find<DataContractSerializerOperationBehavior>();

                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
                }
            }

            //serviceProxy = sampleChannel.CreateChannel();

            // Create the channel to retrieve the pipe proxy object
            MethodInfo method = duplexChannelFactory.GetMethod("CreateChannel", new Type[0]);
            object pipeProxyObject = method.Invoke(pipeFactory, new object[] { });

            // Set the service proxy with the retrieved pipe proxy object
            serviceProxy = (IBaseService)pipeProxyObject;

            //Change2
            ((IChannel)serviceProxy).Open();

            // FREEZE HERE...
            bool isServerInitiated = serviceProxy.IsServiceInitiated();
        }
    }
}

A: I found a solution. I don't know exactely why this happens in this specific case with Windows Forms, but i have to start the server on a separated thread.
So I add in my form constructor this change:
CustomClient customClient = new CustomClient();
CustomServer customServer = new CustomServer();

Exception serverStartException = null;

System.Threading.Tasks.Task.Factory.StartNew(() =>
{
    try
    {
        customServer.Start();
    }
    catch (Exception e)
    {
        serverStartException = e;
    }
}

int maxTries = 5;
int currentTry = 0;

while (!customServer.IsStarted && currentTry < maxTries && serverStartException == null)
{
    System.Threading.Thread.Sleep(1000);
    currentTry++;
}

if (serverStartException != null)
{
    throw new Exception("The server couldn't start", serverStartException );
}
else if (!customServer.IsStarted)
{
    throw new Exception("The server couldn't start for unknown reason");
}

customClient.Connect();

if (customClient.ServiceProxy.IsServiceInitiated())
{
    MessageBox.Show("Server initiated");
}

And it's now working !!
If anyone knows why there is this behavior, I'm really interested.
Thanks


text:
Q: How to make Bluetooth work on Thinkpad T410? I'm using Ubuntu 12.10 and I have been trying to make my new keyboard (Logitech K810) and Nokia Phone 700, work with my Thinkpad T410. It just does not work. I have tried the instructions mentioned over here but it still doesn't work.
As for the phone it says that the phone is paired but then gives an error message when I try to transfer files and unexpectedly shuts down.
Any solutions? I'm desperate to make this keyboard work, and I really don't want to revert to Windows!

A: Transfering files to an Ubuntu system requires the Obex demon obexpushd to be up and running which is not the case by default. Which is a pity because it renders bluetooth file transfer useless for most users (Ubuntu should start the demon by default - at least if there is a bluetooth device present).
As for the keyboard - I couldn't pair it either. But I manage to use it anyway by:
hidd --search

The biggest drawback is that the connectin lasts unil reboot. One has to press the pairing key on the keyboard each time. Not good. Even worse - I do not know if the connection is encrypted. So I'd rather use the onscreen keyboard for password entry (especially in sensitive environments).


text:
Q: Subgroup generated by $S$ is $A_5$ Let $G = A_5$. I want to show that $ S = \langle(1,2)(3,4), (1,2,3,4,5)\rangle = A_5$, where $A_5$ is the alternating group.
My thoughts are that $A_5$ is simple, and if I can show that $S$ is a normal subgroup of $A_5$ then I am done. I have shown that $S$ is a subgroup of $A_5$, but I can't show it's normal.
Is this the correct way of tackling the question or is there a better way?

A: Clearly $|S|$ is a mutliple of $10$, so it must be $10,20,30$ or $60$.
Conjugating the second generator by the first does not give a power of the second generator, so $S$ does not have a unique Sylow $5$-subgroup, so $|S|$ is not equal to $10$ or $20$. Since $A_5$ is simple, it has no subgroup of order $30$, so $|S|=60$, and $S=A_5$.


text:
Q: RestKit merging context function is nil'ing properties So I create an object
MyObject *object = [mainManagedObjectContext insertNewObjectForEntityForName:@"MyObject"];

SomeOtherObject *someOtherObject = [s_mainManagedObjectContext insertNewObjectForEntityForName:@"MyObject"];

// in case you're wondering the inverse relationship of someOtherObject's relation ship to myObject is one to many
// so this should remove the idea that setting someOtherObjects.relationship to something else was causing the property to nil
object.oneToOneRelationShip = someOtherObject;

// simply used for debuggin
[object addObserver:self forKeyPath:@"oneToOneRelationShip" options:NSKeyValueObservingOptionInitial context:nil];

I then post the object using the object manager to post this thing
NSMutableURLRequest *request = [objectManager requestWithObject:object method:method path:path parameters:parameters];
[objectManager managedObjectRequestOperationWithRequest:request managedObjectContext:mainManagedObjectContext success:^{
    NSLog(@"blah");
}];

Now after this occurs the RestKit starts running operation objects which eventually calls save which works it way to this calls
-(void)handleManagedObjectContextDidSaveNotification:(NSNotification *)notification {
...
    [self.mergeContext mergeChangesFromContextDidSaveNotification:notification];
...

This is where my KVO observer code signals to me there's a change that was made
object.oneToOneRelationShip == nil

I believed I fixed my problem by simply saving to the persistent store before I post the object, but can someone please explain to me why this occurred. Am I doing something wrong? This bug was very confusing to me. I create objects off the main context so I don't know how this problem could occur.


text:
Q: view queries made? I know I can use get_num_queries() for the number of queries. However, how can I see what queries Wordpress actually makes? I've tried using $query but that didn't work.

A: See this codex page.
in wp-config.php:
define('SAVEQUERIES', true);

then in your template:
if (current_user_can('administrator')){
    global $wpdb;
    echo "
";
    print_r($wpdb->queries);
    echo "
";
}

or without the above SAVEQUERIES, you can still see just the main query:
global $wp_query;
echo $wp_query->request;

or to see all of $wp_query:

    <?php print_r($wp_query); ?>

A: There is another low level way of finding out what queries have been made throughout a request which was very useful for me in order to identify what was being inserted into the database upon submitting a form.
Basically what I did was one database dump before submitting the form, another database dump after submitting the form, then a diff of the two.
Although it may look too primitive, the result was exactly what I needed, without having to install any plugins or modify any code or wp-config.php.
The procedure I adopted was:

*

*Get the form ready to submit, with all fields filled.

*Do the first dump (change user, pass and dbname accordingly):
mysqldump -uuser -ppass dbname --skip-opt > /tmp/before.sql

*Submit the form.

*Do the second dump (change user, pass and dbname accordingly):
mysqldump -uuser -ppass dbname --skip-opt > /tmp/after.sql

*Compare before.sql and after.sql, analyzing the result in vim:
diff /tmp/before.sql /tmp/after.sql | vim -
Very useful for generating users migration scripts, for example.
Notes:

*

*--skip-opt generates a dump with one SQL instruction per line, so it's easier to see the changes when you run diff.

*| vim - makes vim read the output of diff directly into its buffer.

A: Milo's answer is right on. I would add that to save you some trouble, download the WordPress Debug Bar plugin. This plugin will add a little bar to the bottom of your front end pages and it will capture important debugging information, including queries made during the request. For it to work you need to make sure that the constants WP_DEBUG and SAVE_QUERIES are set to true in your wp-config.php file.

A: Similar to above I highly recommend query monitor plugin:
https://wordpress.org/plugins/query-monitor/
It has a lot of great features and really helps with local debugging.
More professional tools to use are different APMs, but they come paid. The best one I ever worked with was new rellic, but datadog APM works quite good well.


text:
Q: Grails in Action 2nd Edition - Error Generating Scaffold I've been painstakingly trying to teach myself Grails using the Groovy Grails Tool Suite.
GGTS 3.6.4
Grails 2.4.4
JDK 1.8.0_45
I'm at P.92 in the book and have 2 problems:

*

*When running the Grails console, I receive these errors:
Error |
2015-09-29 08:03:29,168 [main] ERROR hbm2ddl.SchemaExport  - HHH000389: Unsuccessful: alter table post drop constraint FK_kpfnivid38f5bwx3yl1lxeeae if exists
Error |
2015-09-29 08:03:29,168 [main] ERROR hbm2ddl.SchemaExport  - Table "POST" not found; SQL statement:
alter table post drop constraint FK_kpfnivid38f5bwx3yl1lxeeae if exists [42102-176]
Error |
2015-09-29 08:03:29,168 [main] ERROR hbm2ddl.SchemaExport  - HHH000389: Unsuccessful: alter table post_tags drop constraint FK_rf0kr7eqk5xoalmc4gigdwg3p if exists
Error |
2015-09-29 08:03:29,168 [main] ERROR hbm2ddl.SchemaExport  - Table "POST_TAGS" not found; SQL statement:
alter table post_tags drop constraint FK_rf0kr7eqk5xoalmc4gigdwg3p if exists [42102-176]
Error |
2015-09-29 08:03:29,168 [main] ERROR hbm2ddl.SchemaExport  - HHH000389: Unsuccessful: alter table post_tags drop constraint FK_n8k2owli9ecanh4phj01mddvv if exists
Error |
2015-09-29 08:03:29,168 [main] ERROR hbm2ddl.SchemaExport  - Table "POST_TAGS" not found; SQL statement:
alter table post_tags drop constraint FK_n8k2owli9ecanh4phj01mddvv if exists [42102-176]
Error |
2015-09-29 08:03:29,168 [main] ERROR hbm2ddl.SchemaExport  - HHH000389: Unsuccessful: alter table profile drop constraint FK_c1dkiawnlj6uoe6fnlwd6j83j if exists
Error |
2015-09-29 08:03:29,168 [main] ERROR hbm2ddl.SchemaExport  - Table "PROFILE" not found; SQL statement:
alter table profile drop constraint FK_c1dkiawnlj6uoe6fnlwd6j83j if exists [42102-176]
Error |
2015-09-29 08:03:29,168 [main] ERROR hbm2ddl.SchemaExport  - HHH000389: Unsuccessful: alter table tag drop constraint FK_151ooxskkpn49blwsh7mjwysx if exists
Error |
2015-09-29 08:03:29,168 [main] ERROR hbm2ddl.SchemaExport  - Table "TAG" not found; SQL statement:
alter table tag drop constraint FK_151ooxskkpn49blwsh7mjwysx if exists [42102-176]
Error |
2015-09-29 08:03:29,168 [main] ERROR hbm2ddl.SchemaExport  - HHH000389: Unsuccessful: alter table user_user drop constraint FK_s7pwk9swjfqs0w7ub9tt5s47y if exists
Error |
2015-09-29 08:03:29,168 [main] ERROR hbm2ddl.SchemaExport  - Table "USER_USER" not found; SQL statement:
alter table user_user drop constraint FK_s7pwk9swjfqs0w7ub9tt5s47y if exists [42102-176]
Error |
2015-09-29 08:03:29,168 [main] ERROR hbm2ddl.SchemaExport  - HHH000389: Unsuccessful: alter table user_user drop constraint FK_1hl85r166108l1vgkxycm3cq0 if exists
Error |
2015-09-29 08:03:29,168 [main] ERROR hbm2ddl.SchemaExport  - Table "USER_USER" not found; SQL statement:
alter table user_user drop constraint FK_1hl85r166108l1vgkxycm3cq0 if exists [42102-176]

My guess is that the problem is because I've not changed my DataSource.groovy file to 'update' instead of 'create-drop' and bring the DB out of memory.
I haven't tested that theory because the Grails console still ran, which then led to my second error.

*We're told to generate 4 controllers, using the following commands:
create-scaffold-controller com.grailsinaction.User
create-scaffold-controller com.grailsinaction.Profile
create-scaffold-controller com.grailsinaction.Post
create-scaffold-controller com.grailsinaction.Tag

Each time, I receive an "EOF expected" error:
1 compilation error:

expecting EOF, found 'com' at line: 1, column: 28

These two errors don't seem related, and rather than just skip it, I'd really like to understand what's going on...
Any help would be appreciated.

A: DataSource.groovy file to 'update' instead of 'create-drop' and bring the DB out of memory.
This is assuming you have configured your data source to connect to a real database.
I can see hbm2ddl is the logs above and for your internal in memory DB it should really should be 'create-drop'
DataSource.groovy file to 'update' tells your application to only update existing tables, this will not create any new tables.
In the case of a real life application that connects to lets say MySQL. This setting would equate to you then also manually updating the database and creating any new tables that you have designed in development.
DataSource.groovy file to 'create-drop' is as the name states, it will create new tables and drop entries, so in the case of development environment and even some other environments such as test you may be happy to leave it on create-drop and let grails generate the tables.
The only 1 thing to watch for is if you have lets assume you have some domain class that has a
Boolean isValid

static constraints {
 isValid(nullable:false)
}

If you later decide no actually it should be nullable in the case of the MySQL example, you would have to log into it and manually tweak it since its already created. in the case of inline memory (your example) who cares next run-app =  fresh db .
In regards to :

create-scaffold-controller

This is a new one, http://grails.github.io/grails-doc/2.4.4/ref/Command%20Line/create-scaffold-controller.html It looks correct, what you are executing.
But to try to simplify or expand the horizon, if I understand correctly (I haven't started to delve into what that command does), but surely can't be far off of doing something like this manually.

grails create-controller com.grailsinaction.User

Then going to the user class and doing:
class UserController {
  static scaffold = true
}

Save repeat for each one and then continue with the docs..
Learn more about the concept of scaffolding here:
http://grails.asia/grails-tutorial-for-beginners-scaffolding/
http://tutorials.techmytalk.com/2014/07/19/grails-scaffolding-controllers-and-views/
Also if you are using ggts go over the domain class with your right mouse button choose I think grails generate controllers and views
This will be the alternative to scaffolding which is what scaffolding gives you dynamically is then generated for you to use and edit. Its a good way it get into grails since it gives you stuff you can see/edit and learn from.
Scaffolding just hides all of that and is tidy way of hiding the generated stuff.


text:
Q: How do I load an image from a webserver to clickable Android widget Im trying to load an image from my webserver and display it as an Android widget. Im trying to have the widget update every 60 minutes as well since the image can change. The image should be clickable as well. I had the clickable part working perfectly with a button, but when I change it to an ImageView instead in my layout, the click portion ceases to work. And I cannot get the image to load at all. Here is my code
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Toast.makeText(context, "onUpdate", Toast.LENGTH_SHORT).show();

RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
Intent i = new Intent(context, LoadPage.class);
i.setAction(ACTION_WIDGET_LOAD);

PendingIntent pi = PendingIntent.getActivity(context, 0, i, 0);
remoteViews.setOnClickPendingIntent(R.id.button, pi);

appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);

Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyButton(context, appWidgetManager), 1, 5000);
}

private class MyButton extends TimerTask {
RemoteViews remoteViews;
AppWidgetManager appWidgetManager;
ComponentName thisWidget;

public MyButton(Context context, AppWidgetManager appWidgetManager) {
  this.appWidgetManager = appWidgetManager;
  remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
  thisWidget = new ComponentName(context, ButtonWidget.class);
}

@Override
public void run() {
  Bitmap buttonimg = null;
  try {
    String name = "http://badams.ca/otwstats/get_stats.php?user=badams";
    URL url_value = new URL(name);
    buttonimg = BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }

  i++;
  remoteViews.setBitmap(R.id.button, "setButton", buttonimg);
  appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}

A: You can set your image,as background of your clickable part.

A: I managed to fix this. I was setting the image incorrectly.
Replaced:
remoteViews.setBitmap(R.id.button, "setButton", buttonimg);

with:
remoteViews.setImageViewBitmap(R.id.button, buttonimg);

and that worked flawlessly!


text:
Q: Parity check Matrix for Plotkin construction of linear codes Let's say I have 2 linear codes, $C_1 = [n,k_1]$ and $C_2 = [n,k_2]$, and I have the parity check matricies $H_1,H_2$ for them. I use the Plotkin construction to create the code $C$ out of them (for every $u\in C_1$, $v\in C_2$, $(u|u+v)\in C$). How can I construct the parity check matrix $H$ of $C$?

A: The $k\times n$ generator matrix $\mathbf G$ and the $(n-k)\times n$
parity-check matrix $\mathbf H$ of a $[n,k,d]$ linear code satisfy
$$\mathbf{GH}^T = \mathbf 0.$$
The Plotkin construction $[u \mid u+v]$ where
$u \in \mathcal C[n,k_1,d_1]$ and $v \in \mathcal C[n,k_2,d_2]$ gives
a $[2n,k_1+k_2]$ code whose $2n\times (k_1+k_2)$generator matrix is
$$\mathbf G = \left[\begin{matrix}
\mathbf G_1 & \mathbf G_1\\\mathbf 0&\mathbf G_2\end{matrix}\right]$$
and whose parity-check matrix is
$$\mathbf H = \left[\begin{matrix}
\mathbf H_1 & \mathbf 0\\\mathbf H_2&-\mathbf H_2\end{matrix}\right].$$
Note that
\begin{align}\mathbf{GH}^T &= \left[\begin{matrix}
\mathbf G_1 & \mathbf G_1\\\mathbf 0&\mathbf G_2\end{matrix}\right]
\left[\begin{matrix}
\mathbf H_1 & \mathbf 0\\\mathbf H_2&-\mathbf H_2\end{matrix}\right]^T\\
&= \left[\begin{matrix}
\mathbf G_1 & \mathbf G_1\\\mathbf 0&\mathbf G_2\end{matrix}\right]
\left[\begin{matrix}
\mathbf H_1^T & \mathbf H_2^T\\\mathbf 0&-\mathbf H_2^T\end{matrix}\right]\\
&= \left[\begin{matrix}
\mathbf G_1\mathbf H_1^T & \mathbf G_1\mathbf H_2^T-\mathbf G_1\mathbf H_2^T\\
\mathbf 0&-\mathbf G_2\mathbf H_2^T\end{matrix}\right]\\
&= \large{\mathbf 0}.
\end{align}


text:
Q: Dynamic  not clickable I have done the following code in php so that I can click on the arrow and a form opens below
    echo '
'
    .''
    .'
 '.$uname.'
 '
    .'
'.$date.'
'
    .'
'.$content.'
'
    .'';

My javascript code:
$(document).ready(function() {
  $("a#reply").one("click" , function() {
    var comCode = $(this).attr("name");

    var parent = $(this).parent();
    var str1 = "new-reply";
    var str2 = "tog";
    var res = str1.concat(i);
    var tes = str2.concat(i);

// Create a new editor inside the
, setting its value to html

    parent.append("
<form action='index.php' method='post' id='"+tes+"'><input class='iptext2' type='text' name='uname2' id='uname2' placeholder='Your Name' required />

<textarea class='ckeditor' name='editor' placeholder='Your Query' id='"+res+"' required></textarea><input type='hidden' name='code' value='"+comCode+"' />
<input type='submit' class='form-submit' id='form-reply' name='new_reply' value='Reply' /></form>")

    CKEDITOR.replace(res);

    /*
    var x = document.getElementById("tes");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
    */

    i++;

   });
})

The following is my css code applied to the anchor tag:
.al {
font-size:11.2px;
text-transform: uppercase;
text-decoration: none;
color:#222;
cursor:pointer;
transition:ease 0.3s all;
}
.al:hover {
color:#0072bc;
}
.link-reply {
    color:#767676;
}

Here the arrow icon is displayed but is not clickable

A: Use on for dynamic created events on DOM.
$(document).on("click","a#reply" , function() {
   console.log('a#reply => clicked!')
});

Or
$(body).on("click","a#reply" , function() {
       console.log('a#reply => clicked!')
});

A: Your code fails, because your  elements are created dynamically, whereas the event listener is added only to the elements available when the document has loaded.
In order to get your code to work, you need to use event delegation; that is to add the event listener to a common static ancestor, such as the document or the body, that will in turn delegate it to your target elements.
The methods you can use to achieve this effect in jQuery are on and one, with the latter fitting your case better, if you are trying to attach one-time event listeners.
Code:
$(document).one("click", "a#reply", function() {
   // ...
});


text:
Q: RSpec shared_helpers issue New rails project, installed/configured RSpec 2.3.0, created one model.  When I run rake spec, it can't load shared_helpers.rb.  Any ideas?
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby -S bundle exec rspec "./spec/models/school_spec.rb"
/Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/shared_helpers.rb:2:in `require': no such file to load -- rubygems (LoadError)
 from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/shared_helpers.rb:2
 from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/setup.rb:1:in `require'
 from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/setup.rb:1
rake aborted!
ruby -S bundle exec rspec "./spec/models/school_spec.rb" failed

A: Solved this by using RVM with Ruby 1.8.7.  I was using system ruby prior.


text:
Q: Where should flutter assets of flutterappB go if app is included in flutterappA as a package? I'm assuming that we can have one flutter app embededded in another, for example if I have a reusable menu that has an image that I want to use in multiple apps.
So, FlutterAppA references FlutterAppB and is included in FlutterAppA's pubspec.yaml.  FlutterAppB includes the image in its asset folder, declared in the pubspec file and defines a widget that displays that asset.  I want to access that widget from B (displaying the widget with the asset)
B's pubspec
flutter:
  assets:
    - assets/smile.gif

A's pubspec
dependencies:
  flutter:
    sdk: flutter
  flutter_app_b:
    path: ../flutter_app_b/

When B is run on its own the image is displayed.
class MyApp extends StatelessWidget {
  Widget build(BuildContext context) => MaterialApp(
          home: SmileAssetImage());
}
class SmileAssetImage extends StatelessWidget {
  Widget build(BuildContext context) => Image.asset('assets/smile.gif');
}

however when it is accessed in FlutterAppA it cannot find the asset and an 'unable to load Asset exception is thrown'.
Is the asset in the correct place, should it be in both asset folders and/or both pubspec folders?

A: Right, it seems like the assets should be included and declared in whichever app is actually run (if running A then the assets needs to be defined in app A, if running B then the assets need to be in app B).  The flutter clean command seemed to be necessary


text:
Q: Custom switch appears huge using custom drawables I'm making a custom switch using 3 drawable files. Two icons, On and Off, represented by 89x89 images, and a custom Track drawable resource (colored black) which is 171x93. When I set my custom drawables to the switch, it stretches to the size of the images. How can I down-scale these images to fit exactly and no bigger than the text itself?
 This is my switch xml:
<Switch
        android:layout_width="220dp"
        android:layout_height="wrap_content"
        android:id="@+id/switchAnimation"
        android:thumb="@drawable/my_switch"
        android:switchMinWidth="55dp"
        android:track="@drawable/toggle_track"
        android:textOff=""
        android:textOn=""
        android:textColor="#FFF"/>

 The drawable of the switch my_switch.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/toggle_on" android:state_checked="true"/>
    <item android:drawable="@drawable/toggle_off" android:state_checked="false"/>
</selector>

 The drawable of the track:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true"  android:drawable="@drawable/toggle_track" />
    <item                               android:drawable="@drawable/toggle_track" />
</selector>

I have tested this on two emulator devices, Galaxy nexus API 21, and Nexus 4 API 19. Another question, I've also notices that upon a click on the switch in API 19 devices there is no smooth transition animation like in API 21 (instead the icons just appear and disappear), is this normal?!

![nenxus 4 API 19 with out custom track][2]

EDIT
I made the resources a lot smaller, 25x25, now it appears the right size, but it looks a little bit pixelated. Is there any way to down-scale the quality icons to a smaller size?

A: Simply add stroke with zero opacity:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_enabled="true">
        <shape android:shape="oval" android:visible="true">
            <solid android:color="@android:color/white" />
            <size android:width="20dp" android:height="20dp" />
            <stroke android:width="7dp" android:color="#00000000" />
        </shape>
    </item>
    <item android:state_checked="false" android:state_enabled="false">
        <shape android:shape="oval" android:visible="true">
            <solid android:color="#ccc" />
            <size android:width="20dp" android:height="20dp" />
            <stroke android:width="7dp" android:color="#00000000" />
        </shape>
    </item>
</selector>

Sample Image


text:
Q: Changing the written data in a Writer monad Given a Writer monad action, I want to modify it by mapping a function over the written data inside the monad action.
Something like:
retell :: (w -> w') -> Writer w a -> Writer w' a

Does such a function already exists in the libraries? If not, how can one be defined?

A: retell f = Writer . second f $ runWriter

There is also a mapWriter function provided by the libraries. So you could do this:
retell = mapWriter . second

The second function is in Control.Arrow, but you can define a less general version of it yourself like this:
second f (a, b) = (a, f b)


text:
Q: Responsive grid in just 1 row I've been using bootstrap a while but can't get my head around this.
So, I have 1 row with 4 cols in it, the responsive part this time is that as I keep making size of screen smaller, I want to drop the elements that don't fit. That means that I start showing 4 images one next to the other, later on if screen is smaller I just want to show first 3, and in the end probably only 1.
Is is possible to do this with CSS or am I going to need some Javascript.
I hope I explained well enought.

A: To completely hide or show based of the display size, use :
visible-xs-*, visible-sm-*, visible-md-*, visible-lg-*, hidden-xs, hidden-sm, hidden-md, hidden-lg
* corresponds to block, inline and inline-block, depending on what you want.

        1

        2

        3

        4

A: If you want div 4 to disappear for a small screen you can simply hide it for small screens.
http://getbootstrap.com/css/#responsive-utilities

    1

    2

    3

    4


text:
Q: PHP: `move_uploaded_file` isn't properly accessing `tmp_name` of user submited file I've been struggling for the past couple days to submit an image through a form and have my php script save it in the designated directory. I've tried using $.ajax, I've tried using XMLHttpRequest, and now I've just copied a simpler script from here and tweaked it.
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file) evaluates to falseand I don't believe any warnings are given, so according to the documentation, there was a problem accessing the file.
The script response is
/private/var/tmp/phpwwBaBr
Sorry, there was an error uploading your file.

Also, the error code from echo $_FILE['fileToUpload']['error']; is 0, which means the upload is successful, yet still no file in ../includes/galleryImages/.

Here's the code:
<form action="archive_upload.php" id='file_form' method="post" enctype="multipart/form-data" accept-charset='UTF-8'>
     Select image to upload:
     <input type="file" name="fileToUpload" id="fileToUpload">
     <input type="submit" value="Upload Image" name="submit">
</form>

<?php
    $target_dir = "../includes/galleryImages/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            $uploadOk = 1;
        } else {
            $uploadOk = 0;
        }
    }

    echo $_FILES["fileToUpload"]["tmp_name"].'
';

    /* This is the line that returns false */
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo basename( $_FILES["fileToUpload"]["name"] ). " has been uploaded.
";

    } else {
        echo "Error uploading file.
";
    }
?>


text:
Q: VirtualBox guest Win10 @ Linux host hangs big time at startup, how to troubleshoot? I have a VirtualBox VM running Windows 10 on a Linux host. It used to work just fine, but this day when I started it it hangs big time.
The VM's window is just a black square, and also the host hangs up.
I can't even switch to another console
with Ctrl+Alt+F6.
How can I start troubleshooting this? (I don't have any snapshots to go back to.)

UPDATE: After:
Removed all Virtualbox packages:
apt auto-remove 'virtualbox*'

Reinstalled latest version (first add repositiory of needed (see virtualbox.org):
apt install virtualbox-5.2

It works again as of 2018-02-20 on 4.13.0-32-generic #35~16.04.1-Ubuntu.

A: Kernel update in last days is a reason. Try to boot to older kernel. I think some meltdown patch or something similar is a source of this problem.
How to boot to an older kernel

*

*Reboot and hold Shift when computer starts. Grub-menu opens.

*Choose "Advanced ..."

*Choose your preferred old kernel to boot from it.

A: This can be due to a recent kernel update. You can try booting an older kernel.
You can create a GRUB menu entry for an older kernel (anything less than 4.13) by doing the following:
1) Find out which kernels you have installed by running this in the terminal:
$ls /boot/vmlinuz*

2) Then find the disk UUID that is you system root (not the swap):
$ll /dev/disk/by-uuid

3) Then then in a text file substitute those values into the menu entry below:
menuentry "Linux Mint 18.3 Cinnamon 64-bit, with Linux 4.10.0-38-generic" {
        linux   /boot/vmlinuz-X.X.X-XX-generic root=UUID=XXXX-YYYY ro  quiet splash
        initrd  /boot/initrd.img-X.X.X-XX-generic
}

4) Open the custom GRUB menu for editing:
$sudo nano /etc/grub.d/40_custom

5) Copy and paste your modified menu entry into 40_custom save. Then run:
$sudo update-grub

You could even set that to the grub default if you wanted too.
I would use this kernel with caution as time goes on for obvious reasons. Hopefully a patch for the patch will come soon but I wouldn't hold my breath.


text:
Q: Retrieving scope from oAuth token in Python I am working on creating an api using aws api gateway service. Api gateway is backed by a lambda function written in python.
My Api gateway would be secure and I am using cognito authentication/authorization where consumers would first retrieve oauth token and pass that as Authorization header
I am planning to extend use of scope and planning to map this to my backend service to further narrow down access to underlying resources, if I can extract scope programatically
ex:
if scope is  myscope/tx - only get all transactions to consumer etc
My Question is that how do I retrieve this scope from oauth token ? I googled and found similar question for java , but unfortunately this was not helpful in my case, here is that url How to retrieve scopes from OAuth token within Spring boot SSO + zuul
I am also aware of using https://jwt.io/ to find this manually but in my case I am looking for a programmatic solution in python
It would be great if someone have ever done this ?
-Thanks
I googled and found similar question for java , but unfortunately this was not helpful in my case, here is that url How to retrieve scopes from OAuth token within Spring boot SSO + zuul
I am also aware of using https://jwt.io/ to find this manually but in my case I am looking for a programmatic solution in python
I am expecting solution in python


text:
Q: return first element from array as computed property from Ember controller subclass I am trying to return the first element of my array as a computed property to my template from my controller. My code is below. I am 100% about my array and template. Problem is my syntax about in the controller.
Basically my array is works made of Work objects. And I would ideally return the first element Work. Is that even possible in javascript?
Best.
//controller works.js
import Ember from "ember";
  export default Ember.Controller.extend({
  firstElement: function () {
    var arr = this.get('model');
    return arr[0];
    console.log(arr[0]);
  }.property('Work')
});

//template works.js
<div class="right">
  {{#liquid-with model as |currentModel|}}
    {{firstElement}}
  {{/liquid-with}}
</div>

//route works.js
import Ember from 'ember';

var Work = Ember.Object.extend({
  name: '',
  year: '',
  description:'',
  image:'',
  logo:'',

  work_id: function() {
    return this.get('name').dasherize();
  }.property('name'),

});

var minibook = Work.create({
  id: 1,
  name: 'MINIBOOK',
  year: '2014',
  description:'MiniBook is an iphone app that explores storytelling in its own format. The format',
  image:'assets/images/minibook_iphone.png',
  logo:'assets/images/minibook_logo.png'
});

var poetics = Work.create({
  id: 2,
  name: 'POETICS',
  year: '2013',
  description:'Lorem Ipsum Poetics',
  image:'assets/images/poetics_iphone.png',
  logo:'assets/images/poetics_logo.png'
});

var WorksCollection = Ember.ArrayProxy.extend(Ember.SortableMixin, {
  sortProperties: ['id'],
  sortAscending: true,
  content: []
 });

var works = WorksCollection.create();

works.pushObjects([poetics, minibook]);

export default Ember.Route.extend({
  model: function() {
    return works;
  }

});

A: This would work.
Long way (just to improve your computed property code):
// controller work.js
import Ember from "ember";
export default Ember.Controller.extend({
  firstElement: function () {
    return this.get('model').get('firstObject'); // or this.get('model.firstObject');
  }.property('model.[]')
});

1) you set works as model in route, so you could get it as model in controller
2) .property(model.[]) means computed property on array, so adding and deleting array element will fire update. You could also choose some specific property i.e. .property(model.@each.modelProperty)
3) fistObject is proper method (not [0]), since you are working with Ember.ArrayProxy, see http://emberjs.com/api/classes/Ember.ArrayProxy.html
4) you could use {{firstElement}} in template
Lazy way:
1) set model in route as array or as promise resolved in array
// works = ... as is
export default Ember.Route.extend({
  model: function() {
    return works;
  }
});

2) get model.firstObject in directly in template
//template works
{{model.firstObject}} {{!-- first object of model array --}}
{{model.firstObject.name}}  {{!-- name of first object --}}

UPDATE:
    use proper iteration syntax http://ef4.github.io/liquid-fire/#/helpers/liquid-with/10
{{#liquid-with model as currentModel}}
  {{currentModel.firstObject.name}}
{{/liquid-with}}

A: A bit more updated (or different) example
import Controller from '@ember/controller';
import { readOnly } from '@ember/object/computed';

export default Controller.extend({
  firstElement: readOnly('model.firstObject')
});

Or if you want bidirectional data flow (can set firstElement)
import Controller from '@ember/controller';
import { alias } from '@ember/object/computed';

export default Controller.extend({
  firstElement: alias('model.firstObject')
});


text:
Q: Gradle plugin 3.0.0 beta 4: "buildTypeMatching has been removed. Use buildTypes..fallbacks" After updating to Gradle plugin 3.0.0 beta 4 our build failed with the following message:

buildTypeMatching has been removed. Use buildTypes.<name>.fallbacks

Our libraries have release and debug buildTypes, but our app has two additional buildTypes: 'releaseWithLogs' and 'debugMinified'.
Snippet of our app Gradle file:
android {
    // ...
    buildTypeMatching 'releaseWithLogs', 'release'
    buildTypeMatching 'debugMinified', 'debug'

    buildTypes {
        debug {
            // ...
        }
        debugMinified {
            // ...
        }
        release {
            // ...
        }
        releaseWithLogs {
            // ...
        }
    }
}

A: After some investigation, the following announcement has been found: Android Studio 3.0 Beta 4 is now available. There, it mentions:

You now provide fallbacks for missing build types and flavors using matchingFallbacks (which replaces buildTypeMatching and productFlavorMatching). You also provide the default selection and fallbacks for missing dimensions using missingDimensionStrategy (which replaces flavorSelection).

So, our previous app build.gradle gets converted to:
android {
    // ...
    //buildTypeMatching 'releaseWithLogs', 'release' // remove this
    //buildTypeMatching 'debugMinified', 'debug'     // remove this

    buildTypes {
        debug {
            // ...
        }
        debugMinified {
            // ...
            matchingFallbacks = ['debug']    // instead use this
        }
        release {
            // ...
        }
        releaseWithLogs {
            // ...
            matchingFallbacks = ['release']  // instead use this
        }
    }
}

Notice that, instead of saying that buildType releaseWithLogs will also match with release (buildTypeMatching 'releaseWithLogs', 'release'), we specify the match inside the buildType itself. Same for debugMinified matching debug. Also notice that there's no need to include this in release and debug buildTypes, as they already match.


text:
Q: Pygame traceback error How do i fix this error, this is the message that i get:
Traceback (most recent call last):
File "C:\Users\Games\Desktop\hendeagon.py", line 28, in <module>
font = pygame.font.SysFont(None, 48)
File "C:\Python33\lib\site-packages\pygame\sysfont.py", line 614, in SysFont
return constructor(fontname, size, set_bold, set_italic)
File "C:\Python33\lib\site-packages\pygame\sysfont.py", line 537, in font_constructor
font = pygame.font.Font(fontpath, size)
pygame.error: font not initialized

i need this error fixed for homework by tomorrow.
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
TEXTCOLOR = (255, 255, 255)
WINDOWWIDTH = 500
WINDOWHEIGHT = 400

windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)

def drawText(text, font, surface, x, y):
    textobj = font.render(text, 1, TEXTCOLOR)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit(textobj, textrect)

font = pygame.font.SysFont('comicsansms', 48)
basicFont = pygame.font.SysFont(None, 42)
drawText('8', font, windowSurface, (WINDOWWIDTH / 2.5), (WINDOWHEIGHT / 3))
windowSurface.fill(BLACK)

pygame.draw.polygon(windowSurface, GREEN, ((158, 80), (181, 88), (214, 111), (229, 153),     (216, 191), (181, 212), (135, 207), (102, 181), (89, 149), (102, 109), (130,88)))

pixArray = pygame.PixelArray(windowSurface)
pixArray[480][380] = BLACK
del pixArray
windowSurface.blit(text, textRect)
pygame.display.update()

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

Thank you for attempting to fix this problem that i am having in pygame

A: You can make your drawText method return your textobj and textrect and then use that as follows:
def drawText(text, font, surface, x, y):
    textobj = font.render(text, 1, TEXTCOLOR)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit(textobj, textrect)
    return textobj, textrect

text, text_rect = drawText('8', font, windowSurface, (WINDOWWIDTH / 2.5), (WINDOWHEIGHT / 3))

...

windowSurface.blit(text, text_rect)

A: I think you want to try something like:
import pygame, random, sys
from pygame.locals import *

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (197, 153, 114)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
TEXT_COLOR = (255, 255, 255)
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 400

def draw_text(text, font, surface, x, y):
    text_obj = font.render(text, 1, TEXT_COLOR)
    text_rect = text_obj.get_rect()
    text_rect.topleft = (x, y)
    surface.blit(text_obj, text_rect)

pygame.init()
pygame.display.set_caption('polygon!')
windowSurface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), 0, 32)
basic_font = pygame.font.SysFont(None, 42)
windowSurface.fill(BLACK)

POLYGON_COORDINATES = (
    (158, 80), (181, 88),
    (214, 111), (229, 153),
    (216, 191), (181, 212),
    (135, 207), (102, 181),
    (89, 149), (102, 109),
    (130, 88))

pygame.draw.polygon(windowSurface, GREEN, POLYGON_COORDINATES)

draw_text('8', basic_font, windowSurface,
          (WINDOW_WIDTH / 2.5), (WINDOW_HEIGHT / 3))

pixArray = pygame.PixelArray(windowSurface)
pixArray[480][380] = WHITE
del pixArray

pygame.display.update()

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()


text:
Q: nuxt.js localhost:3000 not running As I'm currently going from React to Vue.js, i failed with running my localhost on Port 3000. Getting the below error message. Looks like there is a problem with the server.
Down below a added the installation process so that it gets clearer how it's installed.
Also you can find the error message when running npm run dev.
Any suggestions what the problem could be?
Installation process
create-nuxt-app v5.0.0
✨  Generating Nuxt.js project in cryptocheck24.org
? Project name: cryptocheck24.org
? Programming language: JavaScript
? Package manager: Npm
? UI framework: None
? Template engine: HTML
? Nuxt.js modules: (Press <space> to select, <a> to toggle all, <i> to invert se
lection)
? Linting tools: (Press <space> to select, <a> to toggle all, <i> to invert sele
ction)
? Testing framework: Jest
? Rendering mode: Universal (SSR / SSG)
? Deployment target: Server (Node.js hosting)
? Development tools: (Press <space> to select, <a> to toggle all, <i> to invert
selection)
? Continuous integration: None
? Version control system: Git

Error message
> cryptocheck24.org@1.0.0 dev
> nuxt

   ╭───────────────────────────────────────╮
   │                                       │
   │   Nuxt @ v2.15.8                      │
   │                                       │
   │   ▸ Environment: development          │
   │   ▸ Rendering:   server-side          │
   │   ▸ Target:      server               │
   │                                       │
   │   Listening: http://localhost:3000/   │
   │                                       │
   ╰───────────────────────────────────────╯

ℹ Preparing project for development                                   16:25:39
ℹ Initial build may take a while                                      16:25:39
ℹ Discovered Components: .nuxt/components/readme.md                   16:25:39
✔ Builder initialized                                                 16:25:39
✔ Nuxt files generated                                                16:25:39

● Client █████████████████████████ compiling (0%)

◯ Server

node:internal/crypto/hash:67
  this[kHandle] = new _Hash(algorithm, xofLen);
                  ^

Error: error:0308010C:digital envelope routines::unsupported
    at new Hash (node:internal/crypto/hash:67:19)
    at Object.createHash (node:crypto:133:10)
    at module.exports (/Users/remo/Desktop/cryptocheck24.org/node_modules/webpack/lib/util/createHash.js:135:53)
    at NormalModule._initBuildHash (/Users/remo/Desktop/cryptocheck24.org/node_modules/webpack/lib/NormalModule.js:417:16)
    at handleParseError (/Users/remo/Desktop/cryptocheck24.org/node_modules/webpack/lib/NormalModule.js:471:10)
    at /Users/remo/Desktop/cryptocheck24.org/node_modules/webpack/lib/NormalModule.js:503:5
    at /Users/remo/Desktop/cryptocheck24.org/node_modules/webpack/lib/NormalModule.js:358:12
    at /Users/remo/Desktop/cryptocheck24.org/node_modules/webpack/node_modules/loader-runner/lib/LoaderRunner.js:373:3
    at iterateNormalLoaders (/Users/remo/Desktop/cryptocheck24.org/node_modules/webpack/node_modules/loader-runner/lib/LoaderRunner.js:214:10)
    at Array.<anonymous> (/Users/remo/Desktop/cryptocheck24.org/node_modules/webpack/node_modules/loader-runner/lib/LoaderRunner.js:205:4) {
  opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
  library: 'digital envelope routines',
  reason: 'unsupported',
  code: 'ERR_OSSL_EVP_UNSUPPORTED'
}

A: Since the v5, a Node v14 version is required: https://github.com/nuxt/create-nuxt-app/releases/tag/v5.0.0
So you can either try that. It works on my side with the latest LTS: Node v16.

Or fallback into using the v4 of the CLI.
That version runs perfectly for ages already
npx create-nuxt-app my-cool-app

and is well battle-tested!
PS: I've opened this issue btw: https://github.com/nuxt/create-nuxt-app/issues/1014


text:
Q: Alternatives to replace ExtJS 1.2 Im thinking in replace ExtJS 1.2 in a project that does not work in IE9 (only works in compatibility view and is so slowly  loading a tree). What JS frameworks are better (and trying to replacing as little posible the code?
I see ExtJS 4 but has changed a lot compared with ExtJS 1.2


text:
Q: php mysqli select function not working So I need some help with the code below, I have simple select function that's not working for some strange reason though everything seems OK and I can't figure out why it prints nothing when called.
function getRegNo($vehicleID){
    if($stmt = $mysqli->prepare("SELECT regNo FROM vehicles WHERE id = ?")){
    $stmt->bind_param('s', $vehicleID);
    $stmt->execute();
    $stmt->bind_result($regNo);
    $stmt->fetch();

    return $regNo;
    }
}

Any assistance you can offer will be highly appreciated.

A: $mysqli isn't defined.
Add it as a global at the top of your function.
global $mysqli;

This relies on you already making $mysqli global which I'm assuming is the case.

A: once try this (assuming the id is an integer)
 $stmt->bind_param('i', $vehicleID);

and set $mysqli as global or pass it as an parameter to the function


text:
Q: " ... cannot be used as a JSX component." warning When I prepare a component like the one below, I get the warning in the picture. It doesn't give any warning if I create it with if instead of switch-case. Why does it give this warning when I use switch-case? How should I write the switch case so it does not give a warning?

import React from "react"
import { Text } from "react-native"

const AppHeader = () => {

    const TextOne = () => (
        <Text>AAA</Text>
    )

    const TextTwo = () => (
        <Text>BBB</Text>
    )

    const TextComp = ({ text }: { text: string }) => {
        switch (text) {
            case "A":
                return <TextOne />
            case "B":
                return <TextTwo />
        }

        // if (text == "A") {
        //     return <TextOne />
        // } else {
        //     return <TextTwo />
        // }
    }

    return (
        <TextComp text={"A"} />
    )
}

export default AppHeader

A: You should add default case with null in the switch-case
The error is because it returns undefined if text is not both "A" and "B", and it does not match type.


text:
Q: Ubuntu on Mac / Parallels, screen resolution I have just downloaded Ubuntu onto my mac using parallels. The only issue is that the Ubuntu window is about an inch too small each side. I have checked the display settings and the only display setting I can choose is 800x600(4:3). I have attempted to change this using:
Change screen resolution:
Create a new resolution using cvt:
$ cvt 1600 900 75
1600x900 74.89 Hz (CVT 1.44M9) hsync: 70.55 kHz; pclk: 151.25 MHz
Modeline "1600x900_75.00" 151.25 1600 1704 1872 2144 900 903 908 942 -hsync +vsync

Add a new mode to the existing list (newmode is the name and remaining portion is):
$ sudo xrandr --newmode "1600x900_75.00" 151.25 1600 1704 1872 2144 900 903 908 942 -hsync +vsync

but once I enter the newmode an error message pops up saying "failed to get size of gamma output default".
I am trying to get this working on my laptop not a monitor.


text:
Q: Notice: Undefined index: REDIRECT_URL in /home/webccans/public_html/index.php I am getting this error:

Notice: Undefined index: REDIRECT_URL in /home/webccans/public_html/index.php

I have Tried taking out the redirect and it still works. I need help try to define the index "REDIRECT_URL" I would appreciate and pointers or advice.
The page is display, and the site works fine but this error is on the home page
This is the Code on my index page
<?
include('application.php');
$header = false;

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (($request = trim($_SERVER['REDIRECT_URL'])) == '') {
    // Deal with direct requests
    $Page = (isset($_GET['Page'])) ? $_GET['Page'] : 1;
    $Page = $CMS->getPageContent($Page);
} else {
    // Deal with "friendly" URL 404 pages
    $pages = explode('/', $request);
    array_shift($pages);
    $page = array_pop($pages);
    if (($pos = strpos($page, '.')) === false) {
        $ext = '';
    } else {
        $ext = substr($page, strpos($page, '.'));
        if ($pos = strpos($ext, '?')) $ext = substr($ext, 0, $pos);
    }
    if ($page == '') {
        // have a CMS page or the home page
    } else if ($ext == '.htm' || $ext == '.html' || $ext == '.php') {
        $PageURL = substr($page, 0, strlen($ext) * -1);
        if ($PageURL != "index") {
            // Possible have a CMS page
            array_push($pages, $PageURL);
        }
    } else if ($ext == '') {
        // have a CMS page
        array_push($pages, $page);
    } else {
        $CMS->show404Page();
        $header = true;
    }
    if (($numPages = count($pages)) > 0) {
        // Get PageID
        $select = 'SELECT ';
        $from = ' FROM site_content AS page0 LEFT JOIN site_content AS
   page ON (page0.ParentID = page.PageID) ';
        $where = ' WHERE (page0.ParentID = 0 OR page.Display = 0) ';
        for ($idx = 0; $idx < $numPages; ++$idx) {
            $where .= ' AND ';
            if ($idx > 0) {
                $select .= ', ';
                $from .= ' JOIN site_content AS page' . $idx . ' ON (page'
 . ($idx - 1) . '.PageID = page' . $idx . '.ParentID)';
            }
            $select .= 'page' . $idx . '.PageID ';
            $where .= 'page' . $idx . '.PageURL = "' . $DB-
    >escape(strtolower($pages[$idx])) . '"';
            #$select1 = 'page' . $idx . '.PageID ';
        }
        $qid = $DB->query($select . $from . $where);

        if ($row = $DB->fetchRow($qid)) {
            $PageID = $row[$numPages - 1];
            $OpenedPages = $row;
            #print_r ($row);
        }
        else {
            $CMS->show404Page();
            $header = true;
        }

    } else {
        $PageID = 1;
    }
    $Page = $CMS->getPageContent($PageID);

    #echo '<script language="javascript">' . 'alert("' . $PageID . '")'
 .
 '</script>';
    #echo '<script language="javascript">' . 'alert("' . $ParentId . '")'
   . '</script>';
}

$TopPage = $CMS->getTopParent($Page->PageID);
if (!$header) header('HTTP/1.1 200 OK');
?>