undefined variable company in zendframework 3

Question: undefined variable company
undefined variable i m getting error
    public function addPolicyAction()
    {
        if ($this->sessionContainer->empId == "")
            {
            return $this->redirect()->toRoute('admin_user_login');
            }
        $ouCode = $this->sessionContainer->ouCode;
        $langCode = $this->sessionContainer->langCode;
        $empId = $this->sessionContainer->empId;
 $arrLabel = array('company_policy','pdid','pdname','file_name','active');
        $commonTransalationLabel = $this->commonTranslation->getCommonTransactionInformation($arrLabel, $langCode);
        $companyPolicyForm = new CompanyPolicyForm($commonTransalationLabel);
         if ($this->getRequest()->isPost()) {
            //  $data = $this->params()->fromPost();
            $request = $this->getRequest();
            $data = array_merge_recursive(
                    $request->getPost()->toArray(), $request->getFiles()->toArray()
            );
            $data['ouCode'] = $ouCode;
            $data['langCode'] = $langCode;
            $companyPolicyForm->setData($data);

            $chkValidate = $this->hrCompanypolicy->findBy([
                'ouCode' => $this->sessionContainer->ouCode,
                'langCode' => $this->sessionContainer->langCode
            ]);

            if ($companyPolicyForm->isValid()) {
               $data = $companyPolicyForm->getData();

               if(isset($_POST['Submit'])){
               $name = $_FILES['fileName']['name'];
               $target_dir = 'public/media/policy_photos/';
               $target_file = $target_dir . basename($_FILES["fileName"]["name"]);
               $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
               $extensions_arr = array("jpg","jpeg","png","gif");
               if( in_array($imageFileType,$extensions_arr) ){
              move_uploaded_file($_FILES['fileName']['tmp_name'],$target_dir.$name);
              }
               }
$company = $this->companyPolicyManager->add($data,$ouCode, $langCode,$empId);
$cpData = $this->companyPolicyManager->getcpDataBycpId($data,$ouCode,$langCode);
$companyPolicyForm->buildCompanyPolicyData($cpData);
$this->flashMessenger()->addMessage($commonTransalationLabel['success_message']);

            }
           }

        return new ViewModel([
            'form' => $company,
            'companypolicydata' =>  $cpData,
            'label' => $commonTransalationLabel,
            'form' => $companyPolicyForm,
            'flashMessages' => $this->flashMessenger()->getMessages()
        ]);
    }

i want to remove undefined variable in zendframework 3
i m using zendframework 3 and getting undefined variable in zendframework 3  what is the issue in the code ?
How to defined a variable in zendframework 3 i want to solve the issue
Comment: Could you fix your code & question please? Unreadable.
Answer: Problem is that you're using the $company variable in your return new ViewModel statement, but you only create the variable when the entire form is valid.
Instead of what you're doing, make sure that you provide a Form instance (whichever you need, e.g. CompanyForm) to your controller via the Factory. Then have your function along the lines like below (I've removed some error checking):
public function editAction()
{
    $id = $this->params()->fromRoute('id', null);

    /** @var Company $entity */
    $entity = $this->getObjectManager()->getRepository(Company::class)->find($id);

    /** @var CompanyForm $form */
    $form = $this->getForm();
    $form->bind($entity);

    /** @var Request $request */
    $request = $this->getRequest();
    if ($request->isPost()) {
        $form->setData($request->getPost());

        if ($form->isValid()) {
            /** @var Company $entity */
            $entity = $form->getObject();

            $this->getObjectManager()->persist($entity);

            try {
                $this->getObjectManager()->flush();
            } catch (Exception $e) {

                throw new Exception('Could not save. Error was thrown, details: ', $e->getMessage());
            }

            return $this->redirectToRoute('companies/view', ['id' => $entity->getId()]);
        }
    }

    return [
        'form' => $form,
    ];
}


MS SAPI 5.1 issue with C++

Question: I am using MS Speech API 5.1 with mingw compiler. I don't have VS hence but I was able to compile the code with c::b.
The code snippet is below:
#include <sapi.h>

int main(int argc, char* argv[])
{
    ISpVoice * pVoice = NULL;

    if (FAILED(::CoInitialize(NULL)))
        return FALSE;

    HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
    if( SUCCEEDED( hr ) )
    {
        hr = pVoice->Speak(L"Hello world", 0, NULL);
        pVoice->Release();
        pVoice = NULL;
    }

    ::CoUninitialize();
    return TRUE;
}

When I execute I found
hr = pVoice->Speak(L"Hello world", 0, NULL);

returning NULL. After looking around for a while, I ran the example TTSApp.exe from the MS SAPI folder. By default the voice was selected as "Microsoft Marry". When I type a text and click Start, no speech sound is produce and I got "Speak error". When I changed the voice to "Microsoft Anna - English (United States)", it worked.
I do not know if I am thinking correct, but is the code of mine also failing because of a wrong/default voice selection ("Microsoft Marry")? Is there any way I can change the voice to "Microsoft Anna - English (United States)" for testing?
I need you help here. Can you help me get the SAPI working fro the above code?
Thanks!
Comment: GetVoices() returns the available ones
Comment: @AlexK. Thanks. Can you give me an example code showing how to use it? Not just display the voice but also to change the voice. Also do you think the above issue could be due to voice selection? Thanks.
Answer: Since this is a microsoft specific question.
I use some vb mixed within some system() calls it results in much simpler code.
I haven't cleaned it up, but it works well
int say(std::string s)
{

string part1content;
string part2content;
string word,complete;
const char * temp2="WScript.exe Scrpt.vbs";
const char * temp="Scrpt.vbs";

string pat1=(
"\'By Timbo\n\n\
Const SVSFlagsAsync = 1\n\
const SVSFPurgeBeforeSpeak =2\n\n\
Dim Speech\n\
Dim FSO\n\n\
CreateObjects\n\
Main\n\
DestroyObjects\n\
Quit\n\n\
Sub Main\n\
        Dim sText\n\n\
        sText = (\""
             );
string pat2=
(
"\")\n\
    Speech.rate = 0.05\n\
        If sText <> \"\" Then\n\
                SpeakText sText\n\n\
        End If\n\
End Sub\n\n\
Sub SpeakText(sText)\n\
        On Error Resume Next\n\
        Speech.Speak sText, SVSFlagsAsync + SVSFPurgeBeforeSpeak\n\
        Do\n\
                Sleep 200\n\
        Loop Until Speech.WaitUntilDone(10)\n\
End Sub\n\n\
Sub StopSpeaking()\n\
        On Error Resume Next\n\
        Speech.Speak vbNullString, SVSFPurgeBeforeSpeak\n\
        Set Speech = Nothing\n\
End Sub\n\n\
Sub CreateObjects\n\
        Set Speech = CreateObject(\"SAPI.SpVoice\")\n\
        Set FSO = CreateObject(\"Scripting.FileSystemObject\")\n\
End Sub\n\n\
Sub DestroyObjects\n\
        Set Speech = Nothing\n\
        Set FSO = Nothing\n\
End Sub\n\n\
Sub Sleep(nTimeout)\n\
        WScript.Sleep nTimeout\n\
End Sub\n\n\
Sub Quit\n\
        WScript.Quit\n\
End Sub\n\n\
"

);

    /*Will say string s*/

    complete=pat1+s+pat2;

    ofstream myfile;
    myfile.open (temp);
    myfile << complete;
    myfile.close();
    system(temp2);
    complete.clear();
    s.clear();
}

For different voice Change pat2 with
string pat2=
(
"\")\n\
    Speech.rate = 0.05\n\
        If sText <> \"\" Then\n\
                SpeakText sText\n\n\
        End If\n\
End Sub\n\n\
Sub SpeakText(sText)\n\
        On Error Resume Next\n\
        Speech.Speak sText, SVSFlagsAsync + SVSFPurgeBeforeSpeak\n\
        Do\n\
                Sleep 200\n\
        Loop Until Speech.WaitUntilDone(10)\n\
End Sub\n\n\
Sub StopSpeaking()\n\
        On Error Resume Next\n\
        Speech.Speak vbNullString, SVSFPurgeBeforeSpeak\n\
        Set Speech = Nothing\n\
End Sub\n\n\
Sub CreateObjects\n\
        Set Speech = CreateObject(\"SAPI.SpVoice\")\n\
        with Speech \n\
            Set .voice = .getvoices.item(1)\n\
            .Volume = 100\n\
            .Rate = 4\n\
        end with\n\
        Set FSO = CreateObject(\"Scripting.FileSystemObject\")\n\
End Sub\n\n\
Sub DestroyObjects\n\
        Set Speech = Nothing\n\
        Set FSO = Nothing\n\
End Sub\n\n\
Sub Sleep(nTimeout)\n\
        WScript.Sleep nTimeout\n\
End Sub\n\n\
Sub Quit\n\
        WScript.Quit\n\
End Sub\n\n\
"
);

Then you can just use it simply by calling say("This is a test");
For more control you can use pipes instead of sytem() , this will enable you to kill the vbscript process if you want to stop it.

MS SAPI 5.1 issue with C++


Unable to add a webview to my android app

Question: This is my main.xml file.
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Hello World, MainActivity"
    />
 <WebView
        android:id="@+id/webView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/urlContainer" />
</LinearLayout>

And this is my java file.
package szdf.asdf;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends Activity
{
    private WebView webView;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        webView = (WebView) findViewById(R.id.webView);
                String customHtml = "
Hello, WebView
" +
                               "
Heading 1

This is a sample paragraph.
" +
                               "";
        webView.loadData(customHtml, "text/html", "UTF-8");
    }
}

I am trying to add a webview to my app. But it compiles with the error
error: Error: No resource found that matches the given name (at 'layout_below' with value '@id/urlContainer').
Can someone tell me what is wrong with my code ?
Answer: You're referencing an object with an ID that doesn't exist on the android:layout_below attribute. Remove the line or add a item with the ID @id/urlContainer.
Answer: android:layout_below="@id/urlContainer" />

You haven't resource with this ID, just delete it :)
Answer: There is no resource container with this id urlContainer. SO remove this line:
  android:layout_below="@id/urlContainer" />


iOS Splash Page while Loading Data

Question: I am trying to write an app that displays a simple logo/splash page while the app retrieves some data. I cannot seem to find a tutorial anywhere.
I have a "MainWindow.xib" file that will have my splash page, and I'm setting that as my "Main Interface" in my Info.plist, however, I cannot seem to see how to replace that page with a .xib that contains a UINavigationController. I thought I would just create a new UIController, that had a UINavigationController and in my .xib I'll drag in a Navigation Controller and set all my information, but it's giving me real fits.
So, I figured I would have a UIController that I would "alloc" and "init" with my second .xib that contains all my navigation.
myMainController = [[UIController alloc] initWithNibName:@"MainNavController":nil];

in "MainNavController.xib", I've dragged in a Navigation Controller, but I don't know what to connect it to????
I'm sure I'm going down the wrong, path; but I cannot find a decent tutorial for this.
Can someone give direction or link to a decent tutorial?
Thanks.
Answer: Are you ever actually adding the new controller to your existing view?  If not, something like:
[self.view addSubview:myMainController.view];

should do it for you.  A better alternative is likely to be:
self.window.rootViewController = myMainController;

But I'm fairly new to this and maybe I've missed something ...
Comment: @El Guapo I almost never (ok, really, never) use the interface builder, so I guess I'm a bit confused as to what you're trying to do or maybe when you're trying to do it (I know, I know, I should learn more about using interface builder).  But, when are you having the problem?  You described it as waiting for the data to load, so I assumed that you were creating the the "myMainViewController" once the data had finished loading? no?  If so, as soon as you create the controller, assign its view as in my answer above.  Or am I missing something in what you're trying to do?
Comment: Basically... I was going down the path of having a "MainWindow.xib" with a splash page... then I was creating a custom UIViewController that had a nib with a NavigationController, but for some reason switching to the custom UIViewController was not working.
Comment: @El Guapo Without some additional code, I can't understand the problem enough to help.  I think I'd need to see the context around where you are creating the custom uiviewcontroller in the code.
Answer: To display a splash screen while the app is loading you can use Default.png image file.
However, I think your question is how to display another splash screen for a period of time after the app has been loaded.
In you MainWindow.xib keep your window separated from your Navigation Controller. Add your splash screen view with an image to the xib.
Make two outlets: one for slash view, one for Navigation Controller.
IBOutlet UIView* _spashScreenView;
IBOutlet UINavigationController* _navigationController;

In applicationDidFinishLaunching method add your splash screen view to the window.
[_window addSubview:_spashScreenView];
// lay it out

When you are ready to display your navigation controller:
[_spashScreenView removeFromSuperView];
[_window addSubview:_navigationController];

iOS Splash Page while Loading Data


how to close a add new record popup wndow in jquery jtable on saving in mvc?

Question: I have used the jTable plugin of jQuery in my CRUD application. My problem is, when I click on the Add New Record, a confirmation dialog appears in but after filling the details and clicking the Save button the dialog doesn't disappear, but the data is added while i refresh the Jtable..how i can close the popup window?
my View contains

<code>$(document).ready(function () {

    $('#StudentTableContainer').jtable({
        title: 'Employee List',
        paging: true, //Enable paging
        sorting: true, //Enable sorting
        defaultSorting: 'Name ASC',
        //openChildAsAccordion: true, //Enable this line to show child tabes as accordion style
        actions: {
            listAction: '@Url.Action("Details")',
            deleteAction: '@Url.Action("Delete")',
            updateAction: '@Url.Action("Update")',
            createAction: '@Url.Action("Create")'

        },
        recordAdded: function (event, data) {
            $('#StudentTableContainer').jtable('reload');
        },
        fields: {
          UserId: {
                key: true,
                create: false,
                edit: false,
                list: false
            },
            FirstName: {
                title: 'FirstName',
                width: '10%'
            },
          LastName: {
               title: 'LastName',
                width: '10%'
          },
          EMail: {
              title:'EMail',
                width: '10%'
          },
          Address: {
              title: 'Address',
                width: '10%'
          },
          PhoneNo: {
              title:'PhoneNo',
                width: '10%'
          },
          Company: {
              title:'Company',
              width:'10%'
          },
          Designation: {
              title:'Designation',
              width:'10%'
          }
      }
  });

  //Load person list from server
  $('#StudentTableContainer').jtable('load');
</code>
and my controller has Create method contains
[HttpPost]
   public JsonResult Create(UserList userList)
        {
<code>        try
        {
            userRepository.InsertUser(userList);
            return Json(new { Result = "OK" });

        }

        catch (Exception exception)
        {
            return Json(new { Result = "ERROR", Message = exception.Message });
        }
    }
</code>
Answer: The jtable expects the inserted data in the return json.
something like
{"Result":"OK","Record":[{"UserId":"169","FirstName":"Attic","LastName":"Server","EMail":"firstname.lastname@example.com","Address":"root","PhoneNo":"12121212","Company":"pass","Designation":"Manager"}]}
you can install Firebug
and Check if you getting this error
jTable ERROR: Server must return the created Record object.
Answer: I think I had the same issue as you. When trying to add a new record "loading data" .gif never dissapear even when Json message is receive. Two possible solutions that worked for me:
(The bad one) In jtable.js => search for  _reloadTable function and comment line self._showBusy(self.options.messages.loadingMessage, self.options.loadingAnimationDelay);
(The good one) Try to use the last version of JTable. I'm testing it now, and the gif never appears and everything works perfectly
Answer: You must to return the added record to the json response.
I don't know for other languages, but for PHP it looks like:
<code>$json['Result'] = "OK";
$json['Record'] = $lastInsertedRecord; // query the last insert id from db
print json_encode($json);
</code>
Answer: Record must be an object, not array of objects. you must check json response from browser.
{"Result":"OK","Record":[{"id":"2","item_id":"6","marked_number":"MN567","p_model":"MDL","p_number":"PNUM","claimed_defects":"CLDEF"}]}
It must be this:
{"Result":"OK","Record":{"id":"2","item_id":"6","marked_number":"MN567","p_model":"MDL","p_number":"PNUM","claimed_defects":"CLDEF"}}
Plus another issue, I was dealing with this problem for a few days and here it is solved in ONE letter (Record vs. Records)


Why do we use GLM?

Question: I'm trying to justify using of GLM model in my project instead of a simple linear regression. A lot of sources that I've seen contain the statement that "GLM allow us to build regression models for response variables that are not normally distributed". I can't understand what that is supposed to mean since we don't make any assumptions about variable distribution. Could you, please, explain  why it's often more appropriate (theoretically)  to use GLM if your response variable is,  say, count.
Comment: OLS does not needs the outcome to be normal, it does, however, assume the *residual* to be normal, or the standard error can be biased, leading to a wrong p-value. Some OLS models using count outcome tend to have non-normal residual (esp. when counts are low or zeroes are abundant,) and hence using Poisson family to model the error is a better choice.
Comment: I think your question is directing people to give you an introduction to Poisson regression. Why don't you revise your question and really tell us what you are trying to justify (in the first sentence?) Is that count variable you're working on?
Comment: The most popular answer to that question also gives the same answer - a variable is assumed to be normally distributed. As far as I know it's not necessary for fitting the model. And, yeah, my variable is count, but I would like to know why not-normal variables don't often work good enough with simple linear regression
Comment: Is the only consequence the wrong p-value? Doesn't it affect fit accuracy?
Answer: You do make assumptions about response variable distribution in normal linear models. Normal linear models can be written as
$$y_i = x_i'\beta + \varepsilon_i,\qquad \varepsilon_i\sim\mathcal{N}(0,\sigma^2)$$
but that means that $y_i$ is a linear transformation of a normally distributed random variable, thus its distribution is
$$y_i\sim\mathcal{N}(x_i'\beta,\sigma^2)$$
BTW, it is this normal distribution that makes $t$- and $F$-tests possible: $\hat\beta$ is normally distributed because it is a linear transformation of $y$, $\hat\beta=(X'X)^{-1}X'y$.
Further, that means that $y_i$ is continuous and can be positive, zero, or negative.
When you have a binary response variable, it can't be normally distributed. You are actually interested in the probability $P(y=1)$ vs $P(y=0)$. You could try a linear probability model, i.e.
$$P(y=1\mid x)=p(x)=x'\beta$$
where
$$\begin{align}E(y\mid x)&=1\cdot p(x)+0\cdot(1-p(x))=p(x)=x'\beta\\
V(y\mid x) &= p(x)(1-p(x))=x'\beta(1-x'\beta)\end{align}$$
but

the error is not normally distributed, since it can just take two vales:
$$\varepsilon=y-x'\beta\quad\Rightarrow\quad
\varepsilon=\begin{cases} 1-x'\beta & \text{if } y=1\\-x'\beta & \text{if } y=0\end{cases}$$
the error is not homoscedastic:
$$V(\varepsilon)=E(\varepsilon^2)=x'\beta(1-x'\beta)$$
thus the error variance depends on $x$
$E(y\mid x)=p(x)$ is a probability, thus it must be greater than 0 and lesser than 1, but the linear predictor $E(y\mid x)=x'\beta$ can take any real value; you could try:
$$p(x)=\begin{cases} 0 & \text{if } x'\beta<0 \\
x'\beta & \text{if } 0\le x'\beta \le 1 \\
1 & \text{if } x'\beta > 1 \end{cases}$$
but the graph of $p(x)$ would be a broken line. How could you interpret it? What could its vertices mean? (BTW: interpretation is even more important than p-values: high p-values which make sense are better than low p-values which do not make sense.)

This is why one looks for a smooth function which maps $[0,1]$ to $\mathbb{R}$:
$$x'\beta=g(E(y\mid x))$$
and you get:
$$P(y=1\mid x)=G(x'\beta),\qquad G(x'\beta)=g^{-1}(x'\beta)$$
In logit models,
$$g(x)=\ln\left(\frac{x}{1-x}\right),\qquad g^{-1}(x)=\frac{1}{1+e^{-x}}$$
where $g^{-1}$ is the cdf of a logistic random variable.
When you have to model count data, a natural (not always perfect) solution is:
$$P(y=k)=\frac{e^{-\theta}\theta^k}{k!}\quad\text{i.e.}\quad y\sim\text{Poisson}(\theta)$$
so that
$$E(y\mid x)=\theta=\exp(x'\beta)$$
thus $E(y\mid x) > 0$ even if $x'\beta < 0$. Other solutions are zero-inflated or negative-binomial models.
Comment: You are welcome. And generalized linear models are a fascinating topic. I'd recommend [Gelman & Hill](http://www.stat.columbia.edu/~gelman/arm/) for an accessible introduction, then [Agresti](http://www.stat.ufl.edu/~aa/cda/cda.html) or [McCullagh & Nelder](http://www.amazon.com/Generalized-Edition-Monographs-Statistics-Probability/dp/0412317605) for in-depth analysis.

Why do we use GLM?


Drupal 6 Add Webform Programmatically

Question: I'm trying to add a new component or populate an existing hidden component on a web form programmatically.  I found this:
http://drupalcontrib.org/api/drupal/contributions!webform!webform.module/function/_webform_client_form_add_component/6
However I have not found any hooks, which would be the preferred way to do this.  I'm essentially just checking to see if there is a hook or how to access that function in a custom module if no hook exists.
Answer: A webform is simply a node so the rough process of doing this would be to node_load() your particular node, add your components array to the $node->components[] array and then execute a node_save(). There is some documentation here that fleshes out how to programmatically add a webform, your code would look something like this:
<code>$node = node_load(YOUR NODE ID);
$components = $components = array(); #YOUR COMPONENTS ARRAY
$node->webform = array(
      'components' => $components,
);
node_save($node);
</code>

Drupal 6 Add Webform Programmatically


Getting Content is not allowed in prolog when running in Java

Question: I am facing Content is not allowed in prolog exception when I run my xxx.jmx file from Java (Jmeter 5.0).
I tested the jmx in the GUI mode and everything works fine and in the Java I am just following the standard way to call the jmx file and execute it.
The jmx just have some normal stuff. Sending HTTP request and validate the expected and received XML (I am using this snipped to validate):
import org.apache.commons.io.FileUtils

expect = FileUtils.readFileToString(new File('some_path'))

XmlParser parser = new XmlParser()

expectedXML = new XmlSlurper().parseText(expect)

actualXML = new XmlSlurper().parseText(prev.getResponseDataAsString())

if (expectedXML != actualXML) {
    AssertionResult.setFailure(true)
    AssertionResult.setFailureMessage('Mismatch between expected and actual XML \n'+ prev.getResponseDataAsString())

and the stack trace:
2018/10/24 15:18:03,386 12675 [ERROR ] [Thread Group 1-1] (JSR223Assertion.java:52) – Problem in JSR223 script: Validate resposne
javax.script.ScriptException: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
    at org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:320)
    at org.codehaus.groovy.jsr223.GroovyCompiledScript.eval(GroovyCompiledScript.java:72)
    at javax.script.CompiledScript.eval(CompiledScript.java:92)
    at org.apache.jmeter.util.JSR223TestElement.processFileOrScript(JSR223TestElement.java:221)
    at org.apache.jmeter.assertions.JSR223Assertion.getResult(JSR223Assertion.java:49)
    at org.apache.jmeter.threads.JMeterThread.processAssertion(JMeterThread.java:901)
    at org.apache.jmeter.threads.JMeterThread.checkAssertions(JMeterThread.java:892)
    at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:565)
    at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:486)
    at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:253)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
    at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
    at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
    at groovy.util.XmlSlurper.parse(XmlSlurper.java:207)
    at groovy.util.XmlSlurper.parse(XmlSlurper.java:260)
    at groovy.util.XmlSlurper.parseText(XmlSlurper.java:286)
    at groovy.util.XmlSlurper$parseText.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at Script1.run(Script1.groovy:9)
    at org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:317)
    ... 10 more

UPDATE 1:
The problem of using Response Assertion is it cannot ignore the space or tab. So if the format is not exactly the same when I use equal will always fail. Any ideas how to ignore these things by using Response Assertion?
UPDATE 2:
I found out that the issue is not related to the BOM. Is becasue if I run the jmx from my Java application:
 prev.getResponseDataAsString()

above function always return:
${__FileToString(${inputFilePath},,)}

but not the actual response. This function is come from the body data of the HTTP Request sampler!!!!!! If I give the acutal body there then I am able to run the jmx...... Any idea how to deal with this dynamic body data?
Comment: Show line 1 of the XML received
Answer: It might be the case your "expected" XML file contains BOM and it causes your code failure.
BOM is basically 3 first bytes so you can remove them using code like:
def expect = FileUtils.readFileToString(new File('some_path')).getBytes().flatten()

1.upto(3) {
    expect.remove(0)
}

XmlParser parser = new XmlParser()

def expectedXML = parser.parseText(new String(expect.toArray(new Byte[0])))

The rest of your code should work fine.
Check out The Groovy Templates Cheat Sheet for JMeter article to learn more Groovy tips and tricks.

Also be informed that in majority of cases it's easier to use Response Assertion or when it comes to XML - XPath Assertion, Java code will work faster than Groovy in any case.
Comment: You need to add [JMeter_Functions.jar](https://mvnrepository.com/artifact/org.apache.jmeter/ApacheJMeter_functions) to your project dependencies/classpath.
Comment: the problem of using Response Assertion is it cannot ignore the space or tab. So if the format is not exactly same when I use equal will always fail
Comment: the reason for getting this exception is because prev.getResponseDataAsString() always return ${__FileToString(${inputFilePath},,)} instead of the actual response when I run from my Java application.  Nothing releated to BOM. Any idea of this? I guess I am missing some Jmeter dependencies in my pom.


Connecting Audio Technica Pro 70 to a laptop for live recording

Question: I'm looking for a nice Lavalier mic to buy mainly concerned about audio quality. I've currently set eyes on this one:
http://www.amazon.com/Audio-Technica-PRO70-Condenser-Instrument-Microphone/dp/B001CITVNQ/ref=cm_cr_pr_product_top?ie=UTF8
It has an XLR cable output and my question is the following:
If I get an XLR to standard stereo cable and hook this mic directly to my laptop's mic recording input, I should be able to capture the sound from the mic via some software in the computer in real time and record it, right? And that without losing from the quality of the sound, of course.
And a bonus question - description says it operates on phantom power as well as battery so if I connect in the way described above, am I going to need the battery or not?
Comment: You can't get real-time result, it may have lag for few seconds. Try search "ASIO4ALL" to fix this. I prefer to get a cheap sound card to deal with it better.
Comment: I do actually have a quite nice sound card which uses ASIO driver but what I'm trying to do is quite the opposite - get rid of it so I can carry less equipment with me around and plug in the mic straight to the laptop instead of additional piece of hardware. What would cause the lag though? Aren't you supposed to be able to use such a mic for let's say real time Skype conversations or something similar?
Answer: Microphones produce a very small signal that needs to be amplified, so you'll need a preamp. A computer mic typically includes that preamp (you don't notice it, it's hidden somewhere inside), but professional microphones don't (I checked that model just in case, it doesn't). Unless your computer mic input has a preamp (it most likely doesn't), you won't be able to implement that setup. At best you might be able to capture some very low amplitude audio, with a lot of noise. Horrible quality.
What you need is an audio interface (aka sound card) with an XLR input (which will have a preamp for that input). You could also amplify the mic with other device (mixing console, stand-alone preamp, vocal amplifier, etc) and then connect that device output to your computer, but the included internal sound cards tend to be bad and noisy, so if you are investing in something invest in an audio interface and not another type of amplifying device.
You will need batteries if you use your described setup (which again, I strongly recommend against). Chances are that your computer doesn't have phantom power, which is what powers a condenser mic without batteries. You need to look for an audio interface with phantom power (or a mixing console, or a stand-alone preamp, or similar, will also provide the phantom power functionality, but in your specific case I really recommend you an audio interface instead).
Comment: Thank you for the feedback. As I mentioned in my comments above, I do have an audio interface and in fact I was able to set the whole scenario up using it but I'm currently trying to find a way to hook up the mic directly to the laptop so I don't have to carry an addition piece of equipment around. Can you suggest an idea how I can do that?
Comment: @mmvsbg You won't get a usable signal without an extra piece of equipment. I'm assuming your computer is a laptop, so installing an internal sound card with XLR and phantom power options should be out of the question (unless you manage to find a way to do it). But it still would be an internal sound card, close to all your computer mechanisms, so there's a big chance it will be noisy. Not worth your time and money it in my opinion.
Comment: @mmvsbg What you can do is get a very small audio interface like the Apogee Duet, Apogee One, Blue Microphones Icicle, ART XConnect, Alesis MicLink, Shure X2u, etc. Just be very careful, most of those micro audio interfaces are 16 bits only, and I strongly recommend you an interface that supports 24 bits (and always record at 24 bits). Check http://www.sweetwater.com/c695--USB_Audio_Interfaces to see a very wide array of options. In that page you can also ask questions to the shop's representatives, abuse that feature. You can also get a portable recorder (no laptop), like the Zoom H4N.
Comment: Thank you, I'll definitely see how much and how far I can abuse the Sweetwater representatives. Unfortunately, I can't get rid off the laptop and based on your comments I guess there's no way to walk around the audio interface as well so at this point I'm stuck with this setup. Making the audio interface smaller is a relatively good option but since it's still there and I do have a nice old Focusrite Saffire 6 in my rack that also goes into the not worth the money category. Thanks for the input though, marking this as an answer as it did show me that there's no easy solution to my problem.
Comment: And just to follow up on the answer, what about a mic with build in preamp to directly plug into the laptop without the need of audio interface or that goes a bit to the science fiction genre?
Comment: @mmvsbg If you can find a mic like that of good quality, and you are ok with the quality of the internal sound card of your computer, go for it.
Comment: I'm afraid @Teental is misinformed.  Although some  cheap audio interfaces may be 16-bit only, the Apogee Duet and One are premium-priced units that offer 24 bits and high sample rates.  They also provide phantom power.
The mic input of a laptop computer is generally low quality, suitable only for Skype calls etc.  But if there's a Line In, you could consider a preamp that takes a microphone up to line level as an alternative to an audio interface.   Incidentally, more than 16 bits don't really matter.  There's nothing you're going to point your mic at that needs even 16 bits of dynamic range
Comment: @LaurencePayne I didn't say all of them were 16-bit only. Of course there are exceptions, and high end interfaces will tend to be above the average.
Answer: If you have any thought of audio quality, you will need an interface between microphone and computer.
What's the application?  Maybe you'd be better served by ditching the laptop and using a portable recorder.  The Zoom H4N offers XLR inputs, but maybe the built-in stereo microphones can be positioned to capture what you need?  In that case, the smaller, cheaper H2N might suit.
The AT mic seems to output a balanced mic-level on XLR.  A laptop may have a TRS mini-jack input, offering a type of phantom power (but a different sort to what the AT mic needs) to a headset-type mic.  There may also be a stereo Line In, using a similar connector.  Neither are suitable for direct connection of the AT mic.
Comment: Thank you for your time. Unfortunately, I cannot ditch the laptop as this stage as I'm recording both video and audio. The video camera captures the video and 'on-the-scene' sound and then I'm mixing that in real time through the laptop with a second audio input which serves as additional commentary to the video. I was hoping to find a way to simplify the audio setup by removing the interface and plugging in a mic directly into the laptop but reflecting on the answers and comments here, at this stage, that seems not possible :(
Comment: Actually, you can still ditch the laptop. Position the camera in the best available position for seeing, the recorder in the best for hearing.  No need for cables connecting them together - just stitch their individual recordings together afterwards in a video editor. You may need a few ms delay on the audio if it was appreciably closer to the source than the camera.  Now everything's digital, wild sync. should be perfectly OK.
Comment: That's a good tip, however, I need one audio input from the camera and then another one for the background commentary. The background commentary needs to be far, far away from the camera along with the laptop which is why I'm looking for a solution similar to the one described in the question above. Additionally, there is not post production - it's all recorded live and streamed live, pretty much as doing a live TV broadcast. (And just as a side note, I can do some artificial delay to sync audio with video through the software on the laptop, however, it's highly desirable to avoid that).


Is there a better way to make a user profile tab using a view?

Question: I have created a question node type using CCK and would like to show all of the questions which users create on a tab on their profile page.
The way I have done this feels a little indirect. I have:

Created a view which lists all of a user's questions and made a block to display it.
Configured the block so that it only displays on the right path ("user/*/questions").
Created an entry in hook_menu for this path. Used a page callback which calls a function which creates an empty page (see below).

Is there a more direct way to do this by, e.g., attaching the view directly to the profile page?
The code in hook_menu() is:
$items['user/%/questions'] = array(
  'title'            => 'Your Questions',
  'description'      => 'User Questions',
  'page callback' => 'answers_blank_page',
  'access arguments'  => array('create question content'),
  'type'     => MENU_LOCAL_TASK,
  'weight' => 9,
);

The page callback is simply:
function answers_blank_page () {
  return '';
}

Answer: There isn't any need to use a custom module for this: The Views module already allows you to associate a URL to a view and make the view appears as a menu tab.
The following screenshots are for Views 7.x-3.x-dev, but the settings are present also in previous versions of the module.
Under "Page settings," there are two options: "Path" and "Menu." The screenshots shows the settings used for a view implemented by a third-party module (the Flag module), whose view is shown as menu tab.

Comment: Just wanted to say "thanks" ... while it took a little while for me to get back to this, this solution worked great. (It turns out I even ended up wanting to create a sub-menu and the same set of ideas here worked for using Views built-in capabilities to make that). Much simpler than what I had.
Answer: Create a new page view, and then configure it to provide a menu item, specifically a tab, at path user/%/questions.
Answer: It should work just by creating a page display, setting the path appropriately; no need to do the tricky steps you used.
Edit: you must also specify a menu item for the display.


Loop through folder and applying code to all xlsx

Question: Had a code that was able to apply protect workbook but didn't save after running a different sub routine. I'm trying to apply a macro to all xlsx files in a folder where I'm deleting two sheets and applying a protect workbook. When I run it without the sheet deletion, the code runs but it doesn't apply to any of the files inside the folder.
Sub LoopThroughFilesFolder()
Dim StrFile As String, wb As Workbook, ws As Worksheet
StrFile = Dir("C:\Users\user\Documents\Destroy\*.xlsx*")
Do While Len(StrFile) > 0

    For Each ws In Worksheets
    If ws.Name = "Summary Copying" Or ws.Name = "Sum Totals" Then
        Application.DisplayAlerts = False
        ws.Delete
        Application.DisplayAlerts = True
    End If
    Next

    ProtectBookStructure ThisWorkbook, "password"
    StrFile = Dir
Loop

End Sub
Fixed with this code
 Sub LoopThroughFilesFolder()

   Dim myfile As String
   Dim wb As Workbook, ws As Worksheet

Application.ScreenUpdating = False

    myfile = Dir("C:\Users\user\Documents\Destroy\*.xlsx*")

        Do While myfile <> ""

           Set wb = Workbooks.Open(fileName:=myfile)

            For Each ws In Worksheets
            If ws.Name = "Summary Copying" Or ws.Name = "Sum Totals" Then
                Application.DisplayAlerts = False
                ws.Delete
                Application.DisplayAlerts = True
            End If
            Next

           ProtectBookStructure wb, "password"

        wb.Close savechanges:=True
        myfile = Dir
    Loop

Application.ScreenUpdating = True

End Sub

Comment: You question indicates to me that you are unfamiliar with the way to use workbooks. I'd suggest you to get started [here](https://www.youtube.com/watch?v=Mx7a-uj2sZI) and if you're still stuck you can edit your question to explain what you've tried.
Comment: Just a little tip: If you find a solution you are not supposed to include it in the answer, you can actually post an answer to your own question.
Also, I strongly recommend you get rid of the `ActiveWorkbook` reference in your solution by replacing the `Worksheets` with `wb.Worksheets` in the line `For Each ws In Worksheets`. Also, it is enough to use `"C:\Users\user\Documents\Destroy\*.xlsx"` (No trailing `*`!), unless you want your macro to get stuck on (hypothetical) files like `wb.xlsx.jpg`.
Answer: I recommend you check out the link posted by @DecimalTurn as a comment to your question.
A solution for your problem may look like this:

Sub LoopThroughFilesFolder()
    Dim strFile As String, wb As Workbook, ws As Worksheet
    strFile = Dir("C:\Users\user\Documents\Destroy\*.xlsx")

    Do While Len(strFile) > 0
        'Open the workbooks like this:
        Set wb = Application.Workbooks.Open(strFile, False, False)

        'In the following, use the "wb" variable to do what you want for the
        'opened workbook.
        For Each ws In wb.Worksheets
            If ws.name = "Summary Copying" Or ws.name = "Sum Totals" Then
                Application.DisplayAlerts = False
                ws.DELETE
                Application.DisplayAlerts = True
            End If
        Next
        ProtectBookStructure wb, "password"

        'Save and close
        wb.Close SaveChanges:=True
        strFile = Dir
    Loop
End Sub

This code may still not work depending on how ProtectBookStructure looks like or if any of the workbooks in the folder are already password protected.
Comment: I had it working but testing it again with a new repopulated files in the folder, I get an error with both yours and my code "run-time 1004': Sorry, we couldn't find is it possible it was moved, renamed or deleted? Any possible fix?
Comment: Which line does it fail on? I assume `Set wb = Application.Workbooks.Open(strFile, False, False)`? Look at the variable `strFile` in the watch window and check it the file it tries to open exists.
Comment: Yeah, fails on wb = application.workbooks.open. The variable is true when failing.
Comment: It shouldn't be `True`, it should be equal to some string (a file path)
Comment: Placing wb in the watch window I get the "filename.xlsx" . wb = nothing.
Comment: Hi @ojmayo. But what if you place just `strFile` in the watch window? It's a string variable, it can't be `Nothing`. I recommend you watch [this video](https://youtu.be/Um2JwZfwoFI "YouTube - Master VBA Debugging in 20 Minutes - Excel Macro Mastery (Paul Kelly)") on VBA debugging, I'm sure it'll help you a lot!


How can i fix concatenate tuple (not "list") to tuple

Question: I'm trying to create a minimum reproducible example, while doing so, i came across this error. How can i solve this?
Traceback (most recent call last):
  File "<string>", line 22, in <module>
File "<string>", line 10, in verified
TypeError: can only concatenate tuple (not "list") to tuple

import json

# Python3 program to convert a
# list into a tuple
def convert(list):
    return tuple(list)

def verified(k_signer, sha256, d_signer, addr_from, seed, data, signature):
    hash = (
                           k_signer +
                           tuple(sha256.encode()) +
                           d_signer +
                           tuple() +
                           tuple() +
                           tuple()
                         )
    return hash

data = {'k_signer': [165, 118, 206, 164, 254, 84, 98, 136, 122, 95, 83, 186, 232, 134, 155, 198, 186, 72, 221, 207, 167, 67, 45, 62, 118, 121, 122, 42, 166, 42, 185, 149, 91, 39, 77, 188, 42, 215, 132, 148, 170, 99, 114, 144, 66, 93, 177, 127, 214, 55, 57, 230, 214, 246, 241, 122, 201, 13, 225, 173, 22, 195, 144, 54, 20, 193, 213, 187, 228, 24, 48, 239, 216, 157, 193, 255, 45, 103, 223, 33, 105, 92, 176, 197, 128, 158, 103, 130, 190, 139, 184, 224, 145, 150, 191, 81, 35, 135, 90, 182, 56, 203, 195, 183, 50, 188, 67, 49, 211, 170, 165, 70, 219, 215, 216, 160, 236, 89, 237, 193, 45, 71, 239, 153, 74, 229, 36, 101, 222, 222, 188, 168, 58, 99, 166, 37, 164, 63, 117, 54, 139, 205, 176, 154, 151, 130, 182, 87, 15, 116, 46, 165, 202, 95, 70, 204, 108, 152, 123, 28, 241, 120, 50, 249, 243, 45, 246, 248, 165, 107, 33, 198, 204, 178, 86, 169, 237, 248, 9, 175, 199, 136, 171, 161, 117, 229, 130, 238, 145, 143, 159, 103, 43, 205, 153, 61, 129, 65, 231, 41, 115, 89, 162, 13, 103, 95, 85, 147, 245, 152, 9, 99, 110, 61, 130, 210, 225, 188, 68, 224, 6, 173, 6, 177, 250, 82, 221, 12, 79, 5, 138, 218, 242, 239, 162, 99, 95, 249, 178, 163, 88, 37, 209, 141, 249, 163, 164, 231, 13, 30, 53, 207, 82, 163, 138, 11, 201, 187, 169, 117, 98, 174, 197, 131, 15, 206, 47, 211, 117, 219, 130, 92, 199, 147, 58, 22, 91, 55, 30, 160, 206, 178, 109, 61, 3, 124, 238, 242, 167, 67, 100, 224, 173, 96, 101, 97, 188, 222, 101, 47, 15, 123, 193, 232, 247, 235, 134, 171, 255, 180, 94, 234, 97, 193, 108, 28, 231, 164, 95, 232, 131, 181, 104, 11, 213, 222, 184, 175, 128, 157, 140, 148, 214, 43, 40, 135, 51, 197, 86, 123, 238, 85, 170, 51, 28, 133, 227, 124, 233, 7, 85, 99, 158, 203, 90, 160, 159, 105, 13, 164, 150, 126, 170, 155, 187, 104, 138, 173, 56, 46, 8, 82, 120, 170, 43, 62, 228, 146, 151, 26, 231, 42, 5, 130, 159, 37, 9, 70, 27, 14, 74, 17, 102, 83, 126, 243, 187, 131, 99, 114, 158, 239, 222, 175, 21, 215, 177, 13, 191, 151, 246, 229, 51, 112, 110, 42, 25, 122, 13, 96, 98, 81, 252, 122, 45, 165, 4, 108, 40, 101, 9, 75, 80, 97, 150, 218, 195, 175, 9, 133, 80, 131, 75, 244, 210, 232, 194, 227, 232, 22, 192, 40, 229, 208, 116, 121, 118, 164, 136, 115, 41, 97, 239, 7, 111, 193, 141, 228, 114, 22, 126, 192, 120, 130, 26, 110, 120, 183, 159, 149, 50, 3, 42, 15, 214, 160, 144, 193, 225, 243, 34, 35, 247, 249, 143, 24, 200, 240, 157, 7, 195, 35, 61, 233, 190, 163, 64, 188, 138, 89, 15, 102, 20, 11, 221, 158, 63, 61, 59, 153, 226, 58, 26, 131, 254, 138, 255, 84, 72, 32, 121, 123, 115, 69, 109, 96, 182, 171, 190, 154, 181, 131, 42, 177, 175, 26, 249, 112, 247, 126, 45, 231, 22, 241, 160, 12, 244, 104, 119, 149, 89, 156, 217, 65, 218, 95, 38, 190, 98, 95, 204, 149, 200, 121, 229, 195, 16, 213, 204, 4, 222, 187, 143, 171, 26, 56, 160, 16, 106, 166, 216, 91, 35, 178, 77, 115, 44, 143, 147, 130, 69, 209, 80, 133, 243, 23, 190, 100, 169, 245, 58, 58, 137, 187, 203, 74, 148, 112, 146, 82, 177, 210, 230, 253, 236, 144, 130, 15, 57, 45, 74, 110, 3, 167, 39, 227, 53, 91, 69, 252, 87, 195, 237, 239, 218, 45, 148, 237, 235, 150, 82, 99, 87, 11, 175, 136, 110, 220, 228, 15, 109, 76, 140, 59, 172, 122, 159, 78, 69, 38, 156, 239, 241, 130, 77, 115, 253, 203, 170, 103, 174, 163, 73, 121, 214, 115, 17, 119, 233, 244, 133, 38, 133, 106, 87, 144, 164, 64, 181, 74, 141, 82, 55, 78, 80, 132, 180, 225, 63, 213, 133, 219, 253, 142, 19, 210, 25, 232, 252, 36, 42, 176, 105, 27, 231, 72, 85, 80, 173, 229, 85, 90, 96, 102, 143, 152, 165, 13, 40, 0, 88, 100, 190, 180, 71, 184, 54, 60, 4, 253, 6, 97, 147, 196, 174, 239, 255, 19, 140, 234, 180, 7, 243, 80, 251, 57, 115, 103, 128, 231, 131, 196, 174, 116, 166, 105, 56, 148, 52, 29, 98, 116, 203, 23, 65, 66, 203, 71, 96, 233, 209, 170, 181, 36, 17, 86, 198, 174, 178, 176, 19, 47, 158, 5, 38, 249, 233, 63, 126, 67, 205, 131, 15, 189, 103, 153, 161, 153, 47, 19, 126, 197, 177, 129, 190, 105, 18, 22, 188, 194, 236, 170, 80, 28, 178, 24, 184, 54, 182, 202, 210, 239, 37, 41, 11, 204, 226, 214, 18, 140, 184, 230, 184, 42, 62, 99, 248, 126, 8, 237, 150, 79, 39, 69, 96, 87, 154, 3, 175, 193, 222, 212, 122, 173, 74, 88, 49, 92, 236, 186, 22, 114, 64, 41, 225, 20, 98, 34, 223, 29, 244, 71, 59, 23, 102, 46, 137, 14, 32, 54, 63, 190, 215, 16, 181, 112, 131, 146, 87, 142, 80, 234, 152, 36, 41, 175, 213, 244, 120, 186, 8, 159, 121, 93, 58, 82, 11, 112, 180, 44, 27, 158, 138, 231, 87, 190, 81, 174, 149, 171, 127, 119, 30, 244, 248, 155, 88, 117, 114, 26, 182, 103, 182, 142, 169, 30, 51, 70, 214, 63, 60, 152, 110, 14, 110, 148, 195, 107, 93, 12, 135, 35, 222, 187, 60, 117, 90, 51, 227, 127, 109, 24, 23, 223, 135, 98, 3, 119, 138, 16, 215, 134, 89, 243, 126, 218, 144, 52, 36, 59, 251, 243, 77, 118, 231, 147, 200, 212, 163, 242, 134, 78, 127, 252, 173, 98, 78, 151, 21, 106, 185, 139, 182, 228, 210, 79, 62, 63, 120, 15, 34, 189, 190, 164, 106, 133, 84, 156, 246, 128, 13, 94, 119, 182, 48, 251, 1, 170, 204, 193, 250, 114, 196, 50, 25, 5, 170, 167, 70, 128, 37, 168, 128, 200, 112, 104, 134, 182, 126, 202, 214, 170, 131, 198, 95, 237, 138, 205, 108, 135, 206, 102, 128, 94, 75, 209, 130, 175], 'd_pk': '81c0a09692ad852649aeca550e0c8a280814b1f2ee5b9cdba7fad5399e050c94', 'd_signer': [92, 179, 203, 137, 168, 215, 194, 231, 231, 220, 175, 55, 104, 195, 181, 202, 168, 124, 36, 109, 96, 52, 119, 111, 123, 228, 68, 52, 181, 176, 146, 52, 110, 192, 12, 72, 140, 192, 53, 100, 9, 182, 78, 181, 147, 164, 213, 10, 151, 175, 65, 17, 110, 223, 245, 47, 20, 208, 48, 41, 30, 236, 111, 168, 188, 193, 28, 201, 123, 106, 228, 90, 176, 80, 228, 237, 209, 104, 204, 165, 146, 66, 84, 137, 250, 123, 1, 169, 48, 28, 33, 131, 220, 15, 248, 189, 248, 196, 210, 54, 70, 84, 201, 197, 4, 169, 187, 74, 122, 147, 205, 245, 111, 164, 212, 30, 7, 134, 117, 220, 58, 85, 201, 124, 76, 119, 171, 16, 128, 75, 95, 142, 33, 112, 7, 235, 237, 106, 176, 42, 79, 101, 233, 123, 218, 40, 105, 40, 131, 178, 105, 26, 164, 83, 217, 72, 110, 192, 245, 134, 156, 200, 121, 190, 53, 159, 136, 149, 20, 92, 59, 158, 40, 180, 6, 85, 38, 37, 93, 140, 11, 230, 95, 178, 209, 159, 73, 21, 62, 164, 247, 235, 114, 164, 239, 84, 185, 99, 134, 105, 190, 168, 189, 167, 27, 238, 210, 2, 112, 69, 54, 80, 247, 122, 86, 253, 131, 10, 159, 124, 219, 234, 81, 177, 64, 99, 143, 18, 94, 3, 89, 126, 215, 254, 57, 136, 35, 251, 152, 4, 75, 83, 7, 14, 173, 250, 86, 240, 132, 155, 171, 59, 157, 144, 235, 150, 58, 239, 151, 106, 248, 62, 217, 115, 177, 243, 37, 62, 9, 112, 90, 140, 185, 240, 145, 164, 215, 124, 134, 196, 57, 138, 244, 108, 145, 11, 134, 234, 74, 14, 83, 168, 222, 161, 94, 196, 27, 62, 111, 11, 245, 13, 223, 217, 47, 99, 120, 59, 28, 42, 108, 190, 217, 153, 150, 225, 33, 129, 182, 150, 222, 184, 9, 211, 250, 40, 251, 26, 87, 30, 105, 113, 145, 86, 251, 186, 2, 48, 64, 78, 226, 97, 29, 180, 111, 247, 49, 19, 172, 160, 115, 128, 187, 240, 111, 243, 248, 11, 153, 91, 245, 24, 58, 252, 112, 187, 27, 121, 31, 167, 186, 76, 120, 233, 82, 227, 216, 104, 215, 29, 12, 12, 64, 186, 167, 219, 232, 4, 42, 243, 80, 133, 189, 137, 153, 195, 94, 197, 53, 121, 178, 185, 130, 75, 22, 139, 144, 149, 183, 245, 40, 120, 155, 165, 174, 7, 167, 181, 162, 119, 237, 197, 38, 65, 9, 118, 213, 181, 211, 221, 15, 59, 203, 170, 144, 112, 198, 212, 142, 173, 131, 227, 47, 242, 125, 175, 250, 168, 202, 212, 196, 247, 16, 252, 32, 130, 19, 183, 197, 152, 227, 141, 52, 55, 200, 15, 20, 97, 204, 65, 93, 10, 120, 31, 15, 181, 5, 206, 152, 136, 15, 123, 62, 56, 41, 77, 186, 12, 130, 52, 214, 202, 19, 248, 159, 45, 60, 27, 161, 44, 27, 187, 86, 213, 105, 23, 80, 153, 214, 245, 35, 66, 210, 98, 56, 245, 117, 156, 78, 78, 47, 35, 204, 105, 234, 210, 165, 101, 148, 112, 48, 233, 236, 73, 113, 182, 166, 187, 148, 32, 131, 68, 76, 85, 241, 41, 160, 23, 156, 84, 103, 66, 137, 3, 154, 30, 167, 192, 237, 211, 122, 65, 195, 65, 212, 121, 49, 235, 68, 201, 11, 13, 93, 149, 14, 221, 51, 31, 108, 134, 83, 93, 155, 61, 32, 57, 240, 180, 161, 235, 211, 66, 126, 100, 95, 131, 109, 198, 54, 37, 62, 137, 50, 82, 153, 255, 213, 2, 181, 72, 145, 248, 127, 150, 33, 22, 116, 128, 52, 102, 39, 17, 42, 83, 116, 80, 245, 220, 80, 113, 226, 20, 196, 84, 91, 215, 172, 92, 88, 128, 146, 220, 102, 243, 125, 13, 216, 215, 253, 102, 224, 212, 225, 126, 145, 135, 188, 163, 4, 71, 218, 141, 77, 112, 100, 235, 236, 104, 27, 214, 216, 97, 49, 245, 236, 45, 136, 5, 96, 17, 171, 70, 254, 205, 252, 85, 26, 11, 3, 50, 153, 5, 6, 18, 38, 87, 251, 25, 111, 236, 216, 28, 95, 163, 218, 170, 16, 59, 140, 96, 220, 87, 191, 133, 47, 127, 100, 184, 241, 40, 167, 140, 115, 193, 17, 28, 209, 208, 43, 4, 50, 117, 181, 65, 236, 131, 71, 163, 119, 101, 67, 174, 160, 220, 231, 177, 245, 80, 115, 201, 34, 195, 158, 24, 42, 103, 198, 136, 152, 93, 190, 61, 169, 105, 188, 109, 185, 90, 14, 126, 238, 33, 234, 17, 151, 148, 91, 178, 93, 198, 188, 178, 26, 218, 78, 236, 16, 156, 146, 19, 227, 18, 103, 254, 182, 51, 186, 96, 223, 105, 129, 228, 81, 12, 150, 92, 88, 146, 171, 73, 243, 9, 126, 195, 1, 57, 60, 113, 204, 21, 87, 160, 166, 162, 118, 26, 112, 45, 153, 59, 41, 84, 247, 190, 29, 26, 26, 45, 99, 202, 65, 224, 37, 142, 37, 192, 116, 255, 129, 13, 246, 71, 172, 40, 138, 140, 44, 255, 209, 188, 175, 60, 230, 215, 86, 229, 217, 141, 115, 38, 154, 5, 123, 32, 247, 173, 166, 149, 70, 91, 68, 172, 168, 92, 147, 170, 5, 95, 75, 188, 101, 48, 160, 145, 225, 66, 192, 56, 138, 208, 121, 222, 23, 164, 228, 78, 3, 182, 172, 94, 107, 237, 114, 208, 233, 191, 209, 69, 58, 38, 255, 207, 226, 212, 124, 62, 186, 3, 198, 55, 147, 17, 52, 84, 78, 137, 172, 200, 140, 70, 8, 187, 55, 235, 129, 247, 186, 96, 194, 225, 9, 94, 38, 19, 119, 170, 247, 243, 43, 54, 112, 54, 172, 67, 29, 201, 17, 141, 143, 37, 105, 62, 82, 244, 131, 148, 106, 99, 147, 46, 0, 7, 242, 47, 231, 201, 105, 127, 111, 140, 58, 228, 216, 128, 236, 33, 42, 245, 128, 88, 111, 95, 200, 56, 37, 84, 184, 80, 179, 102, 226, 39, 179, 112, 188, 90, 137, 111, 158, 162, 116, 63, 169, 250, 126, 29, 22, 41, 31, 148, 193, 99, 64, 67, 216, 160, 73, 154, 184, 129, 246, 44, 102, 21, 168, 126, 145, 169, 203, 232, 6, 59, 65, 125, 180, 122, 28, 33, 91, 66, 68, 11, 246, 74, 118, 52, 229, 200, 28, 209, 215, 255, 68, 122, 40, 146, 124, 181, 245, 25, 179, 139, 95, 42, 74, 228, 207, 206, 2, 239, 156, 136, 73, 221, 73, 248, 94, 184, 75, 148, 126, 25, 71, 22, 237, 14, 53, 132, 145, 216, 64, 172, 212, 153, 178, 182, 93, 71, 113, 109, 64, 41, 146, 190, 22, 198, 238, 171, 72, 155, 6, 182, 205, 234, 157, 74, 43, 188, 187, 28, 94, 0, 138, 133, 238, 30, 216, 154, 160, 31, 87, 137, 58, 217, 221, 186, 154, 138, 244, 50, 30, 253, 220, 34, 175, 0, 139, 55, 26, 103, 35, 136, 210, 180, 7, 223, 221, 201, 212, 190, 39, 128, 63, 46, 210, 156, 149, 19, 41, 41, 77, 147, 26, 253, 40, 253, 134, 125, 115, 89, 117, 156, 169, 47, 154, 227, 178, 155, 20, 40, 79, 82, 164, 103, 55, 107, 251, 8, 95, 197, 237, 81, 14, 18, 16, 62, 14, 48, 28, 206, 137, 27, 247, 69, 214, 38, 201, 128, 128, 105, 197, 72, 135, 246, 249, 24, 244, 244, 6, 73, 146, 2, 186, 54, 50, 143, 77, 118, 185, 187, 252, 195, 32, 11, 40, 224, 212, 41, 26, 238, 23, 81, 67, 81, 200, 3, 15, 19, 45, 129, 22, 17, 189, 107, 111, 239, 235, 57, 58, 145, 230, 37, 212, 75, 189, 44, 191, 123, 9, 250, 137, 224, 186, 84, 145, 158, 236, 11, 83, 142, 103, 92, 71, 98, 214, 103, 184, 10, 36, 208, 143, 74, 186, 201, 158, 166, 67, 144, 15, 183, 228, 12, 193, 220, 199, 141, 64, 234, 145, 94, 212, 110, 15, 14, 92, 84, 57, 50, 164, 252, 198, 205, 233, 18, 175, 239, 161, 196, 89, 188, 165, 189, 16, 162, 108, 6, 187, 140, 197, 165, 202, 107, 193, 54, 44, 163, 10, 241, 218, 30, 197, 37, 1, 189, 180, 133, 214, 32, 245, 16, 46, 49, 239, 156, 56, 151, 36, 115, 170, 222, 96, 135, 165, 9, 191, 10, 207, 128, 219, 170, 102, 85, 2, 8, 59, 237, 132, 35, 94, 187, 139, 136, 243, 50, 103, 43, 140, 167, 51, 70, 252, 200, 198, 120, 13, 212, 85, 35, 170, 135, 196, 38, 190, 172, 190, 136, 12, 50, 67, 209, 125, 228, 189, 164, 247, 38, 69, 79, 122, 149, 172, 221, 41, 25, 254, 126, 156, 38, 201, 56, 239, 158], 'sig': True, 'addr': [], 'seed': [], 'data': []}
serialized_data = json.dumps(data)
data = json.loads(serialized_data)
is_verified = verified(convert(data['k_signer']), data['d_pk'], data['d_signer'], data['sig'], data['addr'], data['seed'], data['data'])
print(is_verified)

Comment: `k_signer` is a `list`, and lists and tuples cannot be concatenated, like the error says. Either use `tuple(k_signer)` and `tuple(d_signer)` if you want it to be a tuple, or make hash a list and use `hash.append` if you want the end result to be a list.
Answer: You forgot to call the conversion function for some parameter in your function.
I tested and corrected your code, call it this way:
is_verified = verified(
    convert(data['k_signer']),
    data['d_pk'],
    convert(data['d_signer']),
    data['sig'],
    convert(data['addr']),
    convert(data['seed']),
    convert(data['data'])
)

Answer: You might also convert(data['d_signer']) as below:
is_verified = verified(convert(data['k_signer']), data['d_pk'], convert(data['d_signer']), data['sig'], data['addr'], data['seed'], data['data'])


Stolz Cesaro Application

Question: If $b_n \rightarrow 1$ as $n \rightarrow \infty$, then show that
$\frac{b_n-1}{\ln b_n} \rightarrow 1$ as $n \rightarrow \infty$.
I was told to prove this using Stolz-Cesaro's Lemma.
Edit: $b_n = \frac{\sqrt[n+1]{(n+1)!}}{\sqrt[n]{n!}}$. Sorry for the confusion.
Thank you!
The hard part is, even if I apply Stolz Cesaro's Lemma, the function we have
$\frac{b_{n+1}-b_{n}}{\ln {\frac{b_{n+1}}{b_n}}}$
Which is even more complex to compute. I tried repeating Stolz Cesaro again, but it still doesn't work.
Comment: Can you really use that? In the assumption some sequence has to be monotone.
Answer: Let's use the differentiable version of Stolz Cesaro's Lemma: The L'Hospital rule. Let $f(x) = \frac{x-1}{\ln x}$. Then
$$\lim_{n\to \infty} \frac{b_n - 1}{\ln b_n} = \lim_{n\to \infty} f(b_n) = \lim_{x\to 1} f(x)$$
if the limit exist. Since
$$\lim_{x\to 1} \frac{(x-1)'}{(\ln x)'} = \lim_{x\to 1} \frac{1}{1/x} =1,$$
By L' Hospital Rule, we have
$$\lim_{x\to 1} f(x) = 1\Rightarrow  \lim_{n\to \infty} \frac{b_n  -1}{\ln b_n} = 1.$$

Stolz Cesaro Application


How to prevent actions using Flag (or similar) module?

Question: The Goal: I'm trying to setup functionality similar to a library with downloadable files. Only one user can download a file at a time.
The Solution: Use the Flag module.
Open to suggestions but through my research it seems like people are using the Flag module for this type of functionality. My question is how do I actually get this to work? I'm using a file field to add a file to a node. An admin comes along, wants to "checkout" that file, and they click the checkout flag, and then download the file. Now no other admin can download that file.
Once the original admin comes back, they can just click the flag again, setting it to open. (I know, they aren't really returning a digital file.) They just need to simulate returning it by basically just telling the system someone else can get this file.
Anyone set up something similar to this or just have an idea of how I would do this? Thanks for any suggestions and help.
Answer: I haven't done this, but if you want a library check in/check out system this is the approach I would try.  Create a flag (here I'll call it Check out) that allows users to "check out" files.  Make sure this is a global flag.  Name the unflag link "Check in" or something similar.  (You could also automatically have files checked back in after a certain interval with Rules Scheduler.)
Then, I would create views so that users cannot see the nodes that are checked out.  To actually enforce security, I would also add a rule that automatically redirects users away from the page of any node that they did not flag that has been flagged (this probably will cause a performance hit and may not be the most secure way but will probably work for general cases).
Comment: Hmmm. I should have been thinking of this. I can see a couple of pitfalls for my use-case, but I'm upvoting regardless because this is something I should have considered and the thought never crossed my mind. Thanks for the suggestion.
Answer: Well the maintainer of the module said it probably isn't possible to do what I want without writing a custom module. The maintainer also stated you can't flag files out of the box like I'm referring to here. Since I want to disable the file download on flag, I can't add the flag to the node and disable because that will disable the node--not my intention.
So since my php skills are virtually equal to nothing I accomplished this via javascript. First, I added the flag to the node. Then I added some js:
<code>$(".flagged").each(function(){
    $(".checkout-file").remove();
});
</code>
Easy to get around, I know, but I don't really need to protect the files at all and only admin will be perusing these files anyway. I only wanted to disable the download as an extra measure in case they don't notice the flag. The purpose being to state, "Don't bother wasting your time downloading this file since someone else is already reviewing it." So maybe someone else will need something like this.
Answer: you should consider a less popular module called "conditional flags" - you can create two flags that effectively represent "checked out" and "available" and make the "available" set to "not available" when a user "checks out" an item.
there are also code examples on the project page and so it may be possible to customize the module for a more elaborate need (e.g. a rule/trigger/action linked to a download or something more robust)
enter link description here


How to know what beat & rhythm to play for add-on to songs

Question: Theres this famous drummer on YouTube named Copper who takes existing songs, removes the drums, and then plays live drums along with the other investments. How does he know what beats & rhythm to play for so many songs?
Is there any methodology to follow?
Comment: What do you mean by add-on? Do you mean he adds drums to existing songs? If so, he just listens to the rhythm, any break points etc and then improvises over standard rhythmic patterns.
Comment: @DrMayhem Yea i mean adding drums to existing drums
Answer: If you listen to a song, you will immediately be able to see what rhythm it is (4/4, 3/4 etc), what bpm, where the breaks are, how much swing is appropriate, where the accents are etc.
That would be the case whether or not existing drums were on the track. If there are no drums, you can pretty much fit what you like to the song, and a little experience will allow any drummer to do this.
If there are already drums, the skill lies in accentuating, rather than copying or just drumming around what is already there, but it is based on the same concepts:

knowing what accents, fills and flourishes will fit
where the breaks lie
and what the basic beat is

So to summarise, he doesn't 'know' what beats to play, but experience allows him to feel where beats could work and he adds these in.
Answer: re "If you listen to a song, you will immediately be able to see what rhythm it is (4/4, 3/4 etc), what bpm, where the breaks are, how much swing is appropriate, where the accents are etc." - I'm not sure I agree with that, although the rest of that answer seems good to me.
If there is an existing drum track, that must give you a huge clue as to where to start. But having just given some rudimentary drum lessons, my student asked how I work out when to start the basic rhythm, so that the rhythm fits the song. This made me realise that what's intuitive to me isn't obvious to everyone ! And I remebered having to learn this for myself.
If you want to try such drumming, and it's not that clear to you, try this :

Tap along to the song, and count 1-2-3-4.  Most people can naturally feel the rhythm of a tune and tap in time to it. Normally, people will tap on the bass and then snare strikes (just intuitively - eg if you listen to a crowd clapping along to music). You'll end up with 1-2-3-4 = bass-snare-bass-snare. Sometimes it doesn't quite work and you have to do this half speed for slower songs or double speed for faster songs like Ace of Spades.
On your drums, play a bass drum and a snare as above along with the song .. there's your basic beat.

Note that I'm assuming the rhythm of the song is "even" ie not 5/8 or something odd, where this method will fall apart. Most popular music is pretty evenly paced.
This is probably how a lot of people gain the ability to drum along to anything.
As of there - for the song you linked to, the bass drum riff is accentuated to be more funky, which is where the feel for the rhythme comes in - and to be honest the choice. You can try a few things decide what you think works best.
For fills etc : It looks to me like this fella is going a bit wild and putting in everything he can think of which probably relies on experience ('this fill fitted with this rhythm last time I did it on another song..'),  "muscle memory" and a feel for what he wants to project.
Answer: In general, look for a phrase that's being repeated. This is the main "building block" for each part of a song. When you've identified the phrase you know when the bar starts and ends. Next, try to count within the bar. The best first guess, as others have indicated, is trying to count to 4 along with some notes played (e.g. notes accented by the bass guitar). If it fits, then most likely it's 4/4 and you can start figuring out where do accents go.
If it doesn't fit, then there are two possibilities. First is easy: it's 3/4 or 6/8 or something like that, so it's easy to deduce by counting that going to 4 is 1 off, and experimenting with counting to 3 (e.g. when it's 3/4 or 6/8) or 5 (e.g. 5/8) makes it right.
Second possibility is that the time signature is something like 5/8 or 13/16 etc. This is indicated when counting to 4 is off with the phrase, but not exactly by some integral number of 1s. For 9/8, for example, it's often easy to hear, that you're missing a half when counting to 4. Then you experiment with counting to 8 twice as fast (if possible) and count 9 notes. If the tempo is too fast to count with 8s, then you need to be accustomed with playing 9/8 - it's easy to imagine as ordinary 4/4 + 1/8 - just "one note twice as fast" added. What you can hear for sure is whether your counting too much, or too few. So you can just experiment with different signatures until you guess the right one.
Of course there may be even more complicated compositions, or parts of composition when it's not easy to hear a repeating phrase. In such case you can try focusing on accents.


How to select a set of independent features predictive of all other features without a target variable

Question: Problem
I have a dataset NxD, where N - number of observation (~100k) and D - number of features (~10k)
(More specifically it is a single-cell RNAseq data, so each observation is a single cell and each feature is a gene, values are counts of genes in each of the cells).
<code>
    *Cell* Cell1 Cell2 Cell3 ....
*Gene*
DPM1       .  . . . .  .  .  . .  .  . 1  . . .  .  .  .  .
SCYL3      .  . . . .  .  .  . .  .  . .  . . .  .  .  .  .
C1orf112   .  . . . .  .  .  . .  .  . .  . . .  .  .  .  .
FGR        .  . . . .  .  .  . .  1  . .  . . .  .  .  .  .
CFH        .  . . . .  .  .  . .  .  . .  . . .  .  .  .  .
FUCA2      .  . . . .  .  .  . .  .  . .  . . .  .  .  1  .
GCLC       .  . . . .  .  .  . .  .  . .  . . .  .  .  .  .

</code>
As you can see data is discrete and sparse (only a small set of genes have non-zero counts in each cell).
I would like to select a subset of features (genes) such that:

The dimensionality of the subset d << D (~1k)
Resulting features are not correlated
Using this subset I can predict remaining features

Possible approaches
I have a few ideas in mind, but I would be very grateful for any comments or suggestions. Are there any standard ways of approaching this problem?

Find clusters of genes in the space of cells (or reduced space) and select one gene per cluster, e.g. from the center. Presumably all genes in the cluster will be somewhat correlated with each other and therefore one gene should be enough to capture information about the other genes in the same cluster. Problems with this approach: clustering in high-dimensional space is hard, and this won't capture anticorrelated genes - they will belong to separate clusters, but still can be used to predict each others' expression.

Same as above, but use hierarchical clustering on the distance matrix. Distance can be anything from simple covariance, to mutual information (this would take care of anticorrelated genes as well).

Select most important features from multiple regularized regressions:
$\forall i, \quad x_i \sim X_{-i}$,
where $x_i$ is expression of gene $i$, $X_{-i}$ - expression of all other genes. The problem with this approach - the distribution of gene counts is negative binomial so both my target variable and predictor variables will be negative binomial distributed.
Comment: You can use as you said a Clustering Method, and from your $D$ features you might result with $K$ clusters $K<<D$. You can also calculate representative statistics for each cluster and summarise them, instead of using the $D$ features. However, in that case, there might be some correlation between the clusters, as you can imagine some features might be really close to each other but assigned to different clusters.
Comment: A different approach would be to use PCA. Where you will get uncorrelated features (principal components), but the new-made features (which are linear combinations of your original features $D$) are hard to be inferred.
Answer: There is extensive literature on the application of unsupervised learning to gene-expression data, dating back to early microarray analysis of RNA. Back then, clustering was done for example to try to distinguish subclasses of tumors among individuals. The advent of RNA-seq moved the focus toward analysis of count data. The more recent extension to single cells (scRNA-seq), typically looking for different types of cells in a sample, requires additional attention to the sparsity of the data.
This recent review goes over ways to cluster scRNA-seq data in substantial detail, with over 100 references and with links to software for implementation. Clustering typically involve a combination of methods. For example, SC3 clustering combines principal components analysis (PCA*, as suggested in a comment) and parallel evaluation of multiple parameter values to provide a final k-means clustering. Other methods are hierarchically based, sometimes combined with other processing. There are tradeoffs among the approaches both in terms of practical implementation, depending on the scale of the data, and in terms of just what you are trying to accomplish with the clustering.
A frequently used method for clustering scRNA-seq data, not addressed well in that review, is t-distributed stochastic neighbor embedding (t-SNE), which attempts to reduce high-dimension data into a 2D representation of clusters. This article by Kobak and Berens shows how to use t-SNE on scRNA-seq data while avoiding problems with its "naive application."
Once you've identified the expression clusters in your data, you could proceed to find exemplar genes expressed highly within each cluster if your clustering is based on gene-expression values rather than on a transformation as in PCA. My guess, however, is that even then you will need to use more than 1 exemplar gene per cluster. That's true with clinical tests that try to distinguish classes of tumors from bulk-tissue RNA analysis, so it's even more likely to be the case with the low number of counts per gene typical with scRNA-seq for other than housekeeping genes. If your clusters are based on linear combinations of gene expression values as in PCA, you will have to find combinations of genes that can be used together to identify clusters.

*PCA ensures that all components are orthogonal, which would match your desire that "resulting features are not correlated." That orthogonality, however, will not be seen on the single-gene level, it will represent the situation after any data pre-processing, and it might make it impossible to find individual genes that are exemplars of your clusters.
Comment: Thank you for your answer! Most of the literature on scRNAseq deals with clustering cells in the space of genes, not the other way around. The difference is that if you're looking at sufficiently different cell types it's easy to end up with well-defined tight cell clusters. Generally this is not going to be the case for majority of genes. With the exception of conserved cell type markers they don't form tight clusters in the cell space. Also, t-SNE is dimensionality reduction method, not clustering method.
Comment: @perlusha after t-SNE reaches dimensionality down to 2, it's quite possible to distinguish clusters. See Figure 2 of [this scRNA-seq paper](https://doi.org/10.1016/j.cell.2017.10.044) for example. So it's possible to consider t-SNE in practice as a clustering method.
Comment: @perlusha In principle if you want to cluster genes rather than cells, you transpose the data matrix and use whichever clustering method best addresses your interest. The sparsity issues specific to scRNA-seq are essentially the same in either direction. The problem with clustering genes across a heterogeneous population of cells is that it will work best if groups of genes are alway co-regulated regardless of the cell type or cell state. That's unlikely biologically. Even in an apparently homogeneous culture of a cell line, cells will be heterogeneous in terms of cell-cycle state.


Does one have to hit a cushion during a break in snooker?

Question: I was wondering during the break in a snooker game can I simple strike the cue softly and just touch the reds. Or do I have to hit the cue ball and make sure it rebounds and hits a cushion?
I just wanted to tap the reds so it lands closer to the reds without breaking the triangle bunch as much..
Answer: Not in snooker, on any shot. You just have to hit the correct ball first. The break shot has no extra rules.
The official rules of snooker are here, the World Professional Billiards and Snooker Association
No specific rule applies to the opening shot of a frame, nor is there anything requiring cushions to be hit.
There is a rule about cushions in the section for Shoot-out Snooker, but this variant is rarely played.
Pool does have rules in these areas, but that is a different sport.


CSS: Float Image

Question: Why does the float:left and float:right element cause my web page to become squashed?
This is what happens when I try to float:left or float:right.
http://prntscr.com/3fx03d
The page seems to forget the images take up space on the page
The only way to fix this is to use "
...
" at the very bottom of the images in the HTML Code then it will look like this.
http://prntscr.com/3fx13l
What is going on here?

Yes I have ensured to specify the size of the images beforehand.

HTML

Images

...

© Copyright 2014 All rights reserved

CSS:
div.images{
    position:relative;
    left:0px;
    float:left;
    width:765px;
    margin:0px -5px;
    }

Comment: It is hard to tell what you're asking from the pictures. Could you create a http://jsfiddle.net ?
Comment: Can you post the relevant code in question?
Answer: If I am understanding your problem correctly, in a nutshell, floated elements do not add height to the container. There are a number of ways to correct this behavior. Float the parent element, specify overflow: hidden on the parent or use a clearfix hack http://css-tricks.com/snippets/css/clear-fix/.
There is a pretty indepth article on this here at stackoverflow:
Why doesn't the height of a container element increase if it contains floated elements?
Comment: I did a search of this topic, but I couldn't find anything on it. Stackoverflow needs to make it easier to find things

CSS: Float Image


How to verify a bivariate density?

Question: Verify that the following is a bivariate density:
$F(X, Y) = \displaystyle\frac{2}{\pi}$ for $X^2+Y^2\leq1$ and $X < Y$
$F(X,Y) = 0$ otherwise
Now, I know that verifying that this is a bivariate density involves taking a double integral and showing that it is equal to 1. However, I'm not quite sure what the limits are for this integral! Here is the integral I have:
$\displaystyle\int\displaystyle\int \displaystyle\frac{2}{\pi} dx dy$
How can I find out the limits for this integral?
Thank you!
Comment: If you draw a picture you can do this one by inspection.
Comment: Integrate over all possible values of $x$ and $y$ where $F(x,y)\neq 0$.
Comment: @MatthewGunn So, would that be $-1 \leq x < \displaystyle\frac{1}{\sqrt{2}}$ and $-\displaystyle\frac{1}{\sqrt{2}} < y \leq 1$?
Comment: Close, but is $x=-1, y=-1$ possible? the range of one variable has to be conditional on the value of the other.
Comment: Three approaches I would consider depending on how much time you want to spend. (1) Recognize that you're after $2/\pi$ times the area of the intersection of $x^2+y^2\leq1$ and $x<y$. What is that? (2) Recognize that this particular problem is invariant to rotation so you could use the algebraicly easier constraints $x^2+y^2\leq 1$ and $y \geq 0$ or (3) integrate over the region from $x \in (-1, 1/\sqrt{2})$ and $y$ what it needs to be (may be a good algebra/geometry/careful thinking exercise, but it's kinda of an unneccesary pain).
Comment: @MatthewGunn I'm not quite sure how to find that condition, though. I drew a picture of the area in question and see that $x=-1,y=-1$ is not possible, but how do I determine the conditional relationship?
Comment: The limits are $-\infty$ and $+\infty$ :)
Answer: My calculus is probably rusty.
I think it's a good idea to sketch the region over which you will integrate. Firstly, we know that:
$$X^{2}+Y^{2}\leq 1$$
which is the region bound by a unit circle. Furthermore, we have the constraint that:
$$X<Y$$
so the desired region is that bounded by a unit circle where $X$ is less than $Y$. To illustrate:

If you want you can convert to polar coordinates as follows:
$$\begin{align}
x=r\text{cos}(\theta)\\
y=r\text{sin}(\theta)
\end{align}$$
where the Jacobian is given by:
$$\begin{align}
J&=\left|\begin{array}{cc}
\tfrac{\partial x}{\partial r} & \tfrac{\partial x}{\partial \theta}\\
\tfrac{\partial y}{\partial r} & \tfrac{\partial y}{\partial \theta}
\end{array} \right|
\\
&=\left|\begin{array}{cc}
\text{cos}(\theta) & -r\text{sin}(\theta)\\
\text{sin}(\theta) & r\text{cos}(\theta)
\end{array} \right|
\\
&=r
\end{align}$$
You'll be able to determine the appropriate limits of integration from the plot. In polar coordinates, the bounds are:
$$\begin{align}
0&\leq r\leq 1\\
\tfrac{\pi}{4}&\leq \theta \leq \tfrac{5\pi}{4}
\end{align}$$
The integral you want to evaluate is:
$$\frac{2}{\pi}\int_{\pi/4}^{5\pi/4}\int_{0}^{1}r\,dr\,d\theta$$
Comment: I've drawn the picture myself, I just can't figure out the correct limits for the integrals. How do I determine the relationship between $x$ limits and the $y$ limits?
Comment: @Bing In polar coordinates: $r$ is bounded by $0$ and $1$. $\theta$ is bounded below by $\pi/4$ and above by $5\pi/4$.

How to verify a bivariate density?


Como colocar um List<> em um ListView?

Question: Eu tenho um método para ler meu banco de dados que me retorna um List<>, gostaria de saber como eu faço para exibir esse List<> em um componente ListView
<code> DLL dll = new DLL();
 dll.listaVeiculoss(); //Esse método retorna um List<Veiculios>
 metroListView2; //Esse é um componente do tipo ListView
</code>
Comment: Você está usando winforms?
Answer: Supondo que você tem uma classe com as seguintes propriedades:
<code>public class Veiculos
{
    public int idVeiculo { get; set; }
    public string Fabricante { get; set; }
    public string Modelo { get; set; }
}
</code>
Então faça isso:
<code>//Adicionando alguns itens na lista:
List<Veiculos> listaVeiculos = new List<Veiculos> {
    new Veiculos { idVeiculo = 1, Fabricante = "Fiat", Modelo = "Palio" },
    new Veiculos { idVeiculo = 1, Fabricante = "Volkswagen", Modelo = "Fusca" },
    new Veiculos { idVeiculo = 1, Fabricante = "Ford", Modelo = "Fiesta" }
};
//Mudei a visualização para detalhes para cada item aparecer em coluna...
listView1.View = View.Details;
//Adicionei as colunas que irei mostrar na listView
listView1.Columns.Add("idVeiculo");
listView1.Columns.Add("Fabricante");
listView1.Columns.Add("Palio");

//Percorre a lista adicionando as linhas do ListView
foreach(var item in listaVeiculos)
{
    listView1.Items.Add(new ListViewItem(new string[] { item.idVeiculo.ToString(), item.Fabricante, item.Modelo }));
}
</code>

Como colocar um List<> em um ListView?


No entry in the database? However, the error message does not

Question: I wrote this code but it is not listed in the database will show the message successfully inserted?
if (txtdate.Text != "" && txtalireza.Text != "" && txtdatekamel.Text != "" && txthasan.Text != "" && txtkarbar.Text != "" && txtkarkard.Text != "" && txtkharid.Text != "" && txtmoj.Text != "" && txttozih.Text != "")
            {

                SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirector  y|\Resources\dbcn.mdf;Integrated Security=True;User Instance=True");
                SqlCommand com = new SqlCommand();
                com.Connection = con;
                com.CommandText="INSERT INTO newbuy(byname,datekol,dateshort,karkard,kharidha,b  arali,barhasan,barmoj,descrip)VALUES(@byname,@date  kol,@dateshort,@karkard,@kharidha,@barali,@barhasa  n,@barmoj,@descrip)";
                com.Parameters.AddWithValue("@byname",txtkarbar.Te  xt);
                com.Parameters.AddWithValue("@datekol", txtdatekamel.Text);
                com.Parameters.AddWithValue("@dateshort", txtdate.Text);
                com.Parameters.AddWithValue("@karkard",txtkarkard.  Text);
                com.Parameters.AddWithValue("@kharidha",txtkharid.  Text);
                com.Parameters.AddWithValue("@barali",txtalireza.T  ext);
                com.Parameters.AddWithValue("@barhasan",txthasan.T  ext);
                com.Parameters.AddWithValue("@barmoj",txtmoj.Text)  ;
                com.Parameters.AddWithValue("@descrip",txttozih.Te  xt);
                con.Open();
                com.ExecuteNonQuery();

                MessageBox.Show("inserted");

                con.Close();
            }
            else
            { MessageBox.Show("error"); }`

Answer: int result=0;
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirector  y|\Resources\dbcn.mdf;Integrated Security=True;User Instance=True");
            SqlCommand com = new SqlCommand();
            com.Connection = con;
            com.CommandText="INSERT INTO newbuy(byname,datekol,dateshort,karkard,kharidha,b  arali,barhasan,barmoj,descrip)VALUES(@byname,@date  kol,@dateshort,@karkard,@kharidha,@barali,@barhasa  n,@barmoj,@descrip)";
            com.Parameters.AddWithValue("@byname",txtkarbar.Te  xt);
            com.Parameters.AddWithValue("@datekol", txtdatekamel.Text);
            com.Parameters.AddWithValue("@dateshort", txtdate.Text);
            com.Parameters.AddWithValue("@karkard",txtkarkard.Text);
            com.Parameters.AddWithValue("@kharidha",txtkharid.Text);
            com.Parameters.AddWithValue("@barali",txtalireza.Text);
            com.Parameters.AddWithValue("@barhasan",txthasan.Text);
            com.Parameters.AddWithValue("@barmoj",txtmoj.Text)  ;
            com.Parameters.AddWithValue("@descrip",txttozih.Text);
            try
            {
               con.Open();
               result=Convert.ToInt32(com.ExecuteNonQuery());
               if(result > 0)
               {
               // Success (show your message)
               }
            }
            catch(SqlException ex)
            {
               // Log exception
               throw ex;
            }
            finally
            {
              con.Close();
            }

Answer: remove space between @date & kol from values brackets

com.CommandText="INSERT INTO newbuy(byname,datekol,dateshort,karkard,kharidha,b  arali,barhasan,barmoj,descrip)VALUES(@byname,@date  kol,@dateshort,@karkard,@kharidha,@barali,@barhasa  n,@barmoj,@descrip)"; to
com.CommandText="INSERT INTO newbuy(byname,datekol,dateshort,karkard,kharidha,b  arali,barhasan,barmoj,descrip)VALUES(@byname,@datekol,@dateshort,@karkard,@kharidha,@barali,@barhasa  n,@barmoj,@descrip)";


How to solve simultaneous equations with both of the equations being quadratic equations.

Question: I'm familiar with how to solve simultaneous equations with 1 quadratic equation but not 2. I've looked all of the internet for a thread that has covered this, but I can't seem to find one.
$$
\begin{cases}
(x+y)^2 = 1\\
\\
(3x+2y)(x-y) = -5
\end{cases}
$$
Could someone please describe the process?
Comment: Neither of these are equations.
Comment: Equation $1$ implies that $y=-x\pm1$ plug that into equation $2$ and solve for four values of $x$ and hence eight values of $y$ by using $y=-x\pm1$.
Comment: My bad, accidentally forgot to add RHS.
Comment: @HenryPage, Is it not $$3x+2y?$$
Comment: my bad, again. yes it is
Comment: This is exactly what I did, however, when I end up checking it, I get a completely different answer like (-15)(-5) = -5 which is not accurate.
Comment: You did not add that context to your question. Perhaps you just made an arithmetic error in your calculations?
Comment: Thanks for the help guys, turned out just to be a calculation error from my side.
Comment: Your equation will simplify a lot by the transformation $$u = x+y\text{, }v = x-y$$ with the back-transform $$x = \frac{u+v}{2} \text{, } y =  \frac{u-v}{2}$$.
Comment: @Peter, each of the four values of $x$ comes from either $y=-1+x$ or $y=-1-x$, not both, so $y$ is fixed once $x$ is.
Comment: @Empy2 You are right. I can't edit the comment anymore so I guess I'll just leave it.
Answer: What if $x=0$
Else set $y=mx$ to find $$\dfrac1{-5}=\dfrac{(1+m)^2}{(3+2m)(1-m)}$$  which is a quadratic equation in $m$
Answer: The first equation is two lines.  Treat them separately.  First do $x+y=1$, substitute into equation 2 for two solutions.  Then do $x+y=-1$, substitute into equation 2 for two more solutions.


Using conformal mapping to solve a boundary value problem,

Question: Use conformal mapping to solve the following boundary value problem for $u=u(x,y)$ in the planar region $R=\{(x,y) \in \mathbb{R}^2: x^2 + y^2 > 1 \text{ and } y>0\}$:

u solves $U_{xx}+U_{yy}=0$ in R
$\frac{d}{d_n}=0$ on the boundary of R, where $\frac{d}{d_n}$ denotes the normal derivative.
$U_x(x,y)\to 1$  , as $x^2+y^2\to\infty$ in R.

I have no experience in solving these types of problems, nor do I have any experience in using conformal mappings / linear fractional transformations.  So, I don't know how to even get started.  Any help will be greatly appreciated.
Overall, I do not even know what the question is really trying to ask, so if someone can start off by helping me understand what the question is, that'd be awesome.  (FYI, this is not homework, just old problems that have been written for our math department.)
I know that the first bulletpoint means we need to find a function u that is harmonic in R, which is the region in the upper half plane, and outside of the unit disk.  I don't know what the second and third bulletpoints are even asking for, let alone proceed to write up a possible solution.
(I'll start with finding out what a normal derivative is...)
Answer: The question asks you to solve the Laplace equation in an indented domain. The domain is the upper half-plane less the upper half of the unit disk $x^2+y^2 < 1$. This is an uncomfortable geometry to work with, so they want you to use a conformal mapping $w=F(z)$ to transform the geometry into something easier to handle - I'm guessing into another half-plane - where the solution to Laplace's equation can be written in terms of boundary integrals.
The normal derivative indicates the rate of change of $u$ along the outward normal direction on the boundary of your region at any point on the boundary. Specifying $\partial_n u =0$ is a typical "insulated" boundary condition: If you imagined $u$ as the temperature in a steady-state heat conduction problem, it suggests that no heat flow occurs across the boundary. This is one example of a Neumann boundary condition, where you impose conditions on the derivatives of your unknown quantity.
The third condition is a boundary condition at infinity. Typically you require a bc at infinity to get a unique solution to the bvp. The bc at infinity also has physical significance - in this case (interpreted physically), it is like a constant heat-flux at infinity.
Comment: You explained that very well, @user_of_math, and I'd love to see a solution from you, if you have time to write one up.  So far, I've considered your background write-up, done some reading on Wikipedia and Wolfram, and have looked at the solution to this old prelim problem offered by a student.  But the solution is a very nasty one, and I'm wondering whether there is a cleaner and perhaps more instructive way of solving this problem...
Comment: @LebronJames It would be a bit too long, I'm afraid, because you don't have the requisite background in conformal mapping and the use of Poisson-type integration formulas to solve bvps. However, I suggest you refer to the excellent book by Ablowitz and Fokas (http://www.amazon.com/Complex-Variables-Introduction-Applications-Mathematics/dp/0521534291) - it has everything you need. Also, if my answer helped you, feel free to upvote it :)
Comment: Ok, got it.  Thanks so much @user_of_math.   Have a great day :)


Why is the SiteCollection Always null?

Question: I have the function:
    public SPList CreateList(SPFeatureReceiverProperties properties, Dictionary<string, List<AddParams>> columns,
        string name, string description, SPListTemplateType type, string viewDescription)
    {

        SPList spList = null;

        SPSite siteCollection = properties.Feature.Parent as SPSite;
        if (siteCollection != null)
        {
            SPWeb web = siteCollection.RootWeb;
            web.Lists.Add(name, description, type);
            web.Update();

            // Add the new list and the new content.
            spList = web.Lists[name];
            foreach(KeyValuePair<string, List<AddParams>> col in columns){
                spList.Fields.Add(col.Key, col.Value[0].type, col.Value[0].required);
            }

            spList.Update();

            //Create the view? - Possibly remove me.
            System.Collections.Specialized.StringCollection stringCollection =
                new System.Collections.Specialized.StringCollection();

            foreach (KeyValuePair<string, List<AddParams>> col in columns)
            {
                stringCollection.Add(col.Key);
            }

            //Add the list.
            spList.Views.Add(viewDescription, stringCollection, @"", 100,
                true, true, Microsoft.SharePoint.SPViewCollection.SPViewType.Html, false);
            spList.Update();

            return spList;
        }

        return spList;
    }

Yet for some reason when debugging the siteCollection is coming back null which is causing it to not do what I want it to. When I inspect properties.Feature.Parent I see the site Name:  'Team Site'
So why is this null?
Update:
This project, is site scoped
Comment: It could be useful to add information on who and from what kind of application calls this method...
Answer: There are two possible reasons that siteCollection might be null after the line instantiating it runs:

properties.Feature.Parent is null
properties.Feature.Parent is not an SPSite (or derived from SPSite)

If you're saying that you can see in the debugger that properties.Feature.Parent is not null when siteCollection is, that means that properties.Feature.Parent is not an SPSite instance.
You can see the type of this property when debugging by opening a Watch window and entering the expression properties.Feature.Parent.GetType().
Answer: Because it is not a kind of SPSite?  So when you cast it as something it's not it becomes null?
Comment: I have other methods very simmilar to to this that are doing the same thing, accept they are not returning null.
Comment: Why don't you check with "if (!properties.Feature.Parent is SPSite) System.Console.Write("Oh, that's why it's null!");"
Answer: Perhaps the properties.Feature.Parent is not an SPSite object.
The code as SPSite will set siteCollection to Null if it's an SPWeb object
Comment: is there a way to test this? when inspecting? will it tell me its type?
Comment: Yes:  properties.Feature.Parent.GetType()
Comment: I suppose you are calling this method from an event receiver that may be either Web or Site scoped? If that's the case you may want to pass in the SPWeb object explicitly
Comment: Can you see the type of properties.Feature.Parent in the debugger?
Answer: If you're trying to debug this, after this line SPSite siteCollection = properties.Feature.Parent as SPSite;, if you run this in either your watch window or immediate window properties.Feature.Parent.GetType() you should be able to identify the type of object it's returning, note that it has to be a compatible type (to SPSite) to be able to cast otherwise you get the null object.

Why is the SiteCollection Always null?


What is the best way of MongoDB Query Reporting in C#?

Question: I'm converting my Reporting website from MySQL to MongoDB in C#.
So far, I'm happy with MongoDB Inserting Data.
Now, from collection, I need to print out as .
Original, my query is like this
<code>strSQL = "SELECT " +
                " '" + strSearchingStartDate + "' AS SearchStartDate, '" + strSearchingEndDate + "' AS SearchEndDate, '" + strCurrentUserName + "' as WhoPrint, " +
                " machinelograwdata.MachineID , " +
                " machinelograwdata.Parameter1 AS 'Code', " +
                " machinelograwdata.Parameter42 AS 'Orders', " +
                " Temp2.HideStartTime AS StartTime, " +
                " machinelograwdata.EndTime, " +
                " UNIX_TIMESTAMP(machinelograwdata.EndTime) - UNIX_TIMESTAMP(Temp2.HideStartTime) AS Duration, " +
                " Temp.StartTime AS CutStartTime, " +
                " Temp.EndTime AS CutEndTime, " +
                " Temp.Duration AS CutDuration, " +
                " NULL AS NestingStartTime, " +
                " NULL AS NestingEndTime, " +
                " '0.00' AS NestingDuration, " +
                " '0.00' AS 'SupplierAream2', " +
                " ROUND(machinelograwdata.Parameter3 / 1000000, 2) AS 'GrossAream2', " +
                " ROUND(machinelograwdata.Parameter26 / 1000000, 2) AS 'NetAream2', " +
                " machinelograwdata.Parameter27 AS 'YieldPercen', " +
                " machinelograwdata.Parameter25 AS 'NoPiece', " +
                " machinelograwdata.Parameter24 AS 'Material', " +
                " machinelograwdata.Parameter44 AS 'Models', " +
                " ROUND(machinelograwdata.Parameter9 / 1000000, 2) AS 'Quantity0Area', " +
                " '0.00' AS 'Quantity1Area', " +
                " '0.00' AS 'Quantity2Area' " +
                " FROM " +
                " machinelograwdata " +
                " INNER JOIN catalogue" +
                " ON machinelograwdata.EventID = catalogue.CatalogueID " +
                " LEFT JOIN " +
                "   (SELECT MachineID, Parameter1, EndTime, StartTime,  UNIX_TIMESTAMP(EndTime) - UNIX_TIMESTAMP(StartTime) AS Duration " +
                "   FROM " +
                "     (SELECT machinelograwdata.MachineID, machinelograwdata.Parameter1, " +
                "         MAX(machinelograwdata.EndTime) AS EndTime, " +
                "         MIN(machinelograwdata.StartTime) AS StartTime " +
                "   FROM " +
                "     machinelograwdata, catalogue " +
                "   WHERE " +
                "     machinelograwdata.EventID = catalogue.CatalogueID " +
                "         AND catalogue.CatalogueGroup = 'EventDesc' " +
                "         AND StartTime >= '" + strSearchingStartDate + "' " +
                "         AND StartTime <= '" + strSearchingEndDate + "' " +
                "         AND EventID = '15' " +
                "         AND machinelograwdata.Parameter2 = '0' " +
                "   GROUP BY machinelograwdata.Parameter1, machinelograwdata.MachineID) M) Temp  " +
                " ON Temp.Parameter1 = machinelograwdata.Parameter1 " +
                "    AND Temp.MachineID = machinelograwdata.MachineID " +
                " LEFT JOIN " +
                "   (SELECT MachineID, Parameter1, MIN(StartTime)AS HideStartTime " +
                "   FROM machinelograwdata " +
                "   WHERE EventID = '13' " +
                "     AND machinelograwdata.StartTime <= '" + strSearchingEndDate + "' " +
                "     AND machinelograwdata.StartTime >= '" + strSearchingStartDate + "' " +
                "   GROUP BY MachineID, Parameter1) Temp2 " +
                " ON Temp2.Parameter1 = machinelograwdata.Parameter1 " +
                "    AND Temp2.MachineID = machinelograwdata.MachineID " +
                " WHERE catalogue.CatalogueGroup = 'EventDesc' " +
                "     AND machinelograwdata.StartTime <= '" + strSearchingEndDate + "' " +
                "     AND machinelograwdata.StartTime >= '" + strSearchingStartDate + "' " +
                "     AND EventID = '14' " +
                "     AND CONVERT(Parameter35, DECIMAL) <> 0 " +
                " ORDER BY machinelograwdata.MachineID , machinelograwdata.StartTime;  ";
</code>
my question is, is it possible for me to write the same query with MongoDB ?
and is there "View" concept on MongoDB? because I have another MySQL Report query using View.
I appreciate if you can have any suggestion or advice.
Thank you,
Thomas
Answer: MongoDB and MySQL are two very different database solutions. Both follow different approach in terms of maintaining data. MongoDB is NO SQL database means data stored in it is not bound with schema like data in MySQL databases.
You cannot able fetch data from MongoDB using SQL query. MongoDB has its own query engine (powered by Javascript) to fetch data.
Concept of view is not supported in MongoDB.
As you able to load data in MongoDB from MySQL using C#, I would recommend to check MongoDB official C# drivers for map reduce operations.
One approach would be to fetch data in memory and then build report. You might also find some online solutions to map SQL query to Mongo like this
Comment: Hi @Monk-Who-Code,
Thank you for your suggestion.
Look like, I will have to do homework to work on Reporting with MongoDB.

I think, I load MongoDB in Memory and handle it.
so, the performance is what I should take care.