text:
Q: Calling function from BLL layer to controller in MVC5 public class StudentBLL
    {
        StudentDAL objStudent = new StudentDAL();
        public List<StudentDAL> GetAllStudnets() {

            List<StudentDAL > lstStudents = objStudent.GetStudentList().Tables[0].AsEnumerable().Select(
                        dataRow => new StudentDAL
                        {
                            StuID = dataRow.Field<int>("StudentId"),
                            StuName = dataRow.Field<int>("StudentName")
                        }).ToList();

            return lstStudents;
        }

    }

I want to call this function in my Home Controller:
    public JsonResult LoadStudents(int randomJunk)
    {
        //call function here ??
        List<SelectListItem> selectListItems = new List<SelectListItem>();
        //selectListItems.Add(si);
       // selectListItems.Add(si1);

        var notesTypes = new SelectList(selectListItems, "Value", "Text");

        return Json(notesTypes, JsonRequestBehavior.AllowGet);

    }

So how can call the return list to my Home Controller , I'm really confused and I'm not a student

A: Create an object of class StudentBLL and call the method GetAllStudnets with this object
StudentBLL  obj = new StudentBLL ();
List<StudentDAL> ls = obj.GetAllStudnets();

Best practise is to create an interface with the required methods. create a class which implements the method. Use dependency injection to inject the class in the controller to call the method.


text:
Q: pthread_mutex and process termination Before using a pthread_mutex_t pthread_mutex_init() should be called, and after it's not longer required it should be destroyed using pthread_mutex_destroy().
My question is, what happens if my process terminates before it can call pthread_mutex_destroy(), for example a SIGKILL, SIGINT or SIGABORT? Is it possible that some resource will leak?
Same question goes to pthread_cond_init/destroy as well.

A: Not on any platform you're likely to use. Objects like mutexes and condition variables are just chunks of memory in the process' address space. When a process terminates, its address space ceases to exist. So it's not possible for any resources to leak.
Process-shared resources are more complex. While the resources won't leak, they may still exist and may even still be in use by other processes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Communication with HyperTerminal [ QT and WINApi ] I write program to communicate with modem (it useing Hayes commands) and this is working.
GUI is programmed with QT, but communication with COM port is write with winapi library. I have problem when I want to send with my program message from one computer to another, i can't send Polish chars (they are repleaced by '?'), how can I fix it ? Does anyone have idea ?? And I have one more problem, I can't send message from my program to Microsoft HyperTerminal, HyperTerminal receive something, but not that what I send.
Thx for any help :)
Important pieces of code:
Connect with port:
portHandle = CreateFile (portName, GENERIC_WRITE | GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);

GetCommState (portHandle, &dcb);
switch(ui->comboBox->currentIndex())
{
       case 0 : dcb.BaudRate=CBR_110; break;
       case 1 : dcb.BaudRate=CBR_300; break;
       case 2 : dcb.BaudRate=CBR_600; break;
       case 3 : dcb.BaudRate=CBR_1200; break;
       case 4 : dcb.BaudRate=CBR_2400; break;
       case 5 : dcb.BaudRate=CBR_4800; break;
       case 6 : dcb.BaudRate=CBR_9600; break;
       case 7 : dcb.BaudRate=CBR_14400; break;
       case 8 : dcb.BaudRate=CBR_19200; break;
       case 9 : dcb.BaudRate=CBR_38400; break;
       case 10 : dcb.BaudRate=CBR_56000; break;
       case 11 : dcb.BaudRate=CBR_57600; break;
       case 12 : dcb.BaudRate=CBR_115200; break;
       case 13 : dcb.BaudRate=CBR_128000; break;
       case 14 : dcb.BaudRate=CBR_256000; break;
}

dcb.fBinary = TRUE;
dcb.fParity = TRUE;
dcb.fOutxCtsFlow = FALSE;
dcb.fOutxDsrFlow = FALSE;
dcb.fDtrControl = DTR_CONTROL_ENABLE;
dcb.fDsrSensitivity = FALSE;
dcb.fTXContinueOnXoff = TRUE;
dcb.fOutX = FALSE;
dcb.fInX = FALSE;
dcb.fErrorChar = FALSE;
dcb.fNull = FALSE;
dcb.fRtsControl = RTS_CONTROL_ENABLE;
dcb.fAbortOnError = FALSE;
//dcb.ByteSize = dataBits;
dcb.DCBlength = sizeof (DCB);

switch(ui->comboBox_3->currentIndex())
{
   case 1 : dcb.Parity = EVENPARITY; break;
   case 3 : dcb.Parity = MARKPARITY; break;
   case 2 : dcb.Parity = ODDPARITY; break;
   case 4 : dcb.Parity = SPACEPARITY; break;
   case 0 : dcb.Parity = NOPARITY; break;
}

switch (ui->comboBox_4->currentIndex())
{
    case 0 : dcb.StopBits = ONESTOPBIT; break;
    case 1 : dcb.StopBits = ONE5STOPBITS;break;
    case 2 : dcb.StopBits = TWOSTOPBITS; break;
}

switch (ui->comboBox_2->currentIndex())
{
    case 0 : dcb.ByteSize = 5; break;
    case 1 : dcb.ByteSize = 6;break;
    case 2 : dcb.ByteSize= 7; break;
     case 3 : dcb.ByteSize = 8; break;
}

SetCommState (portHandle, &dcb);

GetCommTimeouts (portHandle, &CommTimeouts);
CommTimeouts.ReadIntervalTimeout = MAXDWORD;
CommTimeouts.ReadTotalTimeoutMultiplier = 0;
CommTimeouts.ReadTotalTimeoutConstant = 0;
CommTimeouts.WriteTotalTimeoutMultiplier = 10;
CommTimeouts.WriteTotalTimeoutConstant = 1000;
SetCommTimeouts (portHandle, &CommTimeouts);

Send MSG:
void MainWindow::Send(char c)
{
    do
        {WriteFile(portHandle, &c, 1, &cbWritten, NULL);
        }
    while (!(cbWritten));
}

void MainWindow::on_pushButton_clicked()
{
    QString str = ui->lineEdit->text();
    std::string str2;
    ui->lineEdit->clear();
    str2 = str.toStdString();
    for(int i=0; i < str2.size();i++)
    {
        Send(str2[i]);
        //qDebug()<< str2[i];
    }
    Send(char(13));

}

Receive MSG:
void ReaderThread::run()
{

    char c;
    while(1)
    {

        c = Receive();
        if(c==13)
        {
            emit insertPlainText("\n");
        }
        else
        {
            emit insertPlainText(QString(c));

        }

    }
}

char ReaderThread::Receive()
{
    char c;
    do{
        ReadFile(portHandle, &c, 1, &cbRead, NULL);
    }
    while (!(cbRead));
    return c;

}

A: You are hammering a 16-bit QChar into a 8-bit hole.  You'll need to send and receive 2 bytes per character or restrict yourself to an 8-bit character encoding.


text:
Q: How to apply a line of css to all browsers but IE? I don't want to recreate a file just for that specific line of code, I simply want to ignore that css line if I am in Internet Explorer.
I would also like to avoid putting inline css.

Is it possible?

.container {
  height: 100px; // to apply only in Chrome, Firefox, Safari, etc.
}

A: Yes, you can use a conditional comment.
<!--[if !IE]>-->
  <style>
    .container {
      height: 100px; /* only in Chrome, Firefox, Safari, etc */
    }
  </style>
<!--<![endif]-->

Notice the "not" operator ! so it will apply to browsers that are not IE. See this link for more.


text:
Q: OBJLoader with React, THREE, Parcel and react-three-fiber WARNING This is not a copy of three.js OBJLoader not loading in react. react-three-renderer is deprecated and I use functional components here.
I need to load an .obj file but two problems appear. First, it throws TypeError: instance is undefined by react-three-fiber. Second, it loads .obj as HTML: Error: THREE.OBJLoader: Unexpected line: "<!DOCTYPE html>".
Are these issues related to Parcel, THREE or react-three-fiber?
Here's the code that doesn't work:
App.js
import React from 'react'
import { render } from 'react-dom'
import { Canvas } from 'react-three-fiber'
import Model from '/Model'
import Controls from '/Controls'
import '/style.css'

const App = () => {
  return (
    <main>
      <Canvas>
        <Model url="demo.obj" />
        <Controls />
      </Canvas>
    </main>
  )
}

render(<App />, document.getElementById('app'))

Controls.js
import React, { useRef } from 'react'
import { useThree, useRender, extend } from 'react-three-fiber'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

extend({ OrbitControls })

const Controls = props => {
  const { camera } = useThree()
    const controls = useRef()

    useRender(({ camera }) => {
        controls.current && controls.current.update()
        camera.updateMatrixWorld()
    })
  return <orbitControls ref={controls} args={[camera]} {...props} />
}

export default Controls

Model.js
import React, { useRef, useMemo } from 'react'
import { Math as THREEMath } from 'three'
import { useRender } from 'react-three-fiber'
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader'

const Model = ({ url }) => {
    const model = useRef()
  let rot = 0

  const obj = useMemo(() => new OBJLoader().load(url), [url])

    useRender(() => {
        const rad = 5 * Math.sin(THREEMath.degToRad(rot += 0.3))
        model.current.rotation.set(rad, rad, 0)
  })
    return <primitive object={obj} ref={model} />
}

export default Model

OBJ File here

A: wrong path. the doctype stuff is the 404 page it pulls. as of r3f 3 you can use the useLoader hook, it makes error handling easier since it's based on react suspense, so you could wrap it into error boundaries and fallbacks.


text:
Q: Trying to add to an array I'm trying to pass along the question AND the id of the question in the first query and then with that id get that poll's options and add those to the array. Not seeing what I'm doing wronge here.
Here's the error I am getting:

A PHP Error was encountered
Severity: Notice
Message: Undefined property: CI_DB_mysql_result::$row
Filename: models/sitemodel.php
Line Number: 161
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: models/sitemodel.php
Line Number: 161

Code:
function getPoll() {
    $this->db->select('site_polls.id, site_polls_questions.poll_question');
    $this->db->from('site_polls');
    $this->db->join('site_polls_questions', 'site_polls_questions.id = site_polls.site_polls_questions_id');
    $this->db->where('site_polls.status_id', 1);
    $this->db->order_by('site_polls.date_posted', 'desc');
    $this->db->limit(1);
    $query = $this->db->get();
    $id = $query->row->id;

    $this->db->select('site_polls_questions_options.poll_option');
    $this->db->from('site_polls_questions_options');
    $this->db->where('id', $id);
    $query = $this->db->get();

    return $query->result_array();
}

I'm trying to figure out how I can add the question of the poll into the array.

A: row() is a function and not a property.
$id = $query->row()->id;

or
$id = $query->row(0)->id;

A: $id = $query->row->id;

Should be:
$id = $query->row()->id;

$query->row() is a function, not a property.

A: Try this:
$query = $this->db->get()->first_row();
if ( !empty($query->id))
{
    $id = $query->id;
}
else
{
    return array();
}


text:
Q: what are some resources to learn about copyright law? I once heard a prominent scientist say, of global warming, that he didn't realize how much he would have to learn about politics.
I just read an excellent article in DDJ about the Jacobsen verus Katzer case. When in university, I didn't know how much I would have to learn about the law.
It seems to me that a big hole in the classic comp sci education is that of legal issues.  Many of us talk about licenses, copyright, copyleft, prior art, etc, but our terms are often vague and probably inaccurate.
What are some resources where the average developer can learn about copyright law and become an informed citizen of IT?

A: groklaw would seem to be a good starting point for open source issues

A: 1 A good overview of key intellectual property regimes (more geared to open source, US law) can be found here:
http://www.softwarefreedom.org/resources/2008/foss-primer.html
2 Here's also a collection of links to open educational materials on digital copyright:
https://sites.google.com/site/copyrightessentials/
I'd also recommend reading the materials on the Electronic Frontier Foundation's website, regularly updated and high quality.

A: The Nolo book Legal Guide to Web & Software Development discusses copyright and other issues as they pertain to software developers.
http://www.amazon.com/Legal-Guide-Software-Development-CD-Rom/dp/1413305326/

A: I really enjoyed these lectures from MIT Open Courseware.

A: I don't know any truly greate resource. I just know that most of what I've seen is missinformation, even by people who should know. So be very sceptical of anything you read.
If you just want to know the practical concrete law of things I suggest you speak to a lawyer and/or read some actual verdicts.
Then again most copyright issues aren't taken to court but affect you more directly in contracts, expectations and litigation threats. In this case the law won't help you, the cultural dealings with copyright will probably differ a great deal from the actual law, in this case it would be better to just study the people/companies and their actions. I recommend the course COMM 499: PWNED: Is everyone on this campus a copyright criminal? by Cory Doctorow. You can get recordings of the lectures at archive.org
If you are more interested in ideological issues I think Question Copyright has a few interesting articles. Specifically one about the history of copyright.

A: If you are in a company, ask management to have the company's intellectual property lawyer come in and speak to the technical people.  Although lawyers usually work on an hourly rate basis, the good ones love to come in and give little educational seminars to show their clients they care and, of course, to sensitize them to legal issues that they might call for more help on.


text:
Q: VIewModel observeAsState as Single event in Android Compose I have an issue with view model, when I do a network call/viewModel validation, and then the re composition happens (for example Textfield onValueChange) the viewModel holds the reference to the last "state" from the viewModel is any way to "observe" the state only once? similar to SingleLiveEvent or should I "clear" the state from my viewModel somehow?
here is an Example
@Composable
fun TestViewModelStateCompose(viewModel: TestViewModel) {
    Column(modifier = Modifier.fillMaxSize()) {
        var email by remember { mutableStateOf("") }
        var error by remember { mutableStateOf<String?>(null) }

        var lceState = viewModel.lceState.observeAsState().value

        when (lceState) {
            is Lce.Content -> {
                // do something
                if(lceState.result.not()){
                    error = "Wrong email :/"
                }
            }
            is Lce.Error -> {
                error = "Wrong email"
            }
            Lce.Loading -> {
                //loading
            }
            null -> {}
        }

        TextField(
            value = email, onValueChange = {
                email = it
                error = null
            },
            modifier = Modifier.fillMaxWidth()
        )
        error?.let {
            Text(
                text = it,
                style = MaterialTheme.typography.labelMedium,
                color = MaterialTheme.colorScheme.error,
                modifier = Modifier
                    .padding(horizontal = 16.dp)
                    .padding(top = 8.dp)
                    .fillMaxWidth(),
                maxLines = 1
            )
        }
        Spacer(modifier = Modifier.weight(1f))
        Button(
            onClick = {
                viewModel.validateEmail()
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 32.dp)
        ) {
            Text(
                text = "Validate email",
            )
        }
    }
}

sealed class Lce {
    object Loading : Lce()
    data class Content(val result: Boolean) : Lce()
    data class Error(val error: Throwable) : Lce()
}

class TestViewModel() : ViewModel() {
    val lceState = SingleLiveEvent<Lce>()
    private val isValid = false

    fun validateEmail() {
        if (isValid) {
            // do something
        } else {
            viewModelScope.launch {
                //place holder, the email is always invalid for test
                flowOf(false)
                    .onStart {
                        // simulate call
                        delay(1000)
                        lceState.postValue(Lce.Loading)
                    }
                    .catch { lceState.postValue(Lce.Error(it)) }
                    .collect {
                        lceState.postValue(Lce.Content(it))
                    }
            }
        }
    }
}

My main issue is when i call "validate emaial" and then I'm listening the
var lceState = viewModel.lceState.observeAsState().value
this works as expected, then I want to "clear" the error just setting to null, however this is being overriden by viewModel.lceState.observeAsState() because in every re composition it holds the last value. is possible to "observe" as only one time? or "autoClear" after the compose comsume this events?
Thanks a lot

A: I recommend using MVI and using Event to represent the ViewModel's one-time data for compose. For example:
interface Event

abstract class BaseViewModel<E : Event> : ViewModel() {
    private val _event = Channel<E>()
    val event = _event.receiveAsFlow().shareIn(viewModelScope, SharingStarted.Lazily)
    protected suspend fun sendEvent(event: E) = _event.send(event)
    protected fun sendEventSync(event: E) = viewModelScope.launch { _event.send(event) }
}

@Composable
fun <E : Event> OnEvent(event: Flow<E>, onEvent: (E) -> Unit) {
    LaunchedEffect(Unit) {
        event.collect(onEvent)
    }
}

Then you can do this:

@Composable
fun TestViewModelStateCompose(viewModel: TestViewModel) {
    Column(modifier = Modifier.fillMaxSize()) {
        var email by remember { mutableStateOf("") }
        var error by remember { mutableStateOf<String?>(null) }

        OnEvent(viewModel.event) {
            when (it) {
                is TestEvent.ValidateEmailFailure -> error = "Wrong email :/"
                is TestEvent.ValidateEmailLoading -> Unit // loading
                TestEvent.ValidateEmailSuccess -> Unit // do something like toast
            }
        }

        TextField(
            value = email, onValueChange = {
                email = it
                error = null
            },
            modifier = Modifier.fillMaxWidth()
        )
        error?.let {
            Text(
                text = it,
                style = MaterialTheme.typography.labelMedium,
                color = MaterialTheme.colorScheme.error,
                modifier = Modifier
                    .padding(horizontal = 16.dp)
                    .padding(top = 8.dp)
                    .fillMaxWidth(),
                maxLines = 1
            )
        }
        Spacer(modifier = Modifier.weight(1f))
        Button(
            onClick = {
                viewModel.validateEmail()
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 32.dp)
        ) {
            Text(
                text = "Validate email",
            )
        }
    }
}

sealed interface TestEvent : Event {
    object ValidateEmailLoading : TestEvent
    object ValidateEmailSuccess : TestEvent
    data class ValidateEmailFailure(val exception: Throwable) : TestEvent
}

class TestViewModel : BaseViewModel<TestEvent>() {
    private val isValid = false

    private suspend fun simulateValidate(): Result<Unit> {
        return runCatching {
            delay(1000)
        }
    }

    fun validateEmail() {
        if (isValid) {
            // do something
        } else {
            viewModelScope.launch {
                sendEvent(TestEvent.ValidateEmailLoading)
                simulateValidate()
                    .onSuccess { sendEvent(TestEvent.ValidateEmailSuccess) }
                    .onFailure { sendEvent(TestEvent.ValidateEmailFailure(it)) }
            }
        }
    }
}

It is better to handle Events and Actions at the very beginning of the Screen to avoid taking the ViewModel as a parameter of compose function. This helps with testing and code reuse.

A: One option for doing would be adding an Idle state and changing lceState to this state to simulate nothing is happening. I use this approach when i don't want to show an initial loading Composable


text:
Q: Setting imageURL using a function in ASP.NET I've done this task before within repeaters and it has worked.  However I can't get the below to work for me in a normal webforms page.  The images appear as broken links and breakpoints I put in the codebehind are not triggered.
(in the aspx file)
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl='<%# GetImageDirectory()%>btnRunReport.png'  />

(codebehind)
public string GetImageDirectory()
{
    return "~/App_Variants/LBSX/images/";
}

This is the second method I've tried, in the other one I tried passing the imagename through as a string, and it would return the entire link that way.  Still no luck!
Any thoughts?
Thanks!
[EDIT] Thanks for the help everyone.  In the end after the handy hints I found a recursive snippet which did the trick as follows:
private void UpdateImages(Control Parent)
{
    foreach (Control c in Parent.Controls)
    {
        ImageButton i = c as ImageButton;
        if (i != null)
        {
            i.ImageUrl = "~/App_Variants/LBSX/images/" + i.ImageUrl;
        }
        if (c.HasControls())
        {
            UpdateImages(c);
        }
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    UpdateImages(Page);
    ...

Hope it helps someone else.
Cheers

A: First, just like Zachary mentioned, you're using the code block for data binding.
Second, as you've already tried, using an inline expression (<%= %>) won't work either in your case, since you can't use an inline expression for any property of a server-tag.
What you could do instead is defining an image button using HTML syntax, omitting the runat="server" tag, and use the inline expression to get your image's URL:
<input type="image" src="<%= GetImageDirectory() %>btnRunReport.png" name="image" />

What an inline expression does is, it calls Response.Write() with the value between <%= %> as the parameter, e.g. <%= this.MyVar %> is Response.Write(this.MyVar).

A: Your syntax is for data binding, <%# %>.  If you are just trying to do inline c#, you should use <%= %>.

A: I give you another solution. Use ExpressionBuilder :

*

*Create a class devired from ExpressionBuilder and override function GetCodeExpression
 namespace your.namespace
{
public class CustomBuilder : ExpressionBuilder
{
    public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
    {
        Type type1 = entry.DeclaringType;
        PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(type1)[entry.PropertyInfo.Name];
        CodeExpression[] expressionArray1 = new CodeExpression[1];
        expressionArray1[0] = new CodePrimitiveExpression(entry.Expression.Trim());

        String temp = entry.Expression;
        return new CodeCastExpression(descriptor1.PropertyType, new CodeMethodInvokeExpression(new
       CodeTypeReferenceExpression(base.GetType()), "GenerateLink", expressionArray1));
    }
    public static  String GenerateLink(String link)
    {
        return ConfigurationManager.AppSettings["MediaPath"] + link + "?ver=" + ConfigurationManager.AppSettings["MediaCode"];
    }
}
}

expressionArray1 is the input array for GenerateLink function. You can change the size of array according to numbers of input params for your function
2.Register your expression in webconfig
<system.web>
    <compilation debug="true" targetFramework="4.0" >
      <expressionBuilders>

        <add expressionPrefix="GenLink" type="your.namespace.CustomBuilder"/>
      </expressionBuilders>

    </compilation>

3.In view your can use new expression:
<asp:ImageButton ID="ImageButton1" runat="Server" ImageUrl='<%$ GenLink:images/magnifier.jpg %>'/>

4.Enjoy !!!


text:
Q: Django link text too long In my detail view in my Django app I show links to all attached files in the Post. Problem is, if link is too long it goes beyond border. Is it possible to show only part of link if it's too long or to limit the 'preview', not to edit the link.

code:
{% for i in post.file_set.all %}
Privitak prijave {{ forloop.counter }}: {{i.file.name}}
{% endfor %}

A: You can use the |truncatechars template filter [Django-doc]:
{{ i.file.name|truncatechars:20 }}


text:
Q: How can I conduct a non-parametric version of MANCOVA? Is it possible to transform my variables to their ranks and apply MANCOVA to the transformed data, just like how it is done in rank ANCOVA?

A: In this case Peter O'Brien's method of turning the problem around makes sense.  Use a polytomous logistic regression model to estimate the joint relationship between the two dependent variables and the probability of being assigned to each of the three training methods.  This makes no distributional assumptions. You can relax assumptions that are akin to the equal covariance matrix assumption by including nonlinear terms on the right hand side of the model.  See https://www.jstor.org/stable/2288918


text:
Q: Datepicker setData displays incorrect date on dateFormat 'MM yy' I'm working with a datepicker that only needs to show and pick the month and the year. So I changed the dateFormat to 'MM yy'. Now when I do:
$('.date-picker').datepicker('setDate', 'July 2016');

The datepicker shows January 2022. But when I do:
console.log($('.date-picker').datepicker("getDate"));

It shows Tue Jul 19 2016 00:00:00 GMT+0800 (PHT)
I tried changing the dateFormat to 'MM dd yy' and setDate to 'July 01 2016' and it works smoothly.
Here is the JSFiddle: http://jsfiddle.net/gaddygs3/3/
Thanks!

A: $(document).ready(function() {
$('#txtDate').datepicker({
 changeMonth: true,
 changeYear: true,
 dateFormat: 'MM yy',

 onClose: function() {
    var iMonth = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
    var iYear = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
    $(this).datepicker('setDate', new Date(iYear, iMonth, 1));
 },

 beforeShow: function() {
   if ((selDate = $(this).val()).length > 0)
   {
      iYear = selDate.substring(selDate.length - 4, selDate.length);
      iMonth = jQuery.inArray(selDate.substring(0, selDate.length - 5), $(this).datepicker('option', 'monthNames'));
      $(this).datepicker('option', 'defaultDate', new Date(iYear, iMonth, 1));
       $(this).datepicker('setDate', new Date(iYear, iMonth, 1));
   }
}
});
});

Check here

A: Firstly change the format of setting the date
$('#checkin').datepicker('setDate',new Date('July 2016'));


text:
Q: For $R = R_{1} \oplus R_{2}$, where $I_{1}$ ideal of $R_{1}$, $I_{2}$ ideal of $R_{2}$, show that $I_{1},I_{2}$ ideals of $R$ Let $R = R_{1} \oplus R_{2}$ and let $I_{1}$ and $I_{2}$ be ideals of rings $R_{1}$ and $R_{2}$, respectively.
We consider $R_{1}$ and $R_{2}$ as subrings of $R$ under canonical embeddings $R_{i} \to R$ and thus $I_{1}$ and $I_{2}$ are considered as subrings of $R$.
I need to do the following two things:

a. Prove that $I_{1}$ and $I_{2}$ are ideals of $R$.
b. If each $I_{i}$ is a proper ideal of $R_{i}$, determine whether the ideal $I_{1}+I_{2}$ of $R$ is maximal. Is it prime?

For part (a), if we identify $I_{1} = I_{1}\times 0$, then in order for it to be an ideal of $R$, I need it to be both an additive subgroup of $R_{1} \times R_{2}$ and I would need $(R_{1}\times R_{2})(I_{1}) \subseteq I_{1}$ and $(I_{1})(R_{1} \times R_{2}) \subseteq I_{1}$. The latter two things especially are confusing me because of the direct sum notation.
Could anybody assist me with this part especially - hints for part (b) as to how to get at least started are also welcome.
Thank you.

A: For these it is helpful to keep a particular product in mind. Namely, $R$ is the ring of pairs $(r_1, r_2)$ under pointwise product and sum. $R_1$ are all the pairs $(r_1, 0)$ and $R_2$ is all the pairs $(0,r_2)$. Note that $R_1R_2 = 0$ and $R_1 + R_2 = R$.
a) The ideal $I_1$ corresponds to pairs $(i,0)$ where $i \in I_1$ as a subset of $R_1$. Then $RI_1$ = $(R_1 + R_2)I_1 = R_1I_1 + R_2I_1 = R_1I_1 = I_1$ because $R_2I_1 = 0$.
b) $I_1 + I_2$ is prime if and only if $R/(I_1 + I_2)$ is a domain. Hint: are products of rings usually domains?


text:
Q: How to copy Gdk.image? Is it possible to make a copy of Gdk.image object using lablgtk2 for Ocaml?
I tried to find 'copy' or 'clone' methods but failed.

A: Maybe you could use pixbuf? It can be created from any drawable.

A: Here is my clumsy workaround:
let copy_image image =

    let w, h = Image.width image, Image.height image in

    let copy = Image.create ~kind: `FASTEST ~visual: (Image.get_visual image)

        ~width: w

        ~height: h in

    for x = 0 to w-1 do

        for y = 0 to h-1 do

            Image.put_pixel copy ~x:x ~y:y (Image.get_pixel image ~x:x ~y:y)

        done

    done;
    copy


text:
Q: Javascript issue with IE11 My app was working fine till IE9, now it stopped working when I upgraded it to IE11. Here is a sample html and js .
ISSUE
In the first run ie. on load it works well. But when I select PDA brand, second dropdown's all options went blank.
In console there was a script error Invalid Calling Object error on object clonedOptions.

function dynamicSelect(id1, id2) {
  //alert("Everytime")
  // Browser and feature tests to see if there is enough W3C DOM support

  // Obtain references to both select boxes
  var sel1 = document.getElementById(id1);
  var sel2 = document.getElementById(id2);
  // Clone the dynamic select box
  var clone = sel2.cloneNode(true);
  // Obtain references to all cloned options
  var clonedOptions = clone.getElementsByTagName("option");
  // Onload init: call a generic function to display the related options in the dynamic select box
  refreshDynamicSelectOptions(sel1, sel2, clonedOptions);
  // Onchange of the main select box: call a generic function to display the related options in the dynamic select box

  sel1.onchange = function() {
    refreshDynamicSelectOptions(sel1, sel2, clonedOptions);
  };
}

function refreshDynamicSelectOptions(sel1, sel2, clonedOptions) {
  while (sel2.options.length) {
    sel2.remove(0);
  }

  //alert(sel1.options[sel1.selectedIndex].value)

  // Create regular expression objects for "select" and the value of the selected option of the main select box as class names
  var pattern1 = /( |^)(select)( |$)/;
  var pattern2 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");
  // Iterate through all cloned options
  //alert(clonedOptions.length);
  for (var i = 0; i < clonedOptions.length; i++) {
    // If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box

    if (clonedOptions[i].className.match(pattern1) || clonedOptions[i].className.match(pattern2)) {
      // Clone the option from the hidden option pool and append it to the dynamic select box
      //alert("Did match")

      sel2.appendChild(clonedOptions[i].cloneNode(true));
      //alert(sel2.options[1]);
    }
  }
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <title>dynamic selectbox example</title>

  <form action="#">

      <select id="pda-brand">
        <option value="select">Select PDA brand...</option>
        <option value="dell">Dell</option>
        <option value="hp">HP</option>
        <option value="palmone">PalmOne</option>
      </select>
      <select id="pda-type">
        <option class="select" value="select">Select PDA type...</option>
        <option class="dell" value="aximx30">Axim X30</option>
        <option class="dell" value="aximx50">Axim X50</option>
        <option class="hp" value="ipaqhx2750">iPAQ hx2750</option>
        <option class="hp" value="ipaqrx3715">iPAQ rx3715</option>
        <option class="hp" value="ipaqrz1710">iPAQ rz1710</option>
        <option class="palmone" value="tungstene2">Tungsten E2</option>
        <option class="palmone" value="tungstent5">Tungsten T5</option>
        <option class="palmone" value="zire72">Zire 72</option>
      </select>

  </form>

LINE OF ISSUE
in below loc, for clonedOptions i am getting  Invalid Calling Object error.
for (var i = 0; i < clonedOptions.length; i++) {

A: I think the problem is that you are using getElementsByTagName which returns a live list, which means that if an item is removed from the DOM, it is also removed from the list and is therefore eligible for garbage collection. See https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName

The returned list is live, meaning that it updates itself with the DOM tree automatically.

The following example will explain what I mean

var ps = document.body.getElementsByTagName('p');
var ps2 = document.body.querySelectorAll('p');
console.log(ps.length); // 3
document.body.removeChild(ps[0]);
console.log(ps.length);  // 2
console.log(ps2.length);  // 3

Hello

Hello

Hello

I don't have the latest IE, but I have a strong feeling that if you use clone.querySelectorAll("option"), you won't have the same problem because the nodes will not become eligible for garbage collection since the list it returns is not live.

function dynamicSelect(id1, id2) {
  //alert("Everytime")
  // Browser and feature tests to see if there is enough W3C DOM support

  // Obtain references to both select boxes
  var sel1 = document.getElementById(id1);
  var sel2 = document.getElementById(id2);
  // Clone the dynamic select box
  var clone = sel2.cloneNode(true);
  // Obtain references to all cloned options
  var clonedOptions = clone.querySelectorAll("option");
  // Onload init: call a generic function to display the related options in the dynamic select box
  refreshDynamicSelectOptions(sel1, sel2, clonedOptions);
  // Onchange of the main select box: call a generic function to display the related options in the dynamic select box

  sel1.onchange = function() {
    refreshDynamicSelectOptions(sel1, sel2, clonedOptions);
  };
}

function refreshDynamicSelectOptions(sel1, sel2, clonedOptions) {
  while (sel2.options.length) {
    sel2.remove(0);
  }

  //alert(sel1.options[sel1.selectedIndex].value)

  // Create regular expression objects for "select" and the value of the selected option of the main select box as class names
  var pattern1 = /( |^)(select)( |$)/;
  var pattern2 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");
  // Iterate through all cloned options
  //alert(clonedOptions.length);
  for (var i = 0; i < clonedOptions.length; i++) {
    // If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box

    if (clonedOptions[i].className.match(pattern1) || clonedOptions[i].className.match(pattern2)) {
      // Clone the option from the hidden option pool and append it to the dynamic select box
      //alert("Did match")

      sel2.appendChild(clonedOptions[i].cloneNode(true));
      //alert(sel2.options[1]);
    }
  }
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <title>dynamic selectbox example</title>

  <form action="#">

      <select id="pda-brand">
        <option value="select">Select PDA brand...</option>
        <option value="dell">Dell</option>
        <option value="hp">HP</option>
        <option value="palmone">PalmOne</option>
      </select>
      <select id="pda-type">
        <option class="select" value="select">Select PDA type...</option>
        <option class="dell" value="aximx30">Axim X30</option>
        <option class="dell" value="aximx50">Axim X50</option>
        <option class="hp" value="ipaqhx2750">iPAQ hx2750</option>
        <option class="hp" value="ipaqrx3715">iPAQ rx3715</option>
        <option class="hp" value="ipaqrz1710">iPAQ rz1710</option>
        <option class="palmone" value="tungstene2">Tungsten E2</option>
        <option class="palmone" value="tungstent5">Tungsten T5</option>
        <option class="palmone" value="zire72">Zire 72</option>
      </select>

  </form>

A: I could get this working in IE-11, Please try by yourself.
As per my understanding the issue is:
var clone = sel2.cloneNode(true);
var clonedOptions = clone.getElementsByTagName("option");

clonedOptions is probably a reference to children of clone with tag name option
  sel1.onchange = function() {
    refreshDynamicSelectOptions(sel1, sel2, clonedOptions);
  };

In this function there is a reference to clonedOptions, but no reference to clone. So clone is probably garbageCollected as IE couldn't find any reason to keep it. clonedOptions keeps a reference to a collection that doesn't exist.
You could correct in your own way, I am just passing clone instead of clonedOptions and it works for me in IE11

function dynamicSelect(id1, id2) {
  //alert("Everytime")
  // Browser and feature tests to see if there is enough W3C DOM support

  // Obtain references to both select boxes
  var sel1 = document.getElementById(id1);
  var sel2 = document.getElementById(id2);
  // Clone the dynamic select box      // Obtain references to all cloned options
  var clone = sel2.cloneNode(true);
  // Onload init: call a generic function to display the related options in the dynamic select box
  refreshDynamicSelectOptions(sel1, sel2, clone);
  // Onchange of the main select box: call a generic function to display the related options in the dynamic select box

  sel1.onchange = function() {
    refreshDynamicSelectOptions(sel1, sel2, clone);
  };
}

function refreshDynamicSelectOptions(sel1, sel2, clone) {
  var clonedOptions = clone.getElementsByTagName("option");
  while (sel2.options.length) {
    sel2.remove(0);
  }

  //alert(sel1.options[sel1.selectedIndex].value)

  // Create regular expression objects for "select" and the value of the selected option of the main select box as class names
  var pattern1 = /( |^)(select)( |$)/;
  var pattern2 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");
  // Iterate through all cloned options
  //alert(clonedOptions.length);
  for (var i = 0; i < clonedOptions.length; i++) {
    // If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box

    if (clonedOptions[i].className.match(pattern1) || clonedOptions[i].className.match(pattern2)) {
      // Clone the option from the hidden option pool and append it to the dynamic select box
      //alert("Did match")

      sel2.appendChild(clonedOptions[i].cloneNode(true));
      //alert(sel2.options[1]);
    }
  }
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <title>dynamic selectbox example</title>

  <form action="#">

      <select id="pda-brand">
        <option value="select">Select PDA brand...</option>
        <option value="dell">Dell</option>
        <option value="hp">HP</option>
        <option value="palmone">PalmOne</option>
      </select>
      <select id="pda-type">
        <option class="select" value="select">Select PDA type...</option>
        <option class="dell" value="aximx30">Axim X30</option>
        <option class="dell" value="aximx50">Axim X50</option>
        <option class="hp" value="ipaqhx2750">iPAQ hx2750</option>
        <option class="hp" value="ipaqrx3715">iPAQ rx3715</option>
        <option class="hp" value="ipaqrz1710">iPAQ rz1710</option>
        <option class="palmone" value="tungstene2">Tungsten E2</option>
        <option class="palmone" value="tungstent5">Tungsten T5</option>
        <option class="palmone" value="zire72">Zire 72</option>
      </select>

  </form>


text:
Q: Why is user.is_authenticated asserting true after logout I am trying to write a test for logging out a user in Django. Here is the code:
urls.py
from django.conf.urls import url
from django.contrib import admin
from accounts.views import LoginView, LogoutView

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login/', LoginView.as_view(), name='login'),
    url(r'^logout/', LogoutView.as_view(), name='logout'),
]

views.py
from django.http import HttpResponseRedirect
from django.contrib.auth import login, logout
from django.views.generic import View

class LogoutView(View):
    def get(self, request):
        logout(request)
        return HttpResponseRedirect('/')

tests.py
from django.test import TestCase, Client
from django.contrib.auth.models import User

class LogoutTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.user = User.objects.create_user(
            username='user1',
            email='user1_123@gmail.com',
            password='top_secret123'
        )

    def test_user_logs_out(self):
        self.client.login(email=self.user.email, password=self.user.password)
        self.assertTrue(self.user.is_authenticated)

        response = self.client.get('/logout/')

        self.assertFalse(self.user.is_authenticated)
        self.assertRedirects(response, '/', 302)

The assertion self.assertFalse(self.user.is_authenticated) is failing. Testing through the browser seems to work fine. It seems like the user would not be authenticated after calling logout(). Am I missing something?

A:
It seems like the user would not be authenticated after calling logout(). Am I missing something?

.is_authenticated [Django-doc] does not check if a user is logged in. Every real User returns always True for is_authenticated. An AnonymousUser [Django-doc] will return False for example. If you thus log out, then request.user will be the AnonymousUser, and thus not be authenticated.
In other words, if you use request.user.is_authenticated, you will call this on the logged-in user if the session is bounded to a user (you logged in with the browser), and you call this on the AnonymousUser in case the browser did not log in a user/the browser logged out.


text:
Q: How to capture output of a child process in purescript? I am new to both purescript and haskell (and even javascript and node), so I am stumped in trying to figure out how to save off the output of a child process in purescript.  I am using the purescript-node-childprocess and purescript-node-fs modules.  Basically, the problem I am having is this:
import Node.ChildProcess (CHILD_PROCESS, SpawnOptions, defaultSpawnOptions, Exit(..), spawn, onExit, stdout)
import Node.Stream (onData)

type CPEffect = forall e
              .  Eff (cp :: CHILD_PROCESS
                     , console :: CONSOLE
                     , err :: EXCEPTION
                     , buffer :: BUFFER | e
                     ) Unit

-- | Basically a wrapper around the spawn command.
-- | Takes a command, an array of arguments, and a record of
-- | options to pass to spawn.
launch :: String -> Array String -> SpawnOptions -> CPEffect
launch cmd args opts = do
  cmd' <- spawn cmd args opts
  onExit cmd' defaultExitHdlr
  -- My problem is with onData due to its return type
  onData (stdout cmd') -- what do I put as the callback handler arg?
  log $ "done with " <> cmd

As shown in my comment above, the problem is the onData function which comes from the Node.Stream module.  The problem is in the 2nd arg and return type:
onData :: forall w eff
        . Readable w (err :: EXCEPTION | eff)
       -> (Buffer -> Eff (err :: EXCEPTION | eff) Unit)
       -> Eff (err :: EXCEPTION | eff) Unit

Since the return is an Eff which returns Unit, how can I save off the child process output?  The 2nd argument is a function which takes a Buffer and also returns the same type.  Indeed, it is this function which is getting the data from the Readable (which is the stdout of the childprocess).  In other words, the first argument is the stdout stream from node of the child process, and the 2nd arg is a callback handler which will fill in the buffer from the stdout stream.
But since callback handler returns Unit, I don't see how I can accumulate the output from the child process.  I am still in the process of learning Monad Transformers, so is this a solution?  Can I create a Writer monad that somehow wraps this?

A: If I was going to do this in purescript without using the FFI, I would use a Ref, and in the onData callback, read the ref value, make a new string by appending the new data to the ref value, and then update the ref value with this new string.
WriterT is indeed useful for this kind of thing although I probably would not use it in this particular case, because it could be a bit awkward to work out how to get the types to line up, since the callback takes Eff, not WriterT something Eff.
Another option, which I used to solve this exact issue in Pulp, is to use the npm package concat-stream. In fact you might well find Pulp useful as a real world example of using these libraries - I think the modules Pulp.Exec and Pulp.System.Stream are the ones you will be interested in.

A: In pscid I'm using an STRef to concatenate the output of a process and print its results to the console when the process exits. I've copied the relevant code so that you have an example:
execCommand
  ∷ ∀ e
  . String
  → String
  → Eff (cp ∷ CHILD_PROCESS, console ∷ CONSOLE | e) Unit
execCommand name command =
   catchLog (name <> " threw an exception") $
    runST do
      let cmd = unsafePartial fromJust (uncons (split (Pattern " ") command))
      output ← newSTRef ""
      log ("Running: \"" <> command <> "\"")
      cp ← spawn cmd.head cmd.tail defaultSpawnOptions

      let stout = stdout cp
          sterr = stderr cp

      onDataString stout UTF8 \s →
        modifySTRef output (_ <> s) $> unit

      onDataString sterr UTF8 \s →
        modifySTRef output (_ <> s) $> unit

      onExit cp \e → case e of
        Normally 0 → logColored Green (name <> " successful!")
        Normally code → do
          log =<< readSTRef output
          logColored Red (name <> " errored with code: " <> show code)
        BySignal _       → pure unit


text:
Q: Manual run works, but not cron Have a problem with a php script to get the title of a URL. It works when I run it manually, but not when I run it through cron.
Googled to get a small script to get the title of a URL:
function getTitle($url) {
    $fh = fopen($url, "r");
    $str = fread($fh, 7500);
    fclose($fh);
    $str2 = strtolower($str);
    $start = strpos($str2, "<title>")+7;
    $len   = strpos($str2, "</title>") - $start;
    if ($start == 7)
            return $url;
    return substr($str, $start, $len);
}

I then run the below, where I look for urls in texts, and prints the url with titel:
$data = mysql_query('SELECT * FROM msgs ORDER BY id DESC LIMIT 100');
while ($rad = mysql_fetch_array($data)) {
    preg_match_all($pattern, $rad["text"], $a);
    $count = count($a[1]);
    for ($row = 0; $row < $count ; $row++) {
        echo 'URL:'.$a[1]["$row"].'
';
        echo 'TITLE:'.getTitle($a[1]["$row"]).'

';
    }
}

The above code resides in url.php. When I run it manually through the browser it works fine and prints the url with correct title. However, when I run in as a scheduled cron job (once every minute) it writes url and url, i.e. it seems like getTitle always interpret "$start == 7" to be true.
Can this have to do with timing? Does fopen and fread take to much time? If so, how can I fix this.
I've seen a typical cron problem is env. variables, but I don't see how that can affect this?
Any help or ideas are welcome!

A: It usually happens because you have a different environment in your cron (or when you run as a different user).
When you run it in the command line you have a different environment that you can read by running "env".
You can change the environment prepending variables to the command you're running. Like:
PATH=/bin:/usr/local/bin php myprogram.php
Something else that you should do is enable error reporting in your PHP script.
fopen could return FALSE for instance and you have to catch such errors. "$start == 7" happens when you prepend the empty string to your expression thus this can be the result of an unhandled error.
Running error_reporting(E_ALL) while you debug could help here.


text:
Q: nginx regex characters that require quoting? So I was configuring nginx today and I hit a weird problem. I was trying to match a location like this:
location ~ ^/([0-9]+)/(.*) {
    # do proxy redirects
}

...for URLs like "http://my.domain.com/0001/index.html".
This rule was never matching, despite the fact that it by all rights should. It took me awhile to figure out, based on this documentation, that some characters in regexes need to be quoted. The problem is, the documentation is for rewrites, and it specifically calls out curly braces, not square brackets. After a fair bit of experimentation that involved a lot of swearing, I discovered that I could fix the problem by quoting the regex like so:
location ~ "^/([0-9]+)/(.*)" {
    # do proxy redirects
}

Is there a list somewhere of characters that nginx requires quoting regexes with? Or could there be something else going on here that I'm totally missing? This is my first nginx configuration job, so it's very possible I've misunderstood something...

A: Do you need the number? I'd try a simpler variant first and see if the error is maybe something else.
I'd try if ^/[0-9]+/, or do you need the captured elements?


text:
Q: Put points of question into brackets in exsheets I want align the points value of questions to margin and put inside brackets with exsheets package.
MWE:
\documentclass[a4paper]{article}
\usepackage[load-headings,load-tasks,]{exsheets}
\usepackage{lipsum}
\SetupExSheets{
    points/name = pont,
    points/number-format=\textit,
    headings = margin-nr,
    headings-format = \normalfont,
    counter-within=section,
    solution/name = Megoldás
}
\DeclareInstance{exsheets-heading}{my-no-nr}{default}{
    toc-reversed = true,
    indent-first = true,
    vscale = 2,
    post-code = \rule{\linewidth}{1pt},
    title-format = \Large\scshape,
    join = {
        main[l,vc]title[l,B](0pt,0pt) ;
    },
}
\RenewQuSolPair
  {question}[headings=margin-nr]
  {solution}[headings=my-no-nr]
%
\begin{document}
\begin{question}{10}
    \lipsum[1]
\end{question}
\begin{question}{10}
    \lipsum[2]
\end{question}
\end{document}

So I want replace "10 pont" to "(10 pont)". How can I do this?

A: If you want to place all appearances of points in parentheses (i.e. also those created with \pointssum and friends) you can define a command
\newcommand*\pointsformat[1]{(#1)}

and then set the option
\SetupExSheets{
  points/format = \pointsformat
}

If you only want to place the points in the margin in parentheses you need to modify the headings instance you're using for the questions instead:
\documentclass[a4paper]{article}
\usepackage[load-headings,load-tasks,]{exsheets}
\usepackage{lipsum}
\SetupExSheets{
    points/name = pont,
    points/number-format=\textit,
    headings = margin-nr,
    headings-format = \normalfont,
    counter-within=section,
    solution/name = Megoldás
}
\DeclareInstance{exsheets-heading}{my-no-nr}{default}{
    toc-reversed = true,
    indent-first = true,
    vscale = 2,
    post-code = \rule{\linewidth}{1pt},
    title-format = \Large\scshape,
    join = {
        main[l,vc]title[l,B](0pt,0pt) ;
    }
}
\DeclareInstance{exsheets-heading}{margin-nr}{default}{
  runin = true ,
  attach = {
    main[l,vc]number[r,vc](-.333em,0pt) ;
    main[r,vc]points[l,vc](\linewidth+\marginparsep,0pt)
  } ,
  points-pre-code = ( ,  % <= this is different
  points-post-code = ) , % <= this is different
}

\RenewQuSolPair
  {question}[headings=margin-nr]
  {solution}[headings=my-no-nr]
%
\begin{document}
\begin{question}{10}
    \lipsum[1]
\end{question}
\begin{question}{10}
    \lipsum[2]
\end{question}
\end{document}


text:
Q: The import org.apache.cordova cannot be resolved For some reason, after going through Phonegap's non-inclusive instructions (it doesn't even mention setting up ANT, or the headaches with Ant and JDK), this doesn't work at all:
package com.HealthTrustSoftware.AndroidTemplate3;

import android.app.Activity;
import android.os.Bundle;
import org.apache.cordova.*;

public class AndroidTemplate3 extends DroidGap
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        super.loadUrl("file:///android_asset/www/index.html");
    }
}

It gives 5 errors referencing the fact that org.apache.cordova can't be resolved.  I'm entirely sure what to do at this point.  Please help.  This is after 3 hours of trying to get the sdk working and finally being able to open a project within eclipse.  After following the steps on their documentation, I am left with a wasted 3 hours unless I can figure this out.

A: In addition to copying cordova-2.2.0.jar from the phonegapp download to the libs folder of the project I had to manually add it to the projects libraries.
Procedure: Project -> properties -> Java Build Path -> Libraries -> Add JARs... Then select the libs from the project itself

A: Android studio: File -> Invalidate cache / Restart. Worked for me...

A: I just ran into the same problem. Following what was written in here, I finally made it work.
After you download cordova from phonegap github page, you will find cordova-2.2.0.jar and cordova-2.2.0.js in lib/android folder. After running "./create ...", copy cordova-2.2.0.jar into your projects libs folder and cordova-2.2.0.js into your www folder. Then import the project into eclipse and it should work.
I had to go to "Project -> Properties -> Android" and select a newer SDK (I selected the latest one available on the list) and than run the "Project -> Clean" as well.

A: I initially got around this using one of the solutions posted above: about downloading the phonegap from github and pasting in the cordova-2.2.0.jar and cordova-2.2.0.js files into the generated directories.
After fiddling around with the path and environment variables these files are already in place (project/libs/cordova-2.2.0.jar and project/assets/www/cordova-2.2.0.js) now for me after running the "create" command on command line.
I am using the ANT that came bundled with Eclipse so my PATH variable includes:
C:\Program Files\Eclipse\plugins\org.apache.ant_1.8.3.v20120321-1730\bin;
and I added an environment variable for ANT_HOME of:
C:\Program Files\Eclipse\plugins\org.apache.ant_1.8.3.v20120321-1730
I tested adding \bin or removing it to both the PATH and environment variable for ANT_HOME and this was the winning combination.

A: Run cordova -d build. If it says anything about "Unable to locate tools.jar", fix that. Then  completely rebuild the application by running cordova platform rm android. Also remove the project from eclispe. Then recreate the app by running cordova platform add android + cordova build. Finally add the project in eclipse again.
org.apache.cordova should now be included and everything should be working.

A: Replace  your header with some miner changes   like bellow
 import com.google.android.gcm.GCMRegistrar;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.CordovaPlugin;

A: Step 4 in the getting started guide is the only part specific to phonegap. The rest is setting up a general android development environment. Instead of eclipse classic, get the ADT bundle from http://developer.android.com/sdk/index.html - that includes a custom version of eclipse with most of the android stuff ready to go.
The default link to cordova-2.2.0.jar worked fine for me, though it did take a bit of effort to work out that if you want to use a custom build of cordova it needs to be set up as an android library dependency in project properties.

A: Download apache cordova jar and add it to lib folder and classpath.


text:
Q: VMware virtual machines wont resume from the command line I'm running VMWare Workstation on Ubuntu 10.10.  I have a series of virtual machines that I clone every week.
I've written a bash script that cycles through each of the virtual machines, softly suspends it, clones it, and then attempts to resume it.
The problem is, the VM's do not resume, so I have to manually resume them.  I'm trying to figure out how I can modify the script I've written to ensure the VMs resume.  I've included the script and a sample of the generated logfile showing the error message.
#!/bin/bash

##Author:   William Cooper
##Date: 2/15/2011
## Purpose:     Perform full backups of Virtual Machines
##      Running under VMWare Workstation

## Script won't run if the /nas directory doesn't exist
## The /nas directory is a mounted Buffalo Terastation
## Check /etc/fstab if this mountpoint is broken
   BACKUPDEST="/nas"

## No need to modify
   HOST=`hostname`
   DATEFILE=`/bin/date +%G%m%d`

## Run Command to find list of VM names:
## this will only be the name of the vm, no path and no .vmx
   VMLIST=`vmrun list | grep '/' | cut -d'/' -f3 | cut -d'.' -f1`

## Initialize Counter variable used to cycle through VMs in VMARRAY variable
   COUNTER=1

## Run Command to find list of VM Names and then store them in an Array:
## This will include full pathnames
   VMARRAY=( `vmrun list | grep '/'` )

#################################################################
## Functions

##
## Notify the starting time of backup in the log
##
function startScript {
   echo
   echo "----------------------------------------------------"
   echo "START - ${VM}"
   echo "Host: ${HOST}"
   echo "Date: `date`"
   echo
}

##
## Suspend VM
##
function suspendVM {
   ## Suspend the VM
   echo "Attempting to softly suspend "${VM}" . . ."
   vmrun suspend ${VMARRAY[${COUNTER}]} soft
   echo "${VM} Suspended on `date`"
   echo
}

##
## Backup VM
##
function doBackup {

   ## Check to see if the correct backup directory exists.
   if [ ! -d ${BACKUPDEST}/${VM} ]; then
      echo "${BACKUPDEST}/${VM} does not exist, creating . . ."
      mkdir "${BACKUPDEST}/${VM}"
      echo
   fi

   ## Backup VM (clone)
   echo "Backup of "${VM}" began: `date`"
   echo "Backup to ${BACKUPDEST}/${VM}/BACKUP/${DATEFILE} . . ."
   mkdir ${BACKUPDEST}/${VM}/BACKUP/${DATEFILE}
   vmrun clone ${VMARRAY[${COUNTER}]} ${BACKUPDEST}/${VM}/BACKUP/${DATEFILE}/${VM}.vmx full
   echo "Backup of "${VM}" ended: `date`"
   echo
}

##
## Start VM
##
function doStart {
   ## Resume VMs which were running [--type gui|sdl|vrdp|headless]
   echo "Attempting to resume "${VM}" . . ."
   vmrun start ${VMARRAY[${COUNTER}]}
   echo "${VM} Resumed on `date`"
   echo
}

##
## Notify the finishing time of backup in the log
##
function finishScript {
   echo "FINISH - ${VM}"
   echo "Host: ${HOST}"
   echo "Date: `date`"
   echo "----------------------------------------------------"
   echo
}

#################################################################
## Script

for VM in ${VMLIST}
do

   sleep 1
   ## StartScrip executes for logging
      startScript

   ## Suspend VM performs soft suspend
      suspendVM
      sleep 3

   ## Do Backup performs the VM clone
      doBackup
      sleep 3

   ## Start VM performs start vm
      doStart
      sleep 3

   ## FinishScript executes for logging
      finishScript

   ## Increment the Counter
      COUNTER=${COUNTER}+1

done | tee "${BACKUPDEST}/logs/VMClone_${DATEFILE}.log"

## Script
#################################################################
exit

An example of the generated logfile for each VM is shown below.
----------------------------------------------------
START - vmname
Host: servername
Date: Sat Feb 19 12:30:29 CST 2011

Attempting to softly suspend vmname . . .
vmname Suspended on Sat Feb 19 12:30:44 CST 2011

Backup of vmname began: Sat Feb 19 12:30:47 CST 2011
Backup to /nas/vmname/BACKUP/20110219 . . .
Backup of vmname ended: Sat Feb 19 12:43:16 CST 2011

Attempting to resume vmname . . .
Error: Cannot launch the UI because no display server is present in the current environment
vmname Resumed on Sat Feb 19 12:43:20 CST 2011

FINISH - vmname
Host: servername
Date: Sat Feb 19 12:43:23 CST 2011
----------------------------------------------------

Error: Cannot launch the UI because no display server is present in the current environment

A: You could use the nogui paramater to the start command, e.g:
vmrun start yourmachine.vmx nogui

See: http://www.vmware.com/pdf/vix180_vmrun_command.pdf

A: Since no solid answer has been found I'm just going to accept that under these specific circumstances there is no fix.

*

*Ubuntu 10.10 x64

*VMware Workstation 7

Solution: Close down VMware Workstation and choose for the VMs to "Run in the Background"
Works flawlessly after that.

A: try doing echo $DISPLAY on your terminal TTY where vmware workstation runs.
The echo $DISPLAY will return like :1000.0
you need to set
export DISPLAY=":1000.0"   in your script. then the script will resume the VM's..
i found this works when i use areca backup to resume my VM using postscript run in areca.

A: if the problem is because you are running vmrun from a ssh session, then another solution might be run a screen session on the server.
on the machine Workstation is running:
screen -S vmware

on the client machine,
ssh vmware-machine
screen -x vmware
vmrun start /path/to/vm.vmx


text:
Q: fflush() is not working in Linux I used the fflush() in Linux GCC but it did not work. Are there any alternatives for that function? Here is my code:
#include<stdio.h>
void main()
{
  char ch='y';
  while(ch=='y')
  {
    int a;
    printf("Enter some value:");
    scanf("%d",&a);
    fflush(stdin);
    printf("Do you want to continue?");
    scanf("%c",&ch)
  }

The output that I got is:
Enter some value: 10

Then the program ends. That's all. What can I do in Linux? Is there an alternative function?

A: One that always works on Linux:
#include <termios.h>
#include <unistd.h>

void clean_stdin()
{
        int stdin_copy = dup(STDIN_FILENO);
        /* remove garbage from stdin */
        tcdrain(stdin_copy);
        tcflush(stdin_copy, TCIFLUSH);
        close(stdin_copy);
}

You can use tcdrain and tcflush not only for in/out/err fd.

A: The behavior of fflush is not defined for input streams (online 2011 standard):

7.21.5.2 The fflush function
Synopsis
1
    #include <stdio.h>
    int fflush(FILE *stream);

Description
2 If stream points to an output stream or an update stream in which the most recent
 operation was not input, the fflush function causes any unwritten data for that stream
to be delivered to the host environment to be written to the file; otherwise, the behavior is
 undefined.
3 If stream is a null pointer, the fflush function performs this flushing action on all
   streams for which the behavior is defined above.
Returns
4
The fflush function sets the error indicator for the stream and returns EOF if a write
error occurs, otherwise it returns zero.

A: I faced the same problem while working on LINUX and an alternative solution of this problem can be that you define a dummy character lets say char dummy;
and put a scanf() to scan it just before your actual input takes place. This worked for me. I hope it would work for you too.

A: Don't use fflush, use this function instead:
#include <stdio.h>
void clean_stdin(void)
{
    int c;
    do {
        c = getchar();
    } while (c != '\n' && c != EOF);
}

fflush(stdin) depends of the implementation, but this function always works. In C, it is considered bad practice to use fflush(stdin).

A: fflush() doesn't do much for input streams but since scanf() never returns this doesn't matter. scanf() blocks because the terminal window doesn't send anything to the C program until you press Enter
You have two options:

*

*Type 10 Enter

*Put the terminal into raw mode.

The second option has many drawbacls like you will lose editing capabilities, so I suggest to read the input line by line.

A: You must include  and use __fpurge(whatever you want) instead.
Salute from argentina

A: Use getchar() instead, after scanf

A: #include<stdio.h>
int main()
{
char ans='y';
int a;
while(ans=='y'||ans=='Y')
    {

     printf("Type a number:-");
     scanf("%d",&a);
     printf("square of number = %d\nwant to enter
     number again(y/n)?\nANS=",a*a);
     scanf("%s",&ans);//use %s in place of %c
     }
return 0;
}

A: By using bzero(); system call in Linux we can flush the previous stored value.
Please read the manual page of bzero(); by typing in terminal man bzero.
try this example
#include<stdio.h>
#include<string.h>

int main()
{
  char buf[]={'y'};
  int num;
  while(buf[0]=='y')
  {
    printf("enter number");
    scanf("%d",&num);
    printf("square of %d is %d\n",num,num*num);
    bzero(buf, 1);
    printf("want to enter y/n");
    scanf("%s",&buf[0]);
  }
  return 0;
}


text:
Q: Unable to get jQuery on() to register dynamically added content I'm quite new to the on() method in jQuery but the time has come for me to need to use it.
I've two functions for clicking on specific buttons. Each function works on any elements originally on the page but not on any dynamically added content (more of the same buttons). I understand I need to use the on() function after reading other answers on here and on Google but am having trouble still. Anyway, code:
jQuery("ul#THEBUTTONS").on({
    click: function(event){
        event.preventDefault();
        console.log("apaz clicked");
    }
}, "a.azaz");

jQuery("ul#THEBUTTONS").on({
    click: function(event){
        event.preventDefault();
        console.log("mapaz clicked");
    }
}, "a.mapaz");

Any help would be immensely appreciated, tearing my hair out here.

A: .on() essentially has two flavors: one which acts like .bind(), and another which acts like .delegate().
For your problem, you want to use the delegate version. As a reference, on signatures are like this:
// bind
$(element-selector).on(event, handler)

// delegate
$(container-selector).on(event, element-selector, handler)

The best way to get up to speed with this is probably to read up on delegate, what it is, how its used, and then apply that to on.

A: There are two ways to use .on(), and you're using the wrong type.
You can bind event handlers directly to elements using $('selector for elements you want the event handler bound to').on('event', function() {...});
Or, you can delegate events, by calling .on() on a wrapper element that will contain all of the dynamically added elements, such as a div or, in the worst case, the  element. Code would look something like this:

    Test link

$('#wrapper').on('click', '.link', function(e) {
    // code to handle the click event on the link here
});

The event handler is actually handled by the
 element once the event has bubbled up to it, but the function is only called if the original target matches the selector provided. With this method, you can dynamically add additional elements with the class link to the div, and the function will also run when they're clicked on.


text:
Q: matrices program asking for user input # 3x3
X = [[0,0,0],
    [0 ,5,6],
    [7 ,0,0]]
# 3x4
Y = [[0,0,0,0],
    [0,0,0,0],
    [0,0,0,0]]
# 3x4
result = [[0,0,0,0],
         [0,0,0,0],
         [0,0,0,0]]

# iterate through rows of X
for i in range(len(X)):
   # iterate through columns of Y
   for j in range(len(Y[0])):
       # iterate through rows of Y
       for k in range(len(Y)):
           result[i][j] += X[i][k] * Y[k][j]
#This code multiplies matrices X and Y and puts the resulting product into matrix result
#It then prints the matrix result row by row, so it looks like a matrix on the screen
for r in result:
   print(r)

here i have a program that will work out a matrix but i was wondering on how to ask the user for the input when running the program instead of inputting the numbers beforehand

A: A particularly easy way to get two matrices from the user is to use the function literal_eval from the module ast:
import ast
X = ast.literal_eval(input("Enter the first matrix as a list of lists: "))
Y = ast.literal_eval(input("Enter the second matrix: "))
#code to compute X*Y -- note that you can't hard-wire the size of result

The beauty of this approach is that if the user enters [[1,2],[3,4]] at the prompt (which yields the string '[[1,2],[3,4]]') then literal_eval converts this string to the list [[1,2],[3,4]].
To make this approach robust you should use error-trapping to gracefully handle situations where the user e.g. enters [[1,2][3,4]] by mistake.
As far as not hard-wiring in the size of result: Since the product is filled in row by row, I recommend refactoring your code by initializing result as an empty list to which rows are appended as they are calculated. As a template something like:
result = []
for i in range(len(X)):
   row = [0]*len(Y[0])
   for j in range(len(Y[0])):
       # code to compute the jth element of row i
   result.append(row)


text:
Q: Check if mouse is over multiple elements in JQuery? So I'm working on a drop down menu and ran into an issue...here is the code...
$('#layer2_cell1').hide();

$("#layer1_cell1").mouseenter(function () {
    $('#layer2_cell1').show();
    $("#storage").data('airplanesmain', '1');
});
$("#layer1_cell1").mouseleave(function () {
    $("#storage").data('airplanesmain', '0');
    var subcell = $("#storage").data('airplanessubcell');
    if (subcell == '0') {
        $('#layer2_cell1').hide();
    }
});
$("#layer2_cell1").mouseenter(function () {
    $("#storage").data('airplanessubcell', '1');
});
$("#layer2_cell1").mouseleave(function () {
    $("#storage").data('airplanessubcell', '0');
});

I'm trying to hide layer2_cell1 if my mouse is outside of the layer1_cell1 and layer2_cell1 this seems like it would do it but it dosnt. Help!

A: Hi I have written a CSS only menu here http://jsfiddle.net/P8ZH6/3/ as there is no need to use JavaScript.
You can attach JavaScript events to the menu items if you need them to display the dynamic content above the menu.
Something like this could work.
$(document).ready(function(){
$(".menu li").hover(function(){
   $("#dynamic_content").html($(this).parents(".menu_1").find("span").html() + "->" + $(this).find("a").text());
})

$(".menu .menu_1 span").hover(function(){
   $("#dynamic_content").html($(this).html());
})

$(".menu li, .menu .menu_1 span").mouseout(function(){
   $("#dynamic_content").html("");
 });

});

Hope this works for you.


text:
Q: New suspension message: "Grounded" This is a quiet lament for two apparently under-age users Benny & Nyuszika7h whose accounts have been temporarily suspended.
It would be nice to mark their accounts as "temporarily grounded", as they haven't actually done anything 'bad'.
It would also be nice for the team to "add a nice word or two, maybe that this has legal reasons, and that they're welcome back when they're thirteen" (if that hasn't been done already).

For those who aren't aware, the terms and conditions stipulate that users should not be under 13. For some reason, this subject must have come to the fore, and these two users (maybe others) got nobbled. I'm guessing that it's because they self-identified as really being under 13 in other contexts than just their user profile, because there are plenty of users here who aren't suspended.
More here.
[It is mildly ironic that by suspending Nyuszika7h, SO also unwittingly disclosed his date of birth (he gets unsuspended on his 13th birthday :)]
(Some more retroactive irony in xiaohouzi79's suggestion to Benny in his penultimate paragraph here).

A: When these accounts are suspended (and please note, this is extremely rare - you have to go out of your way to volunteer personal information in order for this to happen), it is done because they have violated the site's Terms of Service:

1. Access to the Services
[...]
Subscriber certifies to Stack Exchange that if Subscriber is an individual (i.e., not a corporate entity), Subscriber is at least 13 years of age. No one under the age of 13 may provide any personal information to or on Stack Exchange (including, for example, a name, address, telephone number or email address).
[...]

So the correct reason is, suspended for rule violations.


text:
Q: Stored procedure update to remove duplicates This is my stored procedure:
ALTER PROCEDURE [dbo].[Proc_SAP_Mat_InsertWhereUse]
    (@cust varchar(10),
     @materials varchar(15),
     @Comp varchar(20),
     @qty int)

    SET NOCOUNT ON;

    IF EXISTS ((SELECT DISTINCT COUNT(*) FROM [SAP_Mat_WhereUse]
                WHERE Material = @materials AND Component = @Comp
                HAVING COUNT(*) > 0))
    BEGIN
        IF EXISTS ((SELECT DISTINCT COUNT(*) FROM [SAP_Mat_WhereUse]
                    WHERE Material = @materials AND Component = @Comp
                      AND Quantity =  @qty
                    HAVNG COUNT(*) = 0))
        BEGIN
            UPDATE [SAP_Mat_WhereUse]
            SET Quantity =  @qty
            WHERE Material = @materials AND Component = @Comp
        END
    END
    ELSE IF ((SELECT DISTINCT COUNT(*) FROM [SAP_Mat_WhereUse]
              WHERE Material = @materials AND Component = @Comp
                AND Quantity = @qty) = 0)
    BEGIN
        INSERT INTO SAP_Mat_WhereUse (Customer, Material, Component, Quantity)
        VALUES (@cust, @materials, @Comp, @qty)
    END

This is my database data
https://i.stack.imgur.com/HlD3d.png
If there are any duplicated material + duplicated component, then the stored procedure should automatically remove the duplicated rows and update the quantity of the primary row. And duplicated material + non-duplicated component shall  remain.
Therefore, I can remove the duplicate but the quantity count remain the same, is there any modification need to be made on my existing stored procedure? Please help

A: If I were you, I would try to fix the data first and then changing the procedure only to INSERT or UPDATE. For example, the following code should do that (but please, test it first):
WITH DataSource AS
(
    SELECT Customer
          ,Material
          ,Component
          ,SUM(ISNULL(quantity, 0)) OVER (PARTITION BY  Customer, Material, Component) AS [OveralQty]
          ,ROW_NUMBER() OVER (PARTITION BY  Customer, Material, Component ORDER BY (SELECT 1)) AS [RowID]
    FROM [SAP_Mat_WhereUse]
)
SELECT *
INTO #DataSource
FROM DataSource
WHERE [RowID] = 1;

TRUNCATE TABLE [SAP_Mat_WhereUse];

INSERT INTO [SAP_Mat_WhereUse]
SELECT *
FROM #DataSource;

Then, you can change your routine like this:
ALTER PROCEDURE [dbo].[Proc_SAP_Mat_InsertWhereUse]
(@cust varchar(10),
 @materials varchar(15),
 @Comp varchar(20),
 @qty int)
 AS
 BEGIN;

SET NOCOUNT ON;

IF EXISTS
(
    SELECT 1
    FROM [SAP_Mat_WhereUse]
    WHERE Material = @materials
        AND Component = @Comp
        AND Customer = @cust
)
    BEGIN
        UPDATE [SAP_Mat_WhereUse]
        SET Quantity =  @qty
        WHERE Material = @materials
            AND Component = @Comp
            AND Customer = @cust;
    END
ELSE
    BEGIN
        INSERT INTO SAP_Mat_WhereUse (Customer, Material, Component, Quantity)
        VALUES (@cust, @materials, @Comp, @qty);
    END

END

Of course, depending on your data size, you may not be able to fix the data at one and prefer to do it gradually.
You can apply the same fix, but for particular rows:
WITH DataSource AS
(
    SELECT Customer
          ,Material
          ,Component
          ,SUM(ISNULL(quantity, 0)) OVER () AS [OveralQty]
          ,ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS [RowID]
    FROM [SAP_Mat_WhereUse]
    WHERE Customer = @cust
        AND Material = @materials
        AND Component  = @comp
)
SELECT *
INTO #DataSource
FROM DataSource
WHERE [RowID] = 1;

DELETE FROM [SAP_Mat_WhereUse]
WHERE Customer = @cust
    AND Material = @materials
    AND Component  = @comp

INSERT INTO [SAP_Mat_WhereUse]
SELECT Customer
      ,Material
      ,Component
      ,[OveralQty] + qty
FROM #DataSource;

or (because there are many variants to do this) - you can just sum(quantity) in your current code, store it in a variable and then add it.


text:
Q: getCookie in OmniFaces? I found out that I can generate Cookies with Omnifaces, like:
    public void addCookie(String cookieName, String cookieValue) throws IOException {
            Faces.addResponseCookie(cookieName, cookieValue, "https://myurl.com", "/", -1);
        Faces.refresh();
}

As far I understood I can GET also the Cookie, like:
public String findCookie(String cookieName) throws IOException {

            String cookieValue = Faces.getRequestCookie(cookieName);
            return cookieValue;

    }

But what is unclear for me:
In findCookie(): for what should I search, because in create method I have also the page name included?
I´m missing in Faces.getRequestCookie(cookieName) the application name, like:
Faces.getRequestCookie(cookieName, applicationName);
Or should I save the cookieName, like:
String myCookie = "myPageName" + "myCookie";
Any ideas?


text:
Q: Opening java file with button (javafx) I've got an app made in javafx and another class with menu in this project. In this menu I've got two buttons and one works (exit buuton) and I want buttonStart to open my Main class. How to launch it?
Button buttonStart = new Button("START GAME");

Button buttonExit = new Button("EXIT");

    buttonExit.setOnMouseClicked(event -> System.exit(0));

My menu:
package pl.main;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class Menu extends Application {

    private BorderPane layout;
    private Scene scene;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage window) throws Exception {
        layout = new BorderPane();
        scene = new Scene(layout, 720, 480);

        HBox hbox = new HBox();
        hbox.setPadding(new Insets(15, 12, 15, 12));
        hbox.setSpacing(10);
        hbox.setStyle("-fx-background-color: #F9A825;");

        Button buttonStart = new Button("START GAME");
        buttonStart.setPrefSize(100, 20);
        buttonStart.setStyle("-fx-background-color: #E65100;");

        Button buttonExit = new Button("EXIT");
        buttonExit.setPrefSize(100, 20);
        buttonExit.setStyle("-fx-background-color: #E65100;");

        buttonExit.setOnMouseClicked(event -> System.exit(0));
        hbox.getChildren().addAll(buttonStart, buttonExit);

        layout.setCenter(hbox);

        window.setScene(scene);
        window.show();
    }
}

Class which I wanna launch:
package pl.main;

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import java.util.ArrayList;
import java.util.HashMap;

public class Main extends Application {

    private HashMap<KeyCode, Boolean> keys = new HashMap<KeyCode, Boolean>();
    private ArrayList<Node> blocks = new ArrayList<Node>();
    private Pane appRoot = new Pane();

    private Pane gameRoot = new Pane();
    private Pane uiRoot = new Pane();

    private Node player;
    private Point2D playerGoDown = new Point2D(0, 0);
    private Point2D playerGoRight = new Point2D(0, 0);
    private boolean canJump = true;
    private int levelWidth;

    private void initContent() {
        Rectangle background = new Rectangle(720, 480);
        // BackgroundFill(Color.WHITE);

        levelWidth = LevelData.LEVEL1[0].length();

        for (int i = 0; i < LevelData.LEVEL1.length; i++) {
            String map = LevelData.LEVEL1[i] + LevelData.LEVEL2[i]+ LevelData.LEVEL1[i]+ LevelData.LEVEL2[i]+ LevelData.LEVEL1[i]+ LevelData.LEVEL2[i];

            String line = map;
            for (int j = 0; j < line.length(); j++) {
                switch (line.charAt(j)) {
                case '0':
                    break;
                case '1':
                    Node block = createEntity(j * 30, i * 30, 30, 30, Color.ORANGE);
                    blocks.add(block);
                    break;
                }
            }
        }
        player = createEntity(0, 350, 40, 40, Color.YELLOW);
        // a ????????????
        player.translateXProperty().addListener((a, old, newValue) -> {
            int offset = newValue.intValue();
            //if (offset > 360 && offset < levelWidth - 360) {
                gameRoot.setLayoutX(-(offset - 360));
            //}
        });
        appRoot.getChildren().addAll(background, gameRoot, uiRoot);
    }

    private void update() {
        if (isPressed(KeyCode.W) && player.getTranslateY() >= 0) {
            jumpPlayer();
        }
        if (playerGoDown.getY() < 10) {
            playerGoDown = playerGoDown.add(0, 1);
        }
        movePlayerY((int) playerGoDown.getY());

        if (player.getTranslateX() <= levelWidth - 5) {
            // movePlayerX(5);
            movePlayerRight();
        }

        if (playerGoRight.getX() < 0) {
            playerGoRight = playerGoRight.add(0, 1);
        }
        movePlayerX((int) playerGoRight.getX());
    }

    private void movePlayerX(int value) {
        boolean movingRight = value > 0;
        for (int i = 0; i < Math.abs(value); i++) {
            for (Node block : blocks) {
                if (player.getBoundsInParent().intersects(block.getBoundsInParent())) {
                    if (movingRight) {
                        if (player.getTranslateX() + 40 == block.getTranslateX()) {
                            return;
                        }
                    } else {
                        if (player.getTranslateX() == block.getTranslateX() + 60) {
                            return;
                        }
                    }
                }
            }
            player.setTranslateX(player.getTranslateX() + (movingRight ? 1 : -1));
        }
    }

    private void movePlayerY(int value) {
        boolean movingDown = value > 0;
        for (int i = 0; i < Math.abs(value); i++) {
            for (Node block : blocks) {
                if (player.getBoundsInParent().intersects(block.getBoundsInParent())) {
                    if (movingDown) {
                        if (player.getTranslateY() + 40 == block.getTranslateY()) {
                            canJump = true;
                            return;
                        }
                    } else {
                        if (player.getTranslateY() == block.getTranslateY() + 60) {
                            return;
                        }
                    }
                }
            }
            player.setTranslateY(player.getTranslateY() + (movingDown ? 1 : -1));
        }
    }

    private void jumpPlayer() {
        if (canJump) {
            playerGoDown = playerGoDown.add(0, -10);
            canJump = false;
        }
    }

    private void movePlayerRight() {
        playerGoRight = playerGoRight.add(10, 0);
    }

    private Node createEntity(int x, int y, int w, int h, Color color) {
        Rectangle entity = new Rectangle(w, h);
        entity.setTranslateX(x);
        entity.setTranslateY(y);
        entity.setFill(color);
        gameRoot.getChildren().add(entity);
        return entity;

    }

    private boolean isPressed(KeyCode key) {
        return keys.getOrDefault(key, false);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        initContent();
        Scene scene = new Scene(appRoot);
        scene.setOnKeyPressed(event -> keys.put(event.getCode(), true));
        scene.setOnKeyReleased(event -> keys.put(event.getCode(), false));
        primaryStage.setTitle("Jetpack gameplay");
        primaryStage.setScene(scene);
        primaryStage.show();
        primaryStage.setResizable(false);
        AnimationTimer timer = new AnimationTimer() {
            @Override
            public void handle(long now) {
                update();
            }
        };
        timer.start();
    }

    public static void main(String[] args) {

        launch(args);
    }
}

In future I wanna change current Main.java into ordinary class because now I have two classes which works independently.

A: If you want to go on another page, you have to load the game scene.
Look at Scene class in JavaDoc.
Once you have your scene, you just have to add an ActionEvent to your button that will display your page.


text:
Q: Hello Guys I am new in joomla and I want to display search module in header using code Hello I am new in Joomla and I need help
I just want to display my new module into my header.php file I try with

but I don't see any search form in my header. Can anyone help me step by step thanks in advance
Note: create new module from my Joomla admin using default search module new module name = Header Search Module

A: You need to use <jdoc:include type="modules" name="your-position-name" /> in the file you want to display that module. Have you tried this?


text:
Q: Cannot getting object with MEF I have three Assemblies

*

*AssemblyX contains Interface IContext

*AssemblyY contains class Context which implements IContext

*AssemblyZ is the Client which uses Context and should register it to MEF, that IContext can be used from another Classes (in other Assemblies)

My Problem is now to register Context in MEF, that other instances can get it with IContext.
I have attached the Attribute [Export(typeof(IContext))] to Context. But when I now do this.Container.GetExportedValue<IContext>() I get a ImportCardinalityMismatchException.
The Constructor of Context is defined as follows
    [ImportingConstructor]
    public Context(IEventAggregator eventAggregator) { ... }

When I do this.Container.GetExportedValue<IEventAggregator>() for Testing to resolve the IEventAggregator, this is working.
Can somebody help me, what I am doing wrong? - Does I have to attach somewhere the AssemblyX and/or AssemblyY?
Thanks.
Thomas

A: To resolve IContext(as Context from the assemblyY), the Container has to be aware of AssemblyY(that is, about all composable parts from it). In order to it, you should use the appropriate catalog. Or in case if AssemblyY is loaded on demand, it should be loaded before the Context is used.

A: Are all three of the assemblies in the catalog MEF is using?
If that's not the issue, have a look at my blog post on How to Debug and Diagnose MEF failures.


text:
Q: Issue with XPATH in Selenium and Python I am trying to automate some components of service-now. Most everything I am doing is working with the exception of the below.
For the below snippet from the site.
    <select aria-required="true"
                    aria-labelledby="label.cmdb_ci_netgear.u_criticality"
                    ng-non-bindable="true" name="cmdb_ci_netgear.u_criticality"
                    id="cmdb_ci_netgear.u_criticality"
                    onchange="onChange('cmdb_ci_netgear.u_criticality');" style="; "
                    class="form-control" mandatory="true" aria-readonly="false">
        <option value="" role="option">-- None --</option>
        <option value="Level_1" role="option">Level 1</option>
        <option value="Level_2" role="option">Level 2</option>
        <option value="Level_3" role="option">Level 3</option>
        <option value="Level_4" role="option">Level 4</option>
        <option value="Level_5" role="option">Level 5</option>
        <option value="Level_6" role="option">Level 6</option>
        <option value="0" role="option">0</option>
        <option value="Not_Agreed" role="option">Not Agreed</option>
        <option value="level 1" role="option">level 1</option>
        <option value="1" role="option">1</option>
        <option value="3843" role="option">3843</option>
    </select>

If I inspect the HTML and copy the XPATH for the Level_(1-6) options I get the below relationship.
    code =      <option value="Level_1" role="option">Level 1</option>
    xpath =     //*[@id="cmdb_ci_netgear.u_criticality"]/option[2]

    code =      <option value="Level_2" role="option">Level 2</option>
    xpath =     //*[@id="cmdb_ci_netgear.u_criticality"]/option[3]

    code =      <option value="Level_3" role="option">Level 3</option>
    xpath =     //*[@id="cmdb_ci_netgear.u_criticality"]/option[4]

    code =      <option value="Level_4" role="option">Level 4</option>
    xpath =     //*[@id="cmdb_ci_netgear.u_criticality"]/option[5]

    code =      <option value="Level_5" role="option">Level 5</option>
    xpath =     //*[@id="cmdb_ci_netgear.u_criticality"]/option[6]

    code =      <option value="Level_6" role="option">Level 6</option>
    xpath =     //*[@id="cmdb_ci_netgear.u_criticality"]/option[7]

This is the code that I am running through to match the stored value from elsewhere to update the respective XPath
def CI_Create(self,ci_id,Catols):
    self.CI_field_excludes = ['install_status','u_visible_to', 'discovery_source','device_type','u_environment']
    self.ci_ids = ci_id
    self.Catol = Catols
    self.browser.get("https://rttmstest.service-now.com/cmdb_ci_netgear.do")
    sleep(5)
    for i in self.Catol:
        sleep(5)
        print('processing '+ i)
        if i == 'u_criticality':
            print('criticality text is ' + self.Catol['u_criticality'][1])
            if self.Catol[i][1] == 'Level_1':
                print('xxx - process criticality as Level_1')
                self.browser.find_element_by_xpath('//*[@id="cmdb_ci_netgear.u_criticality"]/option[2]').click()
            elif self.Catol[i][1] == 'Level_2':
                print('xxx - process criticality as Level_2')
                self.browser.find_element_by_xpath('//*[@id="cmdb_ci_netgear.u_criticality"]/option[3]').click()
            elif self.Catol[i][1] == 'Level_3':
                print('xxx - process criticality as Level_3')
                self.browser.find_element_by_xpath('//*[@id="cmdb_ci_netgear.u_criticality"]/option[4]').click()
            elif self.Catol[i][1] == 'Level_4':
                print('xxx - process criticality as Level_4')
                self.browser.find_element_by_xpath('//*[@id="cmdb_ci_netgear.u_criticality"]/option[5]').click()
            elif self.Catol[i][1] == 'Level_5':
                print('xxx - process criticality as Level_5')
                self.browser.find_element_by_xpath('//*[@id="cmdb_ci_netgear.u_criticality"]/option[6]').click()
            elif self.Catol[i][1] == 'Level_6':
                print('xxx - process criticality as Level_6')
                self.browser.find_element_by_xpath('//*[@id="cmdb_ci_netgear.u_criticality"]/option[7]').click()
            else:
                print('CRITICAL Failure to select criticality')
        if i in self.CI_field_excludes:
            print('excluding '+i)
            if i == 'discovery_source':
                print('processing lower '+i)
                self.browser.find_element_by_xpath('//*[@id="cmdb_ci_netgear.discovery_source"]/option[3]').click()
            else:
                continue
        else:
            print('processed under else '+i)
            self.browser.find_element_by_xpath(self.Catol[i][0]).send_keys(self.Catol[i][1])
    # self.browser.find_element_by_xpath(device_save_modification).click()
    sleep(5)
    return

All the prints and sleeps are me trying to gain sanity to why the selection is off.
Below is a cut down version of what is being called with self.catol
    CMDB_CAT = {'name': ['//*[@id="cmdb_ci_netgear.name"]', 'somename'],
    'u_managed_b': ['//*[@id="sys_display.cmdb_ci_netgear.u_managed_by"]', 'IT'],
    'u_common_name' : ['//*[@id="cmdb_ci_netgear.u_common_name"]', 'somecommonname'],
    'u_visible_to' : ['//*[@id="cmdb_ci_netgear.u_visible_to"]', 'IT'],
    'install_status' : ['//*[@id="cmdb_ci_netgear.install_status"]', 'Active'],
    'u_criticality' : ['//*[@id="cmdb_ci_netgear.u_criticality"]', 'Level_3'],
    }

If the u_criticality is 'Level_3' it should set the '//*[@id="cmdb_ci_netgear.u_criticality"]/option[4]'.
Everything indicated this is happening, with the exception of the field showing 'Level 4' as the chosen.
Appreciate any help.

A: You can use selenium select class to select the item and get the text value as well.Please check following options.See if this help.
from selenium.webdriver.support.ui import Select
select=Select(driver.find_element_by_id('cmdb_ci_netgear.u_criticality'))
select.select_by_index(3) # First item of the select index is always 0
print(select.first_selected_option.text)

OR
select=Select(driver.find_element_by_id('cmdb_ci_netgear.u_criticality'))
select.select_by_value("Level_3")
print(select.first_selected_option.text)

OR
element = driver.find_element_by_xpath("//select[@id='cmdb_ci_netgear.u_criticality']")
all_options = element.find_elements_by_tag_name("option")
for option in all_options:
    print("Value is: %s" % option.get_attribute("value"))
    option.click()


text: Q: is it possible to get line number of the code from IntelliJ IDEA a SunAwtFrame? I was able to get the line number from some other editors by using autohotkey command A_CaretX and A_CaretY. But not from IntelliJ IDEA a SunAwtFrame. Is there a way to do it? (BTW i want use it inside: https://github.com/sl5net/Magnifier )


text:
Q: How to scan a symbol from the screen in C++ or Java? I want to create a program which must be able to scan symbols from the screen. More precisely I am thinking of a program which reads the cards from the tables in some Poker Software.
Now my question is how would I go about implementing this. Is this doable in Java or C++ or would I use some scripting language for this purpose? And how should I think about the scanning routine? How can the cards be read? Both the symbol and the number of the card must be registered somehow. What method should I use for this?
Hope I can get some good suggestions so I know how I could get started.


text:
Q: Bulk insert XML data into SQL Server database I am working on backup and restore selective data from SQL Server. I am using the following solution:
export multiple tables from mssql to xml
and create a xml with the data I want. How can I create now a function to restore these data  into a SQL Server database?

A: Use SqlBulkCopy, you can load your data in datatable and then using SqlBulkCopy you can insert it in the table.
SqlBulkCopy

Lets you efficiently bulk load a SQL Server table with data from
  another source.

and

The SqlBulkCopy class can be used to write data only to SQL Server
  tables. However, the data source is not limited to SQL Server; any
  data source can be used, as long as the data can be loaded to a
  DataTable instance or read with a IDataReader instance.

A: The easiest way to achieve this is to use Integration Services and CSV files. Xml is too verbose and increase the amount of data needed.


text:
Q: Calling cider-refresh shows "Don't know how to make a localized variable an alias" I'm using Emacs 25 and CIDER 0.18.0.
I'm using cider-connect to attach to a running nREPL process. After connecting, when trying to call cider-refresh, it responds with "Don't know how to make a localized variable an alias".
I've tried debugging by setting Emacs to trace the function, and by looking at the byte-code compile buffers.
Loads of posts on the net refer to using cider-refresh so I'm fairly sure it should work.
How can I identify and fix this problem?

A: In CIDER version 0.18.0, the cider-rename function was renamed to cider-ns-rename. The code defines an alias for the old function that points to the new function.
The project I'm working on had a .dir-locals.el file (as well as my .emacs file) containing code that hooks to the old function name:
((nil . ((cider-refresh-before-fn . "integrant.repl/suspend")
         (cider-refresh-after-fn . "integrant.repl/resume"))))

Because these refer to cider-refresh (which is now an alias) instead of cider-ns-refresh, calling the function fails with the error message mentioned above.
Modifying .dir-locals.el and .emacs to refer to the new function (eg. cider-ns-refresh-before-fn) fixed the problem.