text:
Q: boost python: initialize C++ class that expects a pointer from python I have a main C++ class Test of which member elements are continuously changed by other C++ classes. These other classes receive a pointer to the Test class in the constructor, which they should keep as a member. It is important that this is a pointer, and that all other classes all change the same Test object. A simplified version looks like this:
test.h
#ifndef TEST_H
#define TEST_H
class Test {
public:
    int a;
    Test();
    Test * get_ptr(void);
    int geta(void);
};
#endif // TEST_H

test.cpp
#include "test.h"
Test::Test() {this->a = 4;};
Test * Test::get_ptr(void) {return new Test;};
int Test::geta(void) {return a;};

changer.h
#ifndef CHANGER_H
#define CHANGER_H
#include "test.h"
class Changer {
public:
    Test * t_p;
    Changer(Test * t_ptr);
    void plus1(void);
};
#endif // CHANGER_H

changer.cpp
#include "changer.h"
Changer::Changer(Test * t_ptr) {t_p = t_ptr;};
void Changer::plus1(void) {t_p->a += 1;};

boost.cpp
#include "test.h"
#include "changer.h"
#include "boost/python.hpp"
using namespace boost::python;
BOOST_PYTHON_MODULE(pnt) {
    class_<Test>("Test")
        .def("get_ptr", &Test::get_ptr, return_value_policy<manage_new_object>())
        .def("geta", &Test::geta)
        ;
    class_<Changer>("Changer", init<Test*>())
        .def("plus1", &Changer::plus1)
        ;
}

This compiles fine, but when I use it in python I get a segmentation fault with this code:
In [1]: import pnt
   ...: t = pnt.Test()
   ...: t.geta()
   ...: c = pnt.Changer(t.get_ptr())
   ...: c.plus1()
   ...: t.geta()
   ...:
Out[1]: free(): invalid pointer
Aborted (core dumped)

I got the part for the pointer from https://wiki.python.org/moin/boost.python/PointersAndSmartPointers but I can't seem to get it to work. I would greatly appreciate some hints on how to do this.


text:
Q: Grails: detemine number of calls to vaious API Services I have this working grails app, and i want to determine how many calls various parts of it's API gets per time unit.
This app offers 100+ web services, and 10k+ open connections at any time, so it is pretty busy.
It's written in grails 1.3.6 (developed over 10 years).
My overall target is to gain knowledge about which interfaces are actually used and how often.
I see several poor possibilities:

*

*Log everything, parse the logs and 'grep -c'.... (Bad idea)

*tcpdump... (Bad idea)

*Increment global variables (thread safe) where i want to instrument it (least bad idea)

How do i get grails to tell me which services are called and how often?
...without killing performance?
Any ideas/pointers will be appreciated :-)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Closure memory leak patterns in JavaScript Which of following JavaScript snippets will leak memory?
snippet #1:
function foo(obj)
{
    var obj2 = {};
    $('#something').click(function() { alert(obj.id); } );
}

snippet #2:
function foo(obj)
{
    var obj2 = {}
    $('#something').click(function() { alert('obj was not used.'); } );
}

snippet #3:
function foo(obj)
{
    var obj2= {id: 1}
    bar(function() { alert(obj2.id); } );
}

function bar(func)
{
    var obj3 = {};
    func();
}

and which variables won't be collected by Garbage Collector?
How to fix leaks?

A: As given, none of those will create memory leaks.
Leaks are held by not releasing memory -- everything there gets released.
By the way, none of the code you are showing uses closures.
Now, here are a handful of ways that "leaks" can be created.
// Simple leak -- an array that never lets go of memory
var arrayThatNeverShrinks = [];
function doleak() {
  var s = "1234567890";
  arrayThatNeverShrinks.push(s);
  window.setTimeout(doleak, 500);
}
//start if off
doleak();

// This function leaks because bigVar is used -- and kept --
// inside of the anonymous function inside.
    //Another leak, using closures
    var leakingFunction = (function() {
      var bigVar = "1234567890";
      return function() {
        alert("Hi there");
        var keepBigVar = bigVar;
      }
    }());

A: Old question, but I have a couple of issues with the top-rated answer -

By the way, none of the code you are showing uses closures

The click handler in snippet one is very much a closure - it closes over the obj parameter that is passed to foo. Thus, the memory allocated for obj will not be released until foo is called again with a different object.
Not saying there's a leak here - just wanted to point out that snippet one does create a closure.
Also,

Leaks are held by not releasing memory -- everything there gets released

This is true for snippets #2 and #3, but not for snippet #1.


text:
Q: I want to edit specific item name in my inventory through accessing certain index, my problem is here I want to edit the item name by accessing a certain index, but my problem is when I try to edit the name of index 2
index 1 is editing not index 2
here is my output
if (choice2 == 1) {
    System.out.print("Enter Item name: ");
    String itm = scan.next();
    System.out.print("Enter Item unit: ");
    int unit = scan.nextInt();
    System.out.print("Enter Item quantity: ");
    int qty = scan.nextInt();
    item.add(new Materials(itm, unit, qty));
    System.out.println(itm + " " + unit + " " + qty + " Successfully added!");
    // edit item name
} else if (choice2 == 2) {
    System.out.println("----------------------");
    System.out.println("Edit Materials ");
    System.out.println("----------------------");
    System.out.print("Enter Item index: ");
    int item_index = scan.nextInt();
    System.out.print("Enter new name of the item: ");
    String newitem = scan.next();
    for (Materials m : item) {
        m.setItem_name(newitem);
        System.out.println("Item  ->" + m.getItem_name() + " Successfully updated! ");
        break;
    }// view all item in inventory

I want to edit name of the indexes.
here is the output
 (1) ADD MATERIALS
 (2) EDIT MATERIALS
 (3) VIEW MATERIAL
 (4) Exit
Enter your choice: 3
-------------------------------------------------------------------------
Unique_Id   Item_name       Unit        Quantity
-------------------------------------------------------------------------
1:      fish            2       312
2:      cangoods            3       123

-------------------------------------------------------------------------

 (1) ADD MATERIALS
 (2) EDIT MATERIALS
 (3) VIEW MATERIAL
 (4) Exit
Enter your choice: 2
----------------------
Edit Materials
----------------------
Enter Item index: 2
Enter new name of the item: python
Item  ->python Successfully updated!

 (1) ADD MATERIALS
 (2) EDIT MATERIALS
 (3) VIEW MATERIAL
 (4) Exit
Enter your choice: 3
-------------------------------------------------------------------------
Unique_Id   Item_name       Unit        Quantity
-------------------------------------------------------------------------
1:      python          2       312
2:      cangoods            3       123

-------------------------------------------------------------------------

 (1) ADD MATERIALS
 (2) EDIT MATERIALS
 (3) VIEW MATERIAL
 (4) Exit
Enter your choice:

A: Welcome to stackoverflow.com.
There is a small problem in the edit material for loop. You are always editing the first material and breaking the loop. You have to first find the Material object from the list and then update the same.
Check the sample below:
if (choice2 == 1) {
  System.out.print("Enter Item name: ");
  String itm = scan.next();
  System.out.print("Enter Item unit: ");
  int unit = scan.nextInt();
  System.out.print("Enter Item quantity: ");
  int qty = scan.nextInt();
  item.add(new Materials(itm, unit, qty));
  System.out.println(itm + " " + unit + " " + qty + " Successfully added!");
  // edit item name
} else if (choice2 == 2) {
  System.out.println("----------------------");
  System.out.println("Edit Materials ");
  System.out.println("----------------------");
  System.out.print("Enter Item index: ");
  int item_index = scan.nextInt();
  System.out.print("Enter new name of the item: ");
  String newitem = scan.next();
  for (Materials m : item) {
    if (m.getItem_index() == item_index) {
        m.setItem_name(newitem);
        System.out.println("Item  ->" + m.getItem_name() + " Successfully updated! ");
        break;
    }
  }// view all item in inventory
}

The difference is in for loop
if (m.getItem_index() == item_index) {
  m.setItem_name(newitem);
  System.out.println("Item  ->" + m.getItem_name() + " Successfully updated! ");
  break;
}

Since the definition of Materials class was not provided, so there might be a need of correcting the method call m.getItem_index() in above code.


text:
Q: Instrument a Windows 7 Bluetooth stack I'm working with various (mostly Bluetooth) development boards (ConnectBlue, Ubertooth, USRPs etc.) in order to research about Bluetooth communication behaviour at PHY level. In order to get some more insights I'm looking for a way to debug the Bluetooth stack on a Windows 7 Desktop computer. My use-case is relatively simple: I have custom baseband implementations, which establish connections with the Windows computer. I'd like to see everything the Bluetooth hardware/driver does.
I'm not sure how to approach this: I'd like to see when the Bluetooth Chip/Windows driver receives a Signal, and how it (the message) gets interpreted/formatted/passed through the various APIs concerned. Mostly this relates to kernel debugging.
Is there a way to display the state of the attached hardware in Windows in WinDBG? Maybe to perform (Kernel) API logging on the Bluetooth kernel service?
I hope somebody more familiar with device driver debugging and Windows Kernel services can give me some pointers here.

A: Since you don't appear to have gotten any hits on this, I'll post what I can.
I don't have any definite answers, but on the NTDebugging blog they often do hardware level debugging in windbg.
I.e.
http://blogs.msdn.com/b/ntdebugging/archive/2007/06/22/where-the-rubber-meets-the-road-or-in-this-case-the-hardware-meets-the-probe.aspx
To be honest this is going to require extensive knowledge not only of your hardware, but also of the deep internals of windows, and how the bluetooth stack is written, but the WDK would probably be a good place to start for understanding the bluetooth stack. I would also check out the blog for tips and tricks.
The other place to check and ask questions is http://osronline.com/ It's one of the better communities about device drivers, so they should have some reasonable tips on doing what you're trying to do.


text:
Q: How to display spinner or progress bar while image loading? I am making the react, next.js app on which I am displaying various images:

The user is clicking on the item from the list on the left, and it's getting three images on the right. The images are displaied based on next.js Image component:
            <Image
          src={visualizationData[0]}
          quality={50}
          alt="Zdjęcie oryginalne"
          width={600}
          height={600}
        />

Where visualizationData is a variable using the State Hook and returing 3 urls to photos that user wants to display:
const [visualizationData, setVisualizationData] = useState(getVisualizationData(props.history.model.name, props.history.dataLists[0].replace('img/', '')));

So it returns something like this:

Everything is working fine, but slow, because backend needs to convert .tif photos to .jpg and it takes like 3 seconds. I want to display for this 3 seconds a spinner or something similar to spinner instead of leaving the user with the old visualizations.
How to make it? I don't know how to check that photo is loaded or not, because I am only passing urls to the src prop of the Image component.
Here is a code of getVisualizationData(modelName, pathAndPhotoName):
    export function getVisualizationData(modelName, pathAndPhotoName) {
  const photoName = pathAndPhotoName.split('/').slice(-1)[0];
  const datasetPath = pathAndPhotoName.replace(`/${photoName}`, '');
  const visualizationData = [
    `${backendUrl}download/datasets/${datasetPath}/image/${photoName}`,
    `${backendUrl}download/datasets/${datasetPath}/mask/${photoName}`,
    `${backendUrl}download/models/${modelName}/Predictions/1/${photoName}`];
  return visualizationData;
}

It is converting the path to the photos and returning it in an array.

A: You can create a isLoading boolean. If isLoading is true, then show the Spinner. If not, then the data has been fetched and you can stop showing the spinner and start showing the pictures.
Please notice I don't have enough information about what getVisualizationData returns exactly. But basically, it should return a Promise resolved with the value fetched. So look at this code, get the idea and apply it.
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);

      const result = await getVisualizationData(props.history.model.name, props.history.dataLists[0].replace('img/', '')); //Please check this line
      setVisualizationData(result);
      setIsLoading(false);
    };
    fetchData();
  }, []);

Then in your component, you can render a spinner while isLoading is true. When it's false, then you render what you want to show:
return(
{isLoading ? (
        <SpinnerComponent />
      ) : (
        <div>
          //Render here your pictures
        </div>
      )}
)


text:
Q: iOS Navigationbar changes color during animation I'm having a strange graphical issue in iOS 7 on both, Simulator and Device.
I call a segue from the storyboard programmatically after a cell in a table view has been pressed:
[self performSegueWithIdentifier:@"showTerminDetailView" sender:self];

Then I inflate some values:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"showTerminDetailView"]) {
    Termin *termin = [self termineAtDate:self.currentday][[((TerminDayTableViewTableViewController *)self.terminTableViews[3]).tableView indexPathForSelectedRow].row];
    TerminDetailViewController *terminDetailViewController = segue.destinationViewController;
    terminDetailViewController.termin = termin;
}

}
The problem is that the right side of the navigation bar becomes darker during the animation:

Any help is welcome!

A: This is normal behavior. iOS7 navigation bar is translucent by default so you can see what is beneath it. Your issue could be one of the following

*

*The controller is set to only show beneath the navigation controller.

*You have self.navigationController.navigationBar.translucent = NO; on your pushed view controller so it is changing from translucent to non translucent

*You have self.edgesForExtendedLayout = UIRectEdgeNone; which is again moving the content down below which will make the nav controller not have content under it

*You have something showing in your pushed view controller behind the nav bar.


text:
Q: On iPhone 6 (and probably others) my simple HTML emails are display with stupidly large font I have a little application for a customer which sends some confirmation and info mails. This all works pretty good. However, when I view such an email on an iPhone it looks something like this: https://i.stack.imgur.com/GGyvo.png
I have tried it as follows, because this bring iphones safari, to not mess with the font. In the email (which on android devices looks beautiful) this won't work, somehow.
<html>
<style type="text/css">
    body, p{
        -webkit-text-size-adjust: none;
    }
</style>
<body>
<font face="arial" size="10px">
<%=in.temp.str7%>
</font>
</body>
</html>

A: Setting the viewport scale might help.
<meta name="viewport" content="width=device-width, initial-scale=1">

A: Try adding:
<meta name="viewport" content="width=device-width, maximum-scale=1, minimum-scale=1, user-scalable=no"/>

to head tag and moving the -webkit-text-size-adjust: none;to inline inside the body tag and font tag like so - <body style="-webkit-text-size-adjust: none;"> or heck do both and keep it in the header too.
Honestly the issue may come from other stylings or elements in your html affecting the scale (hopefully solved with viewport) so please keep in mind if you are importing content into this template from an outside source, it may be retaining styling that can affect how it is rendered.

A: You led the right way, but your tips alone did not work. I now have added a doctype and cleaned up everything a bit. I also got rid of the font tag (which, as I found out, is not supported in html 5 anymore).
Anyway, I do not know, what exactly solved the problem, but this is certainly a good base and working fine:
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <style>
        body{
            font-family: Arial,Helvetica, sans-serif !important;
            font-size: 14px !important;
            -webkit-font-smoothing: antialiased !important;
            -webkit-text-size-adjust: none !important;
        }
    </style>
<head>
<body>
    <%=in.temp.str7%>
</body>
</html>


text:
Q: Fundamental solution for a parabolic PDE with constant coefficents [Cross posting https://math.stackexchange.com/questions/1374384/fundamental-solution-for-a-parabolic-pde-with-costant-coefficents ]
I don't know if this question is more appropriate in Mathematics and not here, in this case I will delete it.
As it is well known, the fundamental solution of the heat equation is the function
$G(t,x)=\frac{1}{(4\pi t)^{n/2}}e^{-\frac{|x|^2}{4t}}$,
for all $t>0,x\in\mathbb{R}^n$.
I wonder if exists (and if you have same references) a similar explicit formula for the fundamental solution for a parabolic PDE with constant coefficents.
It is possible that it can be found in "Linear and quasilinear equation of parabolic type" by Ladyzenskaja, Solonnikov and Ural'ceva, but as I cant' consulte the book by now, I don't know.

A: For an operator of the form $L=\partial_t-\sum A_{jk}\partial_j\partial_k$, the fundamental solution is computed in Section 3.3 of Volume I of Hormander's treatise (The Analysis of Linear PDOs). I think one may try to extend the formula to include lower order terms by playing with it a little; for instance if $u$ solves $Lu=0$, then $v = e^{-at}u$ solves $Lv+av=0$, and similarly $v=(a_1x_1+\dots+a_nx_n)u$ solves an equation with additional first order terms.

A: Yes, it can be written out explicitly. Namely, for the operator
$$
\partial_t-\sum_{i,j=1}^na_{ij}\partial_{ij}-\sum_{i=1}^nb_i\partial_i-c,
$$
where $A=(a_{ij})>0$, $b=(b_1,\ldots,b_n)$,
$$
G(t,x)=\frac{1}{(4\pi t)^{n/2}|A|^{1/2}}\exp\left\{-\frac{(A^{-1}(x-bt),x-bt)}{4t}+ct\right\}.
$$
It can be obtained either via the Fourier transform wrt $x$ as in the case of the heat equation or making an affine change of variables in $\mathbb R^{n}$, reducing again to the heat equation.

A: A good place to start is the series of articles by P. Wagner and N. Ortner.  In addition to their constructive proof of the Malgrange-Ehrenpreis theorem on the existence of fundamental solutions for pde's with constant coefficients (AMS 116---MR 2510844), they have, in a series of previous papers, computed explicit solutions for many concrete examples.


text:
Q: Prevent interval being queued on multiple clicks I have created simple script with setInterval function and it is working fine on first button click, but if I click my button couple of times my interval is queued up! I have tried to solve this using one function with Jquery but then I cannot set my Intereval again. Is there a way to prevent this? Thank you!!
Fiddle example
My code:
 var changeClass=function(){

   if($('ul li.active').length==0){
   $('ul li:first').addClass('active');
   }
    else if($('.active').next().length==0){
       $('.active').removeClass('active');
       $('ul li:first').addClass('active');
    }
      else{
      $('.active').removeClass('active').next('li').addClass('active')
      }

 }

$(document).ready(function() {
 var intervalID;
    $(".button").click(function(){
    intervalID=setInterval(changeClass,1000);
    });

      $(".clear").click(function(){
      clearInterval(intervalID);
      });

});

A: So what are you actually trying to do? If you want the start button to be ignored when the interval is already set, write your click handler like this:
$(".button").click(function() {
    if(!intervalID) {
        intervalID = setInterval(changeClass,1000);
    }
});

If you want the start button to restart the interval then you can issue a click on the clear button every time the start button is clicked like this:
$(".button").click(function(){
    // Perform a click on the clear button
    $(".clear").click();

    intervalID = setInterval(changeClass,1000);
});

$(".clear").click(function(){
    clearInterval(intervalID);
});


text:
Q: Android App Development - App crashing after launching second activity I'm new to Android development and have been stuck on a issue for a few days now. Although a lot of people have got the same error answers submitted doesn't seem to help me. I have a splash screen on for 5 seconds, then launch my second activity which is just a webview. (Side note: If I don't use internet permission, second activity launches without a problem but I do get a web page not available screen, when I include the permission the app crashes after splash screen) Here are my codes;
MainActivity:
public class MainActivity extends Activity {

Thread newTimer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    newTimer = new Thread() {
        public void run(){
            try{
                sleep(3000);
                }

            catch(InterruptedException e){
                e.printStackTrace();
                }

            finally
            {
                Intent nw = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(nw);
                }
            }
        };
    newTimer.start();
   }
}

SecondActivity:
public class SecondActivity extends Activity {

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.secondlayout);

    String url = "http://ythaber.com/";
    WebView myWebWiew = (WebView) this.findViewById(R.id.webView1);

    myWebWiew.setWebViewClient(new WebViewClient());

    myWebWiew.getSettings().setJavaScriptEnabled(true);
    myWebWiew.loadUrl(url);

}

AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.idpturkey.ythaber2"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="13"
    android:targetSdkVersion="18" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >
    <activity
        android:name="com.idpturkey.ythaber2.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name="SecondActivity" >
    </activity>
</application>
</manifest>

Logcat:
E/AndroidRuntime(17034): FATAL EXCEPTION: main
Process: com.idpturkey.ythaber2, PID: 18216
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.idpturkey.ythaber2/com.idpturkey.ythaber2.SecondActivity}: android.view.InflateException: Binary XML file line #7: Error inflating class uses-permission
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)

secondlayout.xml:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<uses-permission android:name="android.permission.INTERNET" />

<WebView
    android:id="@+id/webView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</RelativeLayout>

Thanks in advance,
Devrim

A: Remove this line from your secondlayout.xml
<uses-permission
    android:name="android.permission.INTERNET" >
</uses-permission>

put it in your ManifestFile.xml in your project.
Your all Permission should be written in your Manifest.xml rather than in your_layout.xml
Hope it will help you.


text:
Q: Orchestration metadata in Matillion Is there any way I can get some information about an orchestration in Matillion expl when was it first created or who created it, using API
The only thing I find is data about the job like components and variables


text:
Q: libreoffice calc - vary column on drag-down Say I have some data in sheet Sheet_A on R2:AA2
I now want to reference that data in Sheet_B in B2:B10
How do I do that?
If I write
 Sheet_B.B2 = Sheet_A.R$2

And then drag down, it will result in
 Sheet_B.B3 = Sheet_A.R$2

But I want
 Sheet_B.B3 = Sheet_A.S$2

A: The OFFSET function works well here:
=OFFSET(Sheet_A.$R$2;0;ROW()-2)

Alternatively, use ADDRESS and INDIRECT:
=INDIRECT(ADDRESS(2;16+ROW();;;"Sheet_A"))

Documentation is at https://wiki.openoffice.org/wiki/Documentation/OOo3_User_Guides/Calc_Guide/Address,_Indirect,_Offset,_Index.


text:
Q: c# draw simple workflow diagram and mark current status I have a C# Winform project and I need to create a very simple linear workflow just to show visually what is the current status of the record.
Here is a sample image of what I want to do:

I will have to be able to draw the border on the item that is the actual status.
Any advice?

A: If you don't want to have to actually draw on it, you can do as rashfmnb suggested. Here is an example.
The setup:

*

*Form = MainForm

*Panel = pnlOuter [Padding = 5]

*Panel = pnlInner [Parent = pnlOuter, done by placing it inside the other one; Dock = Fill]

*Button = ToggleColor (to trigger the click event handler below)

The code:
public partial class MainForm : Form
{
  bool isOn = false;
  public MainForm()
  {
     InitializeComponent();
     pnlInner.BackColor = Color.LightGoldenrodYellow;
     pnlOuter.BackColor = Color.LightGoldenrodYellow;
  }

  private void ToggleColor_Click(object sender, EventArgs e)
  {
     if (isOn)
     {
        pnlOuter.BackColor = Color.LightGoldenrodYellow;
        isOn = false;
     }
     else
     {
        pnlOuter.BackColor = Color.Red;
        isOn = true;
     }
  }
}

This simple example just toggles the background of the outer panel. In your case, you would use different values to check what should be set and so forth.


text:
Q: Feeding variables into model in R I am building survival model and my code looks something like this:
library('survival')
my.model <- coxhp(Surv(time, event) ~ var_1+var_2+var_3+var_4+var_5, data =df)

The problem is that I have too many variables and set of variables is always changing, I wonder if it would be possible to create list of variables and feed it into model. Something like this:
 my.var <- c(var_1+var_2+var_3+var_4+var_5)
 my.model <- coxhp(Surv(time, event) ~ my.var, data =df)

I found similar post for linear model linear model solution, but do not know how adapt it to coxph.

A: You can use "." to mean "all variables not used already".  So for your example,
my.model <- coxph(Surv(time, event) ~ ., data = df[,c("time", "event", my.var)])

should work.


text:
Q: Download file from Thanks for this excellent resource, it has been of great assistance to me, but I am having a problem using excel VBA to download excel files from a remote server. I suspect it is something obvious that my code is lacking.
The problem I am having is that all the downloaded files are always 15KB in size, regardless of the size or content of the original file and all bear the same content which appears to be text simply copied from the host website, rather than the file I am trying to download. I have tried using various file extensions including CSV but the results are the same.
When I open the downloaded file excel says the file format and extension don't match and then says that, due to problems during load, the file is "missing file C:\remote\css\logon.css" and "missing file C:\remote\javascript\ramjsfx.menu.css", which is Greek to me.
    Sub DownloadFilefromWeb()

Const E_OUTOFMEMORY As Long = &H8007000E
Const E_DOWNLOAD_FAILURE As Long = &H800C0002

Dim InitialName As String
Dim Msg As String
Dim RegExp As Object
Dim RetVal As Long
Dim SaveName As String
Dim SavePath As String
Dim URL As String

URL = InputBox("Enter the download URL below.", "Download from Internet")
If URL = "" Then Exit Sub

Set RegExp = CreateObject("VBScript.RegExp")
RegExp.IgnoreCase = True
RegExp.Pattern = "^(.*\/)(.+)$"
InitialName = RegExp.Replace(URL, "$2")
Set RegExp = Nothing

If InitialName = "" Or InitialName = URL Then
MsgBox ("Error - Missing File Name")
Exit Sub
End If

SavePath = Application.GetSaveAsFilename(InitialName)
If SavePath = "" Then Exit Sub
'SavePath = "C:\Users\Rob's Laptop\Documents\Test\Test3.xls"
'URL = "https://remote.picosting.co.uk/Remote/fs/files.aspx?path=%5c%5cPISBS2011%5cfiles%5cRob%  20Shaw%27s%20test%20folder%5cTest1"

RetVal = URLDownloadToFile(0&, URL, SavePath, 0&, 0&)

Select Case RetVal
Case 0
Msg = "Download Successful"
Case E_OUTOFMEMORY
Msg = "Error - Out of Mmemory"
Case E_DOWNLOAD_FAILURE
Msg = "Error - Bad URL or Connection Interrupted"
Case Else
Msg = "Unknown Error - " & RetVal
End Select

MsgBox Msg

End Sub

Kind regards
Rob

A: URLDownloadToFile() is literally and simply downloading the .aspx page that is on the server - when accessed through a normal web broswer, that page does server side logic to obtain and download the Excel file you are trying to get. The css files it is complaining about are stylesheet files that are used to control the display of the .aspx page.
You will need to use something more complex than URLDownloadToFile() to save the file that you want, for example setting up an IE Application object as described here:
http://www.mrexcel.com/forum/excel-questions/502298-need-help-regarding-ie-automation-using-visual-basic-applications.html


text:
Q: WinDbg is asking for a particular version of mscordacwks.dll. Where can I find this? I am trying to read the crash dump file for a .NET 2.0 assembly using WinDbg and SOS.dll.
From reading around, I have understood that I have to copy sos.dll, mscorwks.dll and mscordacwks.dll into the windbg install directory.
So I did this, but WinDbg then told me that the copies from my own .Net directory are the wrong version.  WinDbg is looking for mscordacwks.dll_x86_x86_2.0.50727.4211.dll, and I have got mscordacwks.dll_x86_x86_2.0.50727.5420.dll
Here is the question: where do I find the correct versions of these files?
a) on the machine where the application that crashed was built
or
b) on the machine where the application crashed?
I found this site where you can see which .NET patch has which versions included, but I haven't managed to download the relevant patch (can't find it) so it occurred to me that copying the files from one of the affected machines would be quicker.

A: Either a or b will work, provided that .NET has not since been updated on either machine.  If I don't have a particular DAC file, I usually get it from the machine that crashed.  Remember to save every single DAC you ever encounter into a directory.  Then add this directory to your symbol path.  This will cause you to have less difficulty locating DACs as time goes on.


text:
Q: Python: How to sum numbers in text file with strings when meet conditions I'm doing an inventory system which require for me to print distribution list of particular item. If the particular item has distribute to the same hospital for more than 1 time, it need to sum the quantity together.
The code that i'm writing now only allow for me to print the distribution list, it won't sum the quantity together if the item code and hospital code is same. (Check with code but not name to sum it up) How can i make it sum up together if hospital code and item code is same?
I'm only allow to use list, dictionary and pandas are not allowed.
def search_functions():
      try:
            fhand = open("distribution.txt","r")
      except:
            print("You haven't distribute any item yet!\n")

      searchInput = input("\nEnter item code to search: ")
      print()
      for line in fhand:
            lines = line.strip()
            if searchInput.lower() in lines.lower():
                  print(lines)
                  continue
      print()
      fhand.close()
search_functions()

Inside the text file
first item is hospital code, second is name, 3rd is item code, 4th is item name and the last one is quantity.
distribution.txt text file
HSPT001,Care Medical Hospital,HC,Head Cover,9
HSPT001,Care Medical Hospital,HC,Head Cover,6
HSPT002,Community Health Service,HC,Head Cover,7
The output need to be like below, when the searchinput is HC
HSPT001, Care Medical Hospital, HC, Head Cover, 15
HSPT002, Community Health Service, HC, Head Cover, 7
instead of
HSPT001,Care Medical Hospital,HC,Head Cover,9
HSPT001,Care Medical Hospital,HC,Head Cover,6
HSPT002, Community Health Service, HC, Head Cover, 7

A: You can use defaultdict for this:
from collections import defaultdict
result = defaultdict(float)

with open("distribution.txt") as f:
    data = f.read().split("\n")
    data = [line.strip().lower() for line in data]

for line in data:
    elements = line.split(",")
    # ["HSPT001", "Care Medical Hospital", "HC", "Head Cover", "6"]
    if len(elements) != 5:
        continue
    item_code = elements[2].lower().strip() # "hc"
    quantity = float(elements[-1].strip()) # "6"
    result[item_code] += quantity

searchInput = input("\nEnter item code to search: ").strip().lower()
print(result.get(searchInput, 0))

If your are not allowed to use dict then just add quantity to a variable:
result = 0
for line in data:
    elements = line.split(",")
    # ["HSPT001", "Care Medical Hospital", "HC", "Head Cover", "6"]
    if len(elements) != 5:
        continue
    item_code = elements[2].lower().strip() # "hc"
    quantity = float(elements[-1].strip()) # "6"
    result += quantity

A: worked on your issue using pandas, and below code solves it:
import pandas as pd
# "hospital_code", "name","item_code","item_name","quantity"
data = pd.read_csv("distribution_list.txt",names=["hospital_code", "name","item_code","item_name","quantity"])
print(data.groupby(["hospital_code", "name","item_code","item_name"]).sum())

A: try it, use pandas
import pandas as pd

df = pd.read_table("distribution.txt text file", sep=",", names=["hospital_code", "name","item_code","item_name","quantity"])

group_df = df.groupby(["hospital_code", "name","item_code","item_name"]).sum().reset_index()

for idx, row in group_df.iterrows():
    for col in ["hospital_code", "name","item_code","item_name","quantity"]:
        print(row[col], end=" ")
    print()


text:
Q: NetBeans, XAMPP, Dropbox, Chrome - Could not access the URL through the external browser I'm a student learning web-developing. My IDE is NetBeans.
I'm having a problem concerning Chrome running NetBeans web-projects that are located in Dropbox. I have recently set my XAMPP htdocs location to my Dropbox for easy syncing through my desktop and laptop, and everything works fine with both IE and Firefox, but I get the "Could not access the URL through the external browser. Check the browser configuration." error if I try to run projects with Chrome.
The only modifications I have done to make Dropbox my "htdocs"-parent is editing the DocumentRoot and Directory properties (from: "C:/xampp/htdocs" to: "C:/Dropbox/webdev/htdocs").
Is this a security feature in Chrome? Or am I missing something strange, as it works in both IE and Firefox?
Thanks in advance for any suggestions!


text:
Q: Optimize serving of static files I have an app running on a windows webserver 2008. It generates thumbnails which are then cached on disk.
But loading these static thumbnail images takes a bit long, as I dont have a slow connection. For example, Firebug tells me that most thumbnails (size between 30 - 50 kb) take between 600 ms and 1.2 second to load. And almost the whole time is spent while "waiting for response". Therefore I suspect that the server is responding too slow. Is there a way to optimize the serving of static content via IIS 7?

A: Newer browsers (IE8, Chrome) have upped the max number of connections per server to 6 which is a good trend.
However, to get around the 2 connection limit (without requiring a browser config change) a trick you can use is to create multiple CNAMES (aliases) in dns that point to your web server.  Then in your app you generate the image tags with patterned (or random) HREFs that utilize all of your.  This tricks the browser into thinking that the images are coming from different sources and then will open more than 2 connections to your site at one time.  This won't necessarily help your serve time for a single image, but for your overall page load time it should provide you some relief.
You would need to consider a couple of things before employing this technique:

*

*How this would work with your application's caching mechanism.  You might end up with a much larger cache of your images

*You would need to pay attention the number of concurrent connections on your web server as it'll go up as the number of concurrent sessions remains the same

There are a ton of posts are there that explain this technique in detail.  Here is a good one from DevCentral:
The third greatest (useful) hack in the history of the Web

A: I'm not sure about IIS 7 but you should probably have the images loading from a different domain that way the browser can try to load them in parallel. A browser (depending on browser) will only try to load 2 files from 1 domain at a time. I believe firefox will try to load up to 6 files at once if they're from different domains. I also recommend lighter webservers for static content, like nginx. I realize it may not be the answer your looking for but maybe it will help.


text:
Q: How to remove stuff inside
A: var style = document.getElementsByTagName("style");
for(x=1;x<style.length;x++) {
    style[x].innerHTML=style[x].innerHTML.replace(/\<br\>/gi,"");
}

A: You can get stylesheet object by using document.styleSheets
Try this in console
for(i in document.styleSheets){
    if(!isNaN(i)){
         document.styleSheets[i].disabled = true;
    }
}


text:
Q: Equal to "=" characters randomy appearing in html POST data I am posting HTML data from an input text field called "textbox" to a backend application. The backend application (a django view) receives the data bu it is garbled with random equal to "=" characters in between, even though the html content in "textbox" before posting, was perfectly fine.
I suspect this is a problem with the encoding of POST data, but I am not able to figure out a solution to avoid this.
The textbox data can have any html data, and special characters like  <, >, {, }.
To summarize the problem:
The text data like:

This is a sample text

 This is the second line

becomes something like when I check the request.POST["textbox"] value in the Django view.

Th=is is a sample tex=t

 This i=s the se=cond line

Is anyone facing a similar problem because I did not find any related questions on stackoverflow? AFAIK, I think this problem might not have specificity to Django, but still adding the information, in case its useful.


text:
Q: Отображение переменных объекта в браузере с помощью jsp Есть такой сервлет
public class BotServlet extends HttpServlet {
private Bot bot;

@Override
public void init(ServletConfig servletConfig) throws ServletException {
    super.init();
    bot = Bot.getInstance();
    bot.setId(1);
    bot.setName("Amigo");
    bot.setSerial("777");
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Enter doGet");

    String action = request.getParameter("action");
    System.out.println(action);
    System.out.println(bot);
    request.setAttribute("bot", bot);
    switch (action == null ? "info" : action) {
        case "update":
            request.getRequestDispatcher("/WEB-INF/view/update.jsp").forward(request, response);
            break;
        case "info":
        default:
            request.getRequestDispatcher("/WEB-INF/view/bot.jsp").forward(request, response);
            break;
    }
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Enter doPost");

    request.setCharacterEncoding("UTF-8");
    String action = request.getParameter("action");

    if (action.equals("submit")) {
        bot.setId(Integer.parseInt(request.getParameter("id")));
        bot.setName(request.getParameter("name"));
        bot.setSerial(request.getParameter("serial"));
    }

    request.setAttribute("bot", bot);
    request.getRequestDispatcher("/WEB-INF/view/bot.jsp").forward(request, response);

}

}
Так же есть jsp страницы в которые я передаю объект bot. Моя проблема заключается в том что я не могу достать данные (значения переменных) этого объекта. Вот пример как я это делаю в самом jsp.

<jsp:useBean id="bot" scope="request" type="com.javamaster.model.Bot"/>

        ID: ${bot.id} | Name: ${bot.name} | Serial number: ${bot.serial}
        Update

А на выходе получаю следующее. Хотя ожидаю что будет ID:1 Name: Amigo и так далее

Смысл программы такой - 2 jsp в одном я ввожу данные(меняю)  в другом отображается. Сами значения меняются (проверил с помощью консоли), а вот почему не правильно отображается не могу понять.

A: Решил проблему следующим образом. В maven добавил зависимость
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>

Так же в web.xml добавил следующие строки

xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  version="2.5">

Информацию по тому что именно прописывать в web.xml нашел тут https://stackoverflow.com/tags/jstl/info. Если у кого-то будет такая проблема, ищите по ссылке выше подробности. Все получится!


text:
Q: Gaussian integrals over the space of symmetric matrices Let $S\in\mathcal S_N$ be a $N\times N$ symmetric matrix over the reals, and introduce the (normalised) gaussian measure
$$
\mathrm d\mu(S):=2^{-\frac 12N}\pi^{-\frac14N(N+1)}\exp\left[-\frac12\operatorname{tr}(S^2)\right]\mathrm dS
$$
where
$$
\mathrm dS:=\prod_{i\le j\le N}\mathrm dS_{ij}
$$
I am interested in the integral
$$
p_n(N):=\int_{\mathcal S_N}\operatorname{tr}(S^{2n})\mathrm d\mu(S)
$$
which is in fact a polynomial in $N$ of degree $n+1$. It can be shown that the coefficients of these polynomials are given by a certain sum over all possible gluings of the $2n$-star (cf. Ref.1, exercise 3.2.12).
These polynomials can be computed explicitly (for example, with the aid of the Weyl integration formula, cf. this MO post, although I found it much more efficient to compute the integrals explicitly by means of Wick's theorem). The first few read
\begin{equation}
\begin{aligned}
p_0(n) &= n\\
p_1(n) &= \frac12 n (1 + n)\\
p_2(n) &= \frac14 n (5 + 5 n + 2 n^2)\\
p_3(n) &= \frac18 n (41 + 52 n + 22 n^2 + 5 n^3)\\
p_4(n) &= \frac{1}{16} n (509 + 690 n + 374 n^2 + 93 n^3 + 14 n^4)\\
p_5(n) &=
 \frac{1}{32} n (8229 + 12143 n + 7150 n^2 + 2290 n^3 + 386 n^4 + 42 n^5)\\
p_6(n) &=
 \frac{1}{64} n (166377 + 258479 n + 167148 n^2 + 58760 n^3 + 12798 n^4 +
    1586 n^5 + 132 n^6)
\end{aligned}
\end{equation}
My question: is there any known formula to compute these polynomials efficiently (say, in the form of an explicit recurrence relation, or a closed-form generating function, etc.)?
Note that $p_n(1)=(2n-1)!!$, which is not too difficult to prove.
If we integrate over hermitian matrices instead of symmetric matrices, the answer to the question above is affirmative (the recurrence relation and the generating functional can be found in Ref.1 §1). In the symmetric case, the best I could find was Ref.2, which is not nearly as explicit as I would like (if the recurrence relation or the explicit generating function for $p_n(N)$ is somewhere there, I couldn't find it myself).
As per Wick's theorem, I am lead to believe it should be useful to express the polynomials $p_n(N)$ using as a basis the bionomial coefficients instead of the powers $\{1,N,N^2,\dots\}$:
$$
p_n(N):=\sum_{j=1}^{n+1}\frac{1}{2^n}\alpha_{n,j}\binom{N}{j}
$$
where the coefficients can be arranged in a Pascal-like triangle:
\begin{equation}
\begin{aligned}
&\hspace{127pt}1\\
&\hspace{100pt}1\hspace{50pt} 1\\
&\hspace{80pt}6\hspace{40pt} 11\hspace{40pt} 6\\
&\hspace{60pt}60\quad\qquad 153\quad\qquad 156\quad\qquad 60\\
&\qquad\qquad840\qquad 2673\qquad 3846\qquad 2796\qquad 840\\
&\qquad15120\quad 56715\quad 102960\quad 106560\quad 60960\quad 15120\\
&332640\ 1420695\ 3066390\ 4032360\ 3304080\ 1568880\ 332640\\
\end{aligned}
\end{equation}
I couldn't find a recurrence relation for the $\alpha_{n,j}$ coefficients either, so I'm not sure this representation is actually more useful than the previous one, but I wanted to include it as well just in case. Note that the triangle is almost symmetric, so that may mean something.
Note: OEIS was unable to recognise any of these sequences/polynomials. Could it be useful to submit them?

References.

*

*Sergei K. Lando, Alexander K. Zvonkin - Graphs on Surfaces and Their Applications (Springer, 2004).

*I.P. Goulden, D.M. Jackson, Maps in locally orientable surfaces, and integrals over real symmetric matrices, Canadian J. Math. 49, 1997, 865-882.

A: A recursion formula for the moments of the Gaussian orthogonal ensemble, M. Ledoux (2009).
The desired recursion formula for the moment $b_p^N\equiv E\,[\,{\rm tr}\,(S_N^{2p})]$ is

I notice a difference in normalization, you'll want to divide $b_p^N$ by $2^p$.


text:
Q: Android getString() with multilingual not working I've create a short test Application with the following pre conditions:
My Smartphone run on 7.0 (and up). I've setup multiple languages in my settings English (United States) & Deutsch (Deutschland).
This is my App setup:
compile-, target-, min-SdkVersion 24
String-Resources:

The content from strings.xml ("default") is:
<resources>
    <string name="app_name">Test</string>
    <string name="test">default</string>
</resources>

And the content from string.xml (values-en-rGB) is:
<resources>
    <string name="test">GB Fallback!</string>
</resources>

The MainActivity have only a onCreate() with the following code:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final String string = getString(R.string.test);
    Log.d("TestString", string);

    final LocaleList locaList = LocaleList.getDefault();
    for (int i = 0; i < locaList.size(); i++) {
        Log.d("AvailableLocale", locaList.get(i).toLanguageTag());
    }
}

When I run my App I expect the output from "TestString" is GB Fallback!. Why? Because Android 7.0 support multilingual. * (See update)
Instead of GB Fallback! I get always the default output. That means default.
The output from AvailableLocale is always up to date with the setup from my phone settings.
So. Why I got default from getString(R.string.test). Do I miss understand something with the multilingual stuff from the Android docs?
* Update
Why I claim I got GB Fallback!. The reason is the multilingual feature. The documentation shows a nice table:

I will try it to map it to my situation:
(Sorry, my Image is wrong. I don't mean de-GB. It's en-GB of course)

So, what is wrong here?


text:
Q: Difference Between controller and controller.content I have an ArrayController and was using {{#each item in controller}} to iterate over the items in the controller. This was working fine while using the same controller however after switching to another route I ran into some weird behavior which stopped the items from being rerendered. Switching to {{#each item in controller.content}} solved this problem. However I am not sure how this even happened.
What's the difference between controller and controller.content in an each expression (or any where else).

A:
What's the difference between controller and controller.content in an each expression (or any where else).

Basically there is no difference, for example when using an ArrayController which extends from ArrayProxy, then inside the controller this.pushObject(obj) will behave the same as doing this.get('content').pushObject(obj). See here for reference.
But IMO you are better of using model everywhere e.g. {{#each item in model}}.
Check also this answer which I guess will be useful: Ember iterations: when to use #each User, #each user in controller, #each user in model, etc
Hope it helps.


text:
Q: Snowflake - While Loop using Current_Date In Snowflake I'm attempting to run a while loop where there is a start date, and the code will loop until it equals today's date.
I'm fairly new to snowflake itself.
First idea was in the while loop check if the variable date was less than the current date. I couldn't seem to get this working even with the Current_Date on it's own or attributed to a variable
 execute immediate $$
    declare
      opdate := '2022-04-29';
      currdate := Current_Date;
     begin
       while (opdate <=currdate) do
        opdate :=dateadd(day,1,opdate);
      end while;
    end;
    $$
    ;

'CURRDATE' cannot have its type inferred from initializer

The second option was to use a datediff to see if the difference between the variable and current_date was equal to zero
execute immediate $$
    declare
      opdate := '2022-04-29';
        currndate := 1;
     begin
       while (currndate<=0) do
        currndate := datediff(day, opdate, CURRENT_DATE);
        opdate :=dateadd(day,1,opdate);
      end while;
    end;
    $$
    ;

error line 7 at position 39 invalid identifier 'CURRENT_DATE'

I've tried many different variants of this code, even use for each and if loops with no luck. I'm seemingly unable to check if a variable is less than the current date. Any help/pointers would be much appreciated.
Without having Current_Date, and having a set start and end date, it appears to run fine
execute immediate $$
declare
  opdate := '2022-04-29';
  currdate := '2022-05-03';
 begin
   while (opdate <=currdate) do
    opdate :=dateadd(day,1,opdate);
  end while;
end;
$$
;

A: Can you try CURRENT_DATE() with the open and close parens? see block below
 execute immediate $$
    declare
      opdate := '2022-04-29';
      currdate := Current_Date();
     begin
       while (opdate <=currdate) do
        opdate :=dateadd(day,1,opdate);
      end while;
     return opdate; --added this return
    end;
    $$
    ;


text:
Q: Solving an expectation related to CIR process I encounter the following question

Let $X$ satisfy the SDE $$dX_s=k(\alpha-X_s)ds+\sigma\sqrt{X_s}dW_s$$ for $s\geq t$ with $X_t=x$, where $k,\alpha,\sigma$ are positive constants.  Find the conditional expectation $$u(t,x)=\mathbb{E}[exp(\beta X_T)|\mathcal{F}_t]$$, where $\beta$ is a positive constant satisfying $k-\sigma^2\beta/2>0$.

$X$ obviously follows a CIR process and therefore $X_t$ has a chi-squared distribution and $u(t,x)$ is just the mgf of a chi-sq distribution (times some deterministic function).  My question is: In an exam, if we don't know the density function of $X_t$, nor the mgf of $X_t$, is there any other way to solve for $u(t,x)$?


text:
Q: How to access the system call from user-space? I read some paragraphs in LKD1
and I just cannot understand the contents below:

Accessing the System Call from User-Space
Generally, the C library provides support for system calls. User applications can pull in function prototypes from the standard headers and link with the C library to use your system call (or the library routine that, in turn, uses your syscall call). If you just wrote the system call, however, it is doubtful that glibc already supports it!
Thankfully, Linux provides a set of macros for wrapping access to system calls. It sets up the register contents and issues the trap instructions. These macros are named _syscalln(), where n is between zero and six. The number corresponds to the number of parameters passed into the syscall because the macro needs to know how many parameters to expect and, consequently, push into registers. For example, consider the system call open(), defined as
long open(const char *filename, int flags, int mode)

The syscall macro to use this system call without explicit library support would be
#define __NR_open 5
_syscall3(long, open, const char *, filename, int, flags, int, mode)

Then, the application can simply call open().
For each macro, there are 2+2×n parameters. The first parameter corresponds to the return type of the syscall. The second is the name of the system call. Next follows the type and name for each parameter in order of the system call. The __NR_open define is in <asm/unistd.h>; it is the system call number. The _syscall3 macro expands into a C function with inline assembly; the assembly performs the steps discussed in the previous section to push the system call number and parameters into the correct registers and issue the software interrupt to trap into the kernel. Placing this macro in an application is all that is required to use the open() system call.
Let's write the macro to use our splendid new foo() system call and then write some test code to show off our efforts.
#define __NR_foo 283
__syscall0(long, foo)

int main ()
{
        long stack_size;

        stack_size = foo ();
        printf ("The kernel stack size is %ld\n", stack_size);
        return 0;
}

What does the application can simply call open() mean?
Besides, for the last piece of code, where is the declaration of foo()? And how can I make this piece of code compilable and runnable? What are the header files I need to include?
__________
1 Linux Kernel Development, by Robert Love.
PDF file at wordpress.com (go to page 81); Google Books result.

A: At first I would like to provide some definition of system call. System call is a process of synchronous explicit requesting of the particular kernel service from the user space application. Synchronous mean that the act of system call is predetermined by executing instructions sequence. Interrupts is an example of asynchronous system service request, because they arrive to the kernel absolutely independently from the code executing on processor. Exceptions in the contrast to system calls are synchronous but implicit requests for the kernel services.
System call consist from four stages:

*

*Passing control to the particular point in kernel with switching processor from user mode to kernel mode and returning it back with switching processor back to the user mode.

*Specifying of id of the requested kernel service.

*Passing of parameters for the requested service.

*Capturing the result of the service.

In general, all these actions can be implemented as a part of one big library function which makes a number of auxiliary actions before and/or after actual system call. In this case we can say that the system call is embedded in this function, but the function in general isn't a system call. In another case we can have a tiny function which makes only this four steps and nothing more. In this case we can say that this function is a system call. Actually you can implement the system call itself by manual implementation of all four stages mentioned above. Note, that in this case you will be forced to use Assembler, because all this steps are entirely architecture-dependent.
For example, Linux/i386 environment has next system call convention:

*

*Passing control from user mode to kernel mode can be done either by software interrupt with number 0x80 (assembly instruction INT 0x80) or by SYSCALL instruction (AMD) or by SYSENTER instruction (Intel)

*Id of the requested system service is specified by the integer value stored in EAX register during entering in the kernel mode. Kernel service id must be defined in the form _NR. You can find all system service ids in Linux source tree on path include\uapi\asm-generic\unistd.h.

*Up to 6 parameters can be passed through registers EBX(1) , ECX(2), EDX(3), ESI(4), EDI(5), EBP(6). The number in brackets is a sequential number of the parameter.

*Kernel returns the status of the service performed in the EAX register. This value usually used by glibc to setup errno variable.

In modern versions of Linux there is no any _syscall macro (as far I know). Instead, glibc library, that is a main interface library of the Linux kernel, provides a special macro - INTERNAL_SYSCALL, which expands into a small piece of code populated by inline assembler instructions. This piece of code is targeted to a particular hardware platform and implements all stages of system call, and due to this, this macro represents a system call itself. There is also another macro - INLINE_SYSCALL. The last one macro provides glibc-like error handling, in accordance to which on failed system call -1 will be returned and the error number will be stored in errno variable. Both macros are defined in sysdep.h of glibc package.
You can invoke a system call in the next way:
#include <sysdep.h>

#define __NR_<name> <id>

int my_syscall(void)
{
    return INLINE_SYSCALL(<name>, <argc>, <argv>);
}

where <name> must be replaced by the syscall name string, <id> - by the wanted system service number id, <argc> - by the actual number of parameters (from 0 to 6) and <argv> - by actual parameters separated by commas (and started by comma if parameters are present).
For example:
#include <sysdep.h>

#define __NR_exit 1

int _exit(int status)
{
    return INLINE_SYSCALL(exit, 1, status); // takes 1 parameter "status"
}

or another example:
#include <sysdep.h>

#define __NR_fork 2

int _fork(void)
{
    return INLINE_SYSCALL(fork, 0); // takes no parameters
}

A: Minimal runnable assembly example
hello_world.asm:
section .rodata
    hello_world db "hello world", 10
    hello_world_len equ $ - hello_world
section .text
    global _start
    _start:
        mov eax, 4               ; syscall number: write
        mov ebx, 1               ; stdout
        mov ecx, hello_world     ; buffer
        mov edx, hello_world_len
        int 0x80                 ; make the call
        mov eax, 1               ; syscall number: exit
        mov ebx, 0               ; exit status
        int 0x80

Compile and run:
nasm -w+all -f elf32 -o hello_world.o hello_world.asm
ld -m elf_i386 -o hello_world hello_world.o
./hello_world

From the code, it is easy to deduce:

*

*eax contains the syscall number, e.g. 4 for write. Full 32-bit list on kernel source at: https://github.com/torvalds/linux/blob/v4.9/arch/x86/entry/syscalls/syscall_32.tbl#L13

*ebx, ecx and edx contain the input arguments. Those should be deducible from the signature of each syscall in the kernel source. See also: What are the calling conventions for UNIX & Linux system calls on x86-64 and Linux system call table or cheetsheet in assembly language

*the return value contains mostly error codes and goes to eax (not shown in this code for simplicity)

*int 0x80 makes the call, although there are now better methods: What is better "int 0x80" or "syscall"?
Of course, assembly will get tedious quickly, and you will soon want to use the C wrappers provided by the glibc / POSIX whenever you can, or the SYSCALL macro when you can't.

A: You first should understand what is the role of the linux kernel, and that applications interact with the kernel only thru system calls.
In effect, an application runs on the "virtual machine" provided by the kernel: it is running in the user space and can only do (at the lowest machine level) the set of machine instructions permitted in user CPU mode augmented by the instruction (e.g. SYSENTER or INT 0x80 ...) used to make system calls. So, from the user-level application point of view, a syscall is an atomic pseudo machine instruction.
The Linux Assembly Howto explains how a syscall can be done at the assembly (i.e. machine instruction) level.
The GNU libc is providing C functions corresponding to the syscalls. So for example the open function is a tiny glue (i.e. a wrapper) above the syscall of number NR__open (it is making the syscall then updating errno). Application usually call such C functions in libc instead of doing the syscall.
You could use some other libc. For instance the MUSL libc is somhow "simpler" and its code is perhaps easier to read. It also is wrapping the raw syscalls into corresponding C functions.
If you add your own syscall, you better also implement a similar C function (in your own library). So you should have also a header file for your library.
See also intro(2) and syscall(2) and syscalls(2) man pages, and the role of VDSO in syscalls.
Notice that syscalls are not C functions. They don't use the call stack (they could even be invoked without any stack). A syscall is basically a number like NR__open from <asm/unistd.h>, a SYSENTER machine instruction with conventions about which registers hold before the arguments to the syscall and which ones hold after the result[s] of the syscall (including the failure result, to set errno in the C library wrapping the syscall). The conventions for syscalls are not the calling conventions for C functions in the ABI spec (e.g. x86-64 psABI). So you need a C wrapper.


text:
Q: How do I bind data from SQL Server to an HTML page.? I want to bind/show data from sql server into a .html page by using javascript,AJAX,jquery but without using c#,php,vb.net etc.... can anyone plz help by posting some reference links or by posting the code itself..

A: Maybe with node.js
There are many examples out there, one of them:
http://blog.codeship.io/2014/04/22/leverage-sql-server-with-node-js-using-edge-js.html


text:
Q: Checkboxes have no "padding" on IE11 I cannot manage to apply "padding" to checkboxes on IE11, so that they behave the same as on IE10.
On IE10, the computed style for checkboxes was:
width: 13px;
height: 13px;
padding: 3px;
margin: 0;

On IE11, it is now:
width: 13px;
height: 13px;
padding: 0;
margin: 3px;

Although the checkboxes have the same size on both browsers, their behaviour has slightly changed. On IE10, the 3 pixels padding was causing the checkbox to "hover" when passing the mouse 3 pixels around the edges of the box. This is no longer the case on IE11, reducing the clickable area by that many pixels on each side.
I have tried applying the same style as on IE10 to the checkboxes, without any success (see http://jsfiddle.net/LSjb4/). The padding seems to be ignored. I've also tried playing with the width and height (as you would do on Chrome for instance), but this is causing the box to visually stretch.
Can anyone think of a pure CSS solution to get the same behaviour as IE10, retaining the native look of the checkbox (no image please)?
NOTE: please spare the "why are you trying to do that, it's bad for user experience etc." comments. Consider it as a technical challenge with no other purpose than the satisfaction to solve it :)

A: http://jsfiddle.net/8xmpw/
HTML
<label for="ie11" class="ie11">
    <input type="checkbox" id="ie11" />
</label>

CSS
.ie11 {
    padding: 3px;
}
.input[type=checkbox] {
    vertical-align:bottom;
}

This create a 3px padding area around the label box that allow you to click checkbox without hover entirely into the checkbox.
But this leads another problem that there is a small margin where IE11 has default margin preset. (I am guessing 1px top, 3px bottom)
I think the best you can do is using vertical-align to make either top or bottom border or checkbox clickable;

A: IMHO:
IE 10 rectangle checkbox perceived as content and 'padding' showed as distance out rectangle.
IE 11 as content perceived contents inside the rectangle and 'padding' just ignor.
Google Chrome browser also behives as IE 11 and ignore padding for checkbox.
For the same display your page in IE10 and in IE11 you must don't use padding for checkbox.
Simple solution is force IE11 simulate IE10 with through use
<meta http-equiv="X-UA-Compatible" content="IE=10">

P.S.
I also was unpleasantly surprised when discover that different behaviour in IE11 and IE10.
I am using Bootstrap.css which inside had classes .checkbox-inline and .checkbox.
If use these css classes, the boxes moved down relatively to label(.control-label).
.form-horizontal .control-label,
.form-horizontal .radio,
.form-horizontal .checkbox,
.form-horizontal .radio-inline,
.form-horizontal .checkbox-inline {
  padding-top: 7px;
  margin-top: 0;
  margin-bottom: 0;
}

For the same display in IE10 and IE11 I rewrite this classes (of course in other css file)
.form-horizontal .checkbox,
.form-horizontal .checkbox-inline {
  padding-top: 0;
  margin-top: 0;
  margin-bottom: 0;
}

I know that my english isn't so good, but i hope you are understood!-)

A: I met the same problem recently, and solved by wrapping around <checkbox> by <span> (jQuery required)
Then move the class of <checkbox> up to the <span>, and defined some special styles for ie11
// IE11 or above
if(!!(navigator.userAgent.match(/Trident/) && ! navigator.userAgent.match(/MSIE/))){
    $(function(){
        $("input[type=checkbox]").wrap(function(){
            return "<span class='" + $(this).attr("class") + " ie11'>";
        });
        $("input[type=checkbox]").removeClass();
    });
}


text:
Q: "Variably modified 'variable_name' at file scope" with size defined in macro I know there is some questions related to this error:
thread1, thread2, thread3, thread4,...
The difference is, I don't use variables to define the size, but macros.
Here is what I do:
#define     SIZE_A      250                      // Real world value
#define     SIZE_B       80                      // Real world value
#define     SCALE         0.25                   // Real world value
#define     TOTAL_A     (uint16_t)(SIZE_A/SCALE)
#define     TOTAL_B     (uint16_t)(SIZE_B/SCALE)
#define     TOTAL       TOTAL_A*TOTAL_B

#define     SIZE_1      (uint16_t)(TOTAL*0.3)

#define     SIZE_2      4000

typedef struct {
    toto_t  toto[TOTAL_A][TOTAL_B];
    foo_t   foo[SIZE_1][SIZE_2];
} bar_t;

As you can see, I've got three macros (SIZE_A, SIZE_B, SCALE) which represent real things. From those I define the sizes (TOTAL_A, TOTAL_B) of a 2 dimensional array (toto_t toto), and the total number of cells in this array (TOTAL). Then I take a piece of that total (SIZE_1) to define the size of an other array I want to create (foo_t foo).
This way gcc throw the error: Variably modified 'foo' at file scope. So, I looked at the preprocessor output:
typedef struct {
    toto_t toto[(uint16_t)(250/0.25)][(uint16_t)(80/0.25)];
    foo_t  foo[(uint16_t)((uint16_t)(250/0.25)*(uint16_t)(80/0.25)*0.3)][4000];
} bar_t;

As we can see, the preprocessor is doing is job well. All macros are replaced by the literal value. So there is only constant values in the array size.
My question
Why gcc can not compute the sizes of the arrays? And is there an option to force it to do the computation?
I compile with this option -O3 -Wall -Wextra -Werror.
Testing:
Create a test.h and put the code I posted and add typedef uint16_t toto_t; typedef uint16_t foo_t; at the begining. And create a test.c file with:
#include <stdio.h>
#include <inttypes.h>

#include "test.h"

int main() {
    printf("hello world\n");

    return 0;
}

A: The problem here is the floating value of SCALE.
You can avoid it using fixed point value:
#define     SIZE_A      250                      // Real world value
#define     SIZE_B       80                      // Real world value
#define     SCALE         25                   // Real world value
#define     TOTAL_A     (SIZE_A*100/SCALE)
#define     TOTAL_B     (SIZE_B*100/SCALE)
#define     TOTAL       TOTAL_A*TOTAL_B

#define     SIZE_1      (TOTAL*3/10)

#define     SIZE_2      4000

typedef struct {
    toto_t  toto[TOTAL_A][TOTAL_B];
    foo_t   foo[SIZE_1][SIZE_2];
} bar_t;

This answer will give you all information about C standard rules.


text:
Q: Behavior of Path.toRealPath() in Java with more than one level of symbolic link what is the behavior of:
Path.toRealPath()

when there is more than one level of symbolic links? I am debugging a program remotely for a friend who is on Linux, and I suspect that he has more than one symbolic links levels.
I am currently doing:
Path path = Path.get(uri);
if (Files.isSymbolicLink(path)) {
   path = path.toRealPath();
   uri = path.toURI();
}

But maybe I should do something like that:
Path path = Path.get(uri);
while (Files.isSymbolicLink(path)) {
   path = path.toRealPath();
}
uri = path.toURI();


text:
Q: Validate Customer Name array with regex conditions in java I have an requirement to validate the customer name, with few conditions in java (validate only with regular expression). The customer name will be in string array and passed to a method. The validateCustomer(String[] names) should validate the customer name and return only the valid customer names in array. The criteria for validating the customer names are as below.

*

*The name can contain only alphabets and spaces.

*Each word should be separated by a space and the name should not start or end with a space.

*The first character of each word of the name should be an upper case alphabet.

*Special characters should not be allowed.

*The length of the name should be between 2 and 75 characters.

Since the conditons can be updated later i need only regex validation
and not using any other methods like String.length().

I tried with few regex, but failing with some conditions.
A Sample tried
[((([A-Z][a-zA-Z])([+\\s]?[A-Z][a-zA-Z]*))]{2,75}

A: You can use
^(?=[a-zA-Z\\h]{2,75}$)[A-Z][a-zA-Z]*(?:\\h+[A-Z][a-zA-Z]*)*$

*

*^ Start of string

*(?=[a-zA-Z\\h]{2,75}$) Assert 2-75 chars a-zA-Z or a horizontal space

*[A-Z][a-zA-Z]* Match an uppercase char A-Z and optional chars a-zA-Z

*(?:\\h+[A-Z][a-zA-Z]*)* Repeat the previous preceded by 1+ horizontal spaces

*$ End of string

Regex demo
If you want a single space:
^(?=[a-zA-Z ]{2,75}$)[A-Z][a-zA-Z]*(?: [A-Z][a-zA-Z]*)*$

Regex demo

A: Your regex is wrong:
┌─ Definitely wrong!! Remove this
│               ┌─ Missing '*' to allow 1 to many words
│               │   ┌ '+' should not be allowed
│               │   │  ┌ Only space allowed, not other whitespace characters
│               │   │  │ ┌ Space is required between words, so remove '?'
│               │   │  │ │              ┌ Missing '*' to allow 1 to many words
│               │   │  │ │              │ ┌ Definitely wrong!! Remove this
│               │   │  │ │              │ │
[((([A-Z][a-zA-Z])([+\\s]?[A-Z][a-zA-Z]*))]{2,75}

What you want:
┌─ Must be 2-75 characters long (positive lookahead)
│          ┌─ Word must be uppercase letter
│          │    ┌─ followed by 0 or more letters
│          │    │        ┌─ followed by 0 or more words separated by single space
(?=.{2,75})[A-Z][a-zA-Z]*(?: [A-Z][a-zA-Z]*)*

The above regex must be used with matches(). If to be used with find(), it needs ^ and $ anchors.
The above regex only allows A-Z letters. For support of international letters like ñ, use this instead:
(?=.{2,75})\p{Lu}\p{L}*(?: \p{Lu}\p{L}*)*

Remember to double the \ when used in a Java string literal.


text:
Q: Modal Enzyme mount unit test: MutationObserver is not defined I'm trying to make a unit test for a react modal:
import React from "react";
import { mount } from "enzyme";
import Modal from ".";
import "wicg-inert";
import "animate.css";

describe("Modal component", () => {
  describe("When props is missing", () => {
    it("should raise an exception", () => {
      expect(() => mount(<Modal />)).toBeDefined();
    });
  });
});

It Fails with this message:
Test suite failed to run
ReferenceError: MutationObserver is not defined

  4 | import classnames from "classnames";
  5 | import Button, { ButtonGroup } from "components/Button";
> 6 | import "wicg-inert";
  7 | import "animate.css";
  8 |
  9 | import "./Modal.scss";

  at new InertManager (node_modules/wicg-inert/dist/inert.js:537:28)
  at node_modules/wicg-inert/dist/inert.js:792:22
  at node_modules/wicg-inert/dist/inert.js:2:66
  at Object.<anonymous> (node_modules/wicg-inert/dist/inert.js:5:2)
  at Object.<anonymous> (src/components/Modal/Modal.jsx:6:1)
  at Object.<anonymous> (src/components/Modal/index.mjs:1:318)
  at Object.<anonymous> (src/components/Modal/Modal.test.js:3:32)

My impression is that is failing because of limitation with Enzyme simulating the DOM. Can it be solved with react-test-library? Or with Enzyme itself?


text:
Q: Spring AOP :- Passing method parameters dynamically to advice My ServiceImpl class contains multiple methods.I have one LoggingAspect and i want to dynamically pass the method parameters to an advice based on the method called in the ServiceImpl. how do i acheive this?In the below code my method has 4 parameters,but one of my other method has 5 parametres and the third has 3.So how do i pass parameters dynamically based on number of method parameters?
@Aspect
public class LoggingAspect {

@Before("allGenericAppServiceImplMethods(userid,galleryId,sid,imageName)")
public void LoggingAdvice(JoinPoint joinPoint,String userid,String     galleryId,String sid,String imageName){
System.out.println("String values are "+userid+" "+sid+" "+galleryId+" "+imageName);
}

@Pointcut("execution(public * com.nrollup.service.impl.GenericAppServiceImpl.*(..)) && args(userid,galleryId,sid,imageName)")
public void allGenericAppServiceImplMethods(String userid,String galleryId,String sid,String imageName)
{
}

}

A: You can use the around advice for this. A code snippet for your reference:
public void myAdvice(final ProceedingJoinPoint joinPoint) throws Throwable
{
    Object[] arguments = joinPoint.getArgs();
}

Once you have the arguments array, you can operate upon it as required.
You can use joinPoint.proceed() to continue with the function call.


text:
Q: Gnome animations gone after upgrade to 18.04 All animations were working in 17.10 before upgrading.  Afterward, no animations.
The "Animations" toggle in tweaks is "On".  I've confirmed that using the dconf editor.  I tried toggling it, but all animations seem to be off either way, including the dock hiding, which I turned on.  When a window approachs the dock, it simply vanishes as if the animations were off.
I checked journalctl -b0 for any clues but there's no warnings, failures, etc.
I did try a Wayland session for kicks but that completely failed.  Related?
Anyway, at least everything else in the Xorg session appears to be working just fine.  It's not a big deal.  But I'm mystified.
Any ideas?

Solution
Okay, I figured this out.   The artful installer left nux-tools, left over from unity, in a half-installed state but did purge it. This left a start up script in /etc/X11/Xsession.d which interfered with the gnome-session in bionic. Purged that and the problem was gone.
So this is a dependency bug in the nux-tools package (or perhaps some mistakenly identified changed file which the package partly installed and turned into evil cruft). Sigh. Took me a long time to find this.
May this report help somebody else.  Be careful to remove all of nux-tools which switching over from Unity.

A: I solved this by installing and using vanilla-gnome-desktop on my ubuntu 18.04


text:
Q: redux Async Action Error: Actions must be plain objects. Use custom middleware for async actions I used redux thunkMiddle to implement async action, but it was error when I send Http request in actions, the err is :
VM711:3 Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
    at Object.performAction (<anonymous>:3:2312)
    at liftAction (<anonymous>:2:27846)
    at dispatch (<anonymous>:2:31884)
    at Object.dispatch (bundle.js:22661)
    at dispatch (<anonymous>:2:1620)
    at Object.submitForm (bundle.js:23120)
    at Form.submitForm (bundle.js:23168)
    at Object.ReactErrorUtils.invokeGuardedCallback (bundle.js:4532)
    at executeDispatch (bundle.js:4332)
    at Object.executeDispatchesInOrder (bundle.js:4355)

There is my code:
In my action,I use superagent to send  request,my code like this:
import superagent from 'superagent'
import async from 'async'

export const onSubmitForm = userInfo => {
    async.waterfall([
        (done) => {
            superagent
                .post('/userInfo')
                .send(userInfo)
                .end((err, res) => {
                    done(err, res.body)
                });
        }
    ], (err, data) => {
        return (dispatch) => (dispatch(submitFormAction(data)))
    });
};

export const submitFormAction = data => {
    return {
        type: "USER_INFO",
        data
    }
};

And This is my entry file,I import thunkMiddle from redux :
import React from 'react';
import {render} from 'react-dom';
import {createStore, applyMiddleware} from "redux";
import { composeWithDevTools } from 'redux-devtools-extension';
import {Provider} from "react-redux";
import reducer from './reducers/index';
import thunkMiddleware from 'redux-thunk';
import {App} from './containers/App';

const store = createStore(reducer, composeWithDevTools(applyMiddleware(thunkMiddleware)));

render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root'));

So,how to solve this problem?

A: A thunk must return a function - some of your code-paths result in nothing being returned.
try altering your action by wrapping it in a function which you can return:
export const onSubmitForm = userInfo => {
    return function(dispatch) {
        async.waterfall([
            (done) => {
                superagent
                    .post('/userInfo')
                    .send(userInfo)
                    .end((err, res) => {
                        done(err, res.body)
                    });
            }
        ], (err, data) => {
            dispatch(submitFormAction(data))
        });
    }
};


text:
Q: How to refer two schemas in single entity using ejb I want to use two different schema in database, each schema has same set of Tables but data differs. How to use same entity two point different schemas in ejb.
Thanks in advance


text:
Q: Add active class based on URL path? My website is split into various categories. In each category, there are articles. I'm trying to add an active class to both the category page, which is a grid menu of all of the articles, as well as each article page within that category. The solutions I have seen compare your current url with the url attached to the navigation link. That solution would work for the category grid page, but not the article pages. To make things a little more complicated, the path for the grid page is /category, but the path for the articles within that category is /article/category/article-name.
Is there a way for me to place an active class on a menu link that relates to all articles within a category as well as the category grid page? I'd prefer a JQuery solution, if possible.

A: $(document).ready(function () {
 if (/category/.test(window.location.href)){
    //add the active class
 } else if (/article-name/.test(window.location.href)){
   //add the active class
 }
});

something like this?


text:
Q: LDAP and pam without binddn and anonymous access I am working in a large company and can use its central read-only LDAP server remotely. The LDAP server does not allow anonymous binding. In order to use this server for authentication of the users on my small server with a pam module I need an account which exposes the data on LDAP to me. The account data is normally filled in binddn and bindpw fields of the configuration. As I understood pam module normally logins with binddn and bindpw, then performs a search and afterwards bind for each user who is willing to login.
The administrators of the server however do not like exposing all the data to me. And so my question is:
How can I configure pam without binddn account? Ideally a direct bind for each user should be performed without prior login with binddn account.

A: I couldn't figure out a way to do this with the pre-existing PAM modules, so I wrote one. It only supports simple authentication at the moment. Be sure to include a uri and binddn template parameter like so:
auth    sufficient    pam_ldapdb.so uri=ldap://example.com binddn=uid=%s,dc=example,dc=com

%s will be replaced with the user connecting.
This requires g++, pam devel and ldap devel. It's been tested on CentOS 6 and 7, 64 bit.
https://github.com/rmbreak/pam_ldapdb

A: The problem is that user authentication on UNIX works by taking a simple username string, such as 'usera'.
LDAP does not work like this, but instead needs a full username DN, such as uid=mruser,cn=users,dc=ibm,dc=com.
So the reason you need to allow anon binding or have a valid binddn is so that your authentication system can bind to the LDAP server and perform a search to translate usera -> uid=mruser,cn=users,dc=ibm,dc=com.  Without this ability, it wouldn't know what to test the password against in the directory.
It's usual for LDAP admins to not want to allow anonymous binding, but they should be able to create a specific user for you which is only allows to access the specific details you require for LDAP authentication to work on UNIX.  ie. read-only access on the user and group areas of the LDAP hierarchy.

You don't mention what OS you're actually talking about, but remember that PAM is for authentication - you also need to be able to have the NSS service also resolve usernames and userids.  Depending on the implementation, this may be a different part of the configuration work you need to do.

A: I think I understand what you want to do, which I think is:

*

*A user presents credentials to you for validation.

*Instead of binding to the LDAP server via anonymous access, or with a standard set of binding credentials, you want to use the credentials just presented to you by the user, each time, to authenticate to the LDAP server in order to ask it to validate those credentials.
Is that it?
If so, then in order for that to make sense, each user's credentials must be LDAP-valid only for authenticating his or her own credentials; otherwise you could perform the clearly-feared wide search with the first set of credentials so presented.  And if the LDAP server admins can tie the scope of a set of credentials down that tightly, then they should be able to provide you with a standard set of binding credentials which are valid only to perform searches against those users who you're authorised to see.
Do you see my point?  If your LDAP server admins are that good at scoping the searches that credentials can do, they have the skills needed to give you a suitable set of binding credentials.  And if they're not that good, there's no point in asking you to do what they want, because you already possess credentials powerful enough to do what they don't want you to do.
The two standard ways to access an LDAP server are (1) anonymously, and (2) using a set of credentials issued by the server admins which are suitable only for doing what you need them to do.  If the server admins don't like (1), then it's their job to provide you suitable credentials to do (2).


text:
Q: Programmatically add retina and non-retina images to local store via writeToFile? Hello: I have a photo uploader in my application that will let players upload their own photos for use in my application. I crop and resize each uploaded image in order to create two images: an X-by-X pixel image (for non-retina displays) and a 2X-by-2X pixel image (for retina displays).
I then save both images to local player's Private Documents directory via [photoDataNonRetina writeToFile:pathNonRetina atomically:YES] and [photoDataRetina writeToFile:pathRetina atomically:YES] where photoDataNonRetina and photoDataRetina are NSData objects and the filenames for each image are photo.png and photo@2x.png respectively.
How should I subsequently retrieve my images from the local Private Documents directory so that the appropriate image is retrieved based on whether the device has a retina display? Right now I would guess doing something akin to the following:
NSString *path = [[self pathForPlayer:player] stringByAppendingPathComponent:@"photo.png"];
return [UIImage imageWithContentsOfFile:path];

except that would seem only to load the non-retina image?

A: Try this:
if ([[UIScreen mainScreen] respondsToSelector:@selector(displayLinkWithTarget:selector:)]            &&
([UIScreen mainScreen].scale == 2.0)) {
  // Retina display
} else {
  // non-Retina display
}

A: Maybe this?
if ([[UIScreen mainScreen].scale > 1) {
  NSString *path = [[self pathForPlayer:player] stringByAppendingPathComponent:@"photo@2x.png"];
  UIImage * image = [UIImage imageWithContentsOfFile:path];
  UIImage * retinaImage = [UIImage imageWithCGImage:[image CGImage] scale:2 orientation:[image imageOrientation]];
  return retinaImage;
} else {
  NSString *path = [[self pathForPlayer:player] stringByAppendingPathComponent:@"photo.png"];
  return [UIImage imageWithContentsOfFile:path];
}

A: Simply remove the extension from the filename.
NSString *path = [[self pathForPlayer:player] stringByAppendingPathComponent:@"photo"];
return [UIImage imageWithContentsOfFile:path];


text:
Q: How to install OpenMotif on 12.04 There is no package called openmotif, so how do I install it on Ubuntu 12.04? It's needed according to Citrix, for using Citrix Receiver 12.1 for Linux.

A: Installation should be as simple as installing the libmotif-dev package. So
sudo apt-get install libmotif-dev

A: To install OpenMotif for Citrix, check out the CitrixICAClientHowTo

A: *

*Install packages libmotif4 & nspluginwrapper (you can use synaptic package manager)

*Download the Receiver you need from citrix.com (.deb file)

*Open the downloaded file

*Add the certificates to avoid SSL error
sudo ln -s /usr/share/ca-certificates/mozilla/* /opt/Citrix/ICAClient/keystore/cacerts/

A: in some cases packages for ubuntu are named little bit differently

*

*so you need to search by package name

*or to search for package contents
apt-cache search 'pattern'
apt-file search 'path'
this is a universal solution


text:
Q: firePropertyChange - does it matter what the parameters oldValue and newValue are? I'm currently working on a project in which a propertyChangeListener is used to update the view-part of the program when somthing has changed in the model-part. The program solves a given sudoku puzzle and updates the model to include the solution.
I use a firePropertyChange method which has the parameters oldValue and newValue. i understand that these have to be different in order for something to happen but does it actually matter what they are? In my program the model is always updated when something happens and I never use the information contained in oldValue or newValue.
Could it be possible to just put these as "1" and "2" to make sure they are always different? Would this cause any other issues. Here is a method called clear which resets the sudoku to a blank board:
public void clear() {
    String oldBoard = getBoard();
    for (int i=0; i<9; i++) {
        for (int k=0; k<9; k++)
            plan[i][k] = 0;
    }
    pcs.firePropertyChange("clear", oldBoard, getBoard());
}

A: Yes, it matters in the general sense, since when you are writing the code for the observed entity, you write it with the idea that this entity can never know who or what is listening to it or how the observers are going to use the information that the listener is going to provide to them. It may be important to the observer, it may not, but always assume that it is, keep the information as accurate as possible, and your code will be safer for future extensions and use.

A: It would work if the receiver of the property change is your internal classes and they have the knowledge of ignoring the old/new values of the property change event. You may still need to document this fact clearly in case you may forget it yourself after some time later. To make code more maintainable and readable however, it would be a better approach you write your own listener interface, though it would requires some more works.
An example:
public interface SudokuListener {
    void sudokuCleared();
}


text:
Q: Java not equals with OR I'm just wondering why this is not correct :
if ( !name.equals("abc") || !name.equals("cba") )`

And this is correct :
if ((!(name.equals("abc") || name.equals("cba") )))

thank you !

A: To understand the difference, it always helps to read out your condition statement in english.
if ( !name.equals("abc") || !name.equals("cba") )

Translates to

If name does not equal "abc" OR name does not equal "cba", then...

Whereas,
if ((!(name.equals("abc") || name.equals("cba") )))

If (name equals "abc' OR name equals "cba" ) IS FALSE, then...

or, by Boolean Logic,

If name does not equal "abc" AND name does not equal "cba", then...

The two are definitely not the same.

A: Think about how the ! works.
Take !(a || b)
whats the truth table:
a=f b=f = !(f || f) = !(f) = t
a=f b=t = !(f || t) = !(t) = f
a=t b=f = !(t || f) = !(t) = f
a=t b=t = !(t || t) = !(t) = f

Now take (!a || !b)
a=f b=f = (!f || !f) = (t || t) = t
a=f b=t = (!f || !t) = (t || f) = t
a=t b=f = (!t || !f) = (f || t) = t
a=t b=t = (!t || !t) = (f || f) = f

Now take the correct way to distribute  ! (!a && !b)
a=f b=f = (!f && !f) = (t && t) = t
a=f b=t = (!f && !t) = (t && f) = f
a=t b=f = (!t && !f) = (f && t) = f
a=t b=t = (!t && !t) = (f && f) = f

And for completeness sake take the same as (!a || !b) !(a && b)
a=f b=f = !(f && f) = !(f) = t
a=f b=t = !(f && t) = !(f) = t
a=t b=f = !(t && f) = !(f) = t
a=t b=t = !(t && t) = !(t) = f

A: The first code has this truth table

The second code instead has this truth table

A: Actually this is a math question. These are same logical equation:
!x || !y  ==  !(x && y)
!x && !y  == !x || !y

You can read more about logical operation here


text:
Q: Error 13 in Java Eclipse, how do I fix this? I just built a new PC and I tried to run eclipse on it from a USB stick, I did this earlier on my previous machine and it worked just as intended but after I upgraded my PC it gives me the error 13. I tried reinstalling java, jdk everything and it just doesn't want to work.
-startup
plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.500.v20170531-1133
-product
org.eclipse.epp.package.java.product
-showsplash
org.eclipse.epp.package.common
--launcher.defaultAction
openFile
--launcher.defaultAction
openFile
--launcher.appendVmargs

-vm
C:\Program Files\Java\jre1.8.0_271\bin\javaw.exe

-vmargs
-Dosgi.requiredJavaVersion=1.8
-Dosgi.instance.area.default=@user.home/eclipse-workspace
-XX:+UseG1GC
-XX:+UseStringDeduplication
-Dosgi.requiredJavaVersion=1.8
-Xms256m
-Xmx1024m

this is my eclipse.ini file
Here is what comes up whenever I try to launch eclipse

A: That's usually indicative of a broken java version. Did you install java on the stick too? Your new PC is 64-bit, your old one was 32-bit, you have a 32-bit java; that's not going to work, install a modern 64-bit one from e.g. adoptopenjdk.net.
Alternatively, the problem is that you have no java installed at all; same fix: Install one.
NB: I'm taking a wild stab here, you haven't provided a ton of information.

A: In order to run Eclipse from the USB drive, follow the steps given below:

*

*Download JDK and install it in the USB drive.

*Download Eclipse and extract it on the USB drive.

Make sure that both of them are 64-bit versions. It can still work if both of them are 32-bit version but I recommend you go for the 64-bit version. In any case, they should not be of mixed versions (i.e. one is 32-bit while the other one is 64-bit).

*On the command prompt, change the directory to the USB drive and append the path to the JDK bin folder to the path variable e.g. set path=%PATH%;path-to-jdk-bin-folder-in-USB. Then use the command java -version to confirm if the correct Java version is picked up.

*Change the directory to Eclipse folder and execute the command, eclipse.


text:
Q: Accessing a member in the hash I have a JSON that controller generates and in debug window it looks like this:

So basically this hash has two main elements, one is medications and one is query_duration. And medications its self is has a few members.
To draw some charts I need to pass the whole Medications part of this to the Javascript, I used GON gem for passing to JavaScript.  But my problem is that I don't know how to pass the medications part?
Should I say like @order_summary[0] @order_summary.medications  ? none of them worked tho.

A: @order_summary['medications']

Should work.


text:
Q: Second-order non-linear differential equation containing sgn function encountered in literature on the SYK model. I'm trying to solve the following differential equation:
$$J^2\frac{1}{2^{q-1}}\operatorname{sgn}(\tau)e^{g(\tau)}=\partial_\tau^2\Big(\frac{1}{2q}\operatorname{sgn}(\tau)g(\tau)\Big).$$
Here $J^2$ and $q$ are constants and I want to solve for $e^{g(\tau)}$. I encountered this equation in a paper by Gábor Sárosi et al. called "AdS$_2$ holography and the SYK model" (p.38) and "Comments on the Sachdev-Ye-Kitaev model" (p.12) by Juan Maldacena and Douglas Stanford.
According to them the general solution to this differential equation is given by:
$$e^{g(\tau)} =\frac{c_1^2}{\mathcal{J}^2}\frac{1}{\sin^2(c_1(|\tau|+c_2))}$$ where $$\mathcal{J}=J\sqrt{\frac{q}{2^{q-1}}}$$
I am unable to reach the same result unfortunately. What I tried to do is solve the equation for $$|\tau|>0$$ so that I loose the sgn function (this could potentially be the problem) since I'm not sure how to deal with it otherwise. I get:
$$\frac{d^2g(\tau)}{d\tau^2}=J^2\frac{q}{2^{q-2}}e^{g(\tau)}$$
It would be nice if we could make this a first order differential equation so
multiplying both sides by $$\frac{dg(\tau)}{d\tau}$$ and integrating w.r.t. $\tau$ gives:
$$\int\frac{dg(\tau)}{d\tau}\frac{d^2g(\tau)}{d\tau^2}d\tau=J^2\frac{q}{2^{q-2}}\int e^{g(\tau)}\frac{dg(\tau)}{d\tau}d\tau\\$$
$$\frac{1}{2}\Big(\frac{dg(\tau)}{d\tau}\Big)^2=J^2\frac{q}{2^{q-2}}(e^{g(\tau)}+c_1)$$
Here I used integration by parts to rewrite the lhs. Rearranging a bit gives:
$$\frac{dg(\tau)}{d\tau}=J\sqrt{\frac{q}{2^{q-3}}}\sqrt{(e^{g(\tau)}+c_1)}$$
Now that the equation is a separable first order differential equation we can integrate to find the general solution:
$$\int\frac{dg(\tau)}{\sqrt{(e^{g(\tau)}+c_1)}} =J\sqrt{\frac{q}{2^{q-3}}}\int d\tau$$
$$-\frac{2}{\sqrt{c_1}} \operatorname{artanh}\Big(\frac{\sqrt{e^{g(\tau)}+c_1}}{\sqrt{c_1}}\Big) =J\sqrt{\frac{q}{2^{q-3}}}(\tau+c_2)$$
So that:
$$e^{g(\tau)} =c_1\bigg(\tanh^2\Big(\mathcal{J}\sqrt{c_1}(\tau+c_2)\Big)-1\bigg)$$ where again $$\mathcal{J}=J\sqrt{\frac{q}{2^{q-1}}}$$
Obviously this is not the same as the general solution they state in their paper. Hopefully someone can help me see where I go wrong.
If I check the solution they give in the paper $\Big(e^{g(\tau)} =\frac{c_1^2}{\mathcal{J}^2}\frac{1}{\sin^2(c_1(|\tau|+c_2))}\Big)$ it does work out:
$$\frac{d^2g(\tau)}{d\tau^2}=\mathcal{J}^2e^{g(\tau)}$$
$$\frac{c_1^2}{\sin^2(c_1(|\tau|+c_2))}=\frac{c_1^2}{\sin^2(c_1(|\tau|+c_2))}$$
But I can think of no way of finding the constants of integration ($c_1$ and $c_2$) using boundary conditions $$g(0)=g(\beta)=0$$

A: I tried to analyze the situation and to understand what happens. I shall refer to the paper by Maldacena and Stanford as to [MS] and to the paper by Sárosi as to [S].
At p. 11 in the first line of the paper [MS] is written that $\tau=it$. Then, I guess, Equation 2.16 from [MS] implies the equation $$\frac{d^2g(\tau)}{d\tau^2}=\color{red}-2\mathcal J^2e^{g(\tau)},$$ whereas (132) from [S] transforms to this equation, but without the minus sign. Nevertheless, both papers provide the same general solution for both equations (assuming $\sin(c(|\tau|+\tau_0))^2$ means $\sin^2(c(|\tau|+\tau_0))$), so I guess that in the later paper ([S]) it was taken from the former paper ([MS]) and the correct equation should have the minus sign. Farther I assume that the funсtion $g$ is real-valued.
Anyway, your way of solution should be applicable mutatis mutandis to both equations. I think that the key point is the following. When we obtain an equality
$$\left(\frac{dg(\tau)}{d\tau}\right)^2=\color{red}-4\mathcal J^2 (e^{g(\tau)}+c_1), \tag{1}\label{1}$$
we should care about the sign of $c_1$. This is important because Mathcad suggests that the expression for $\int\frac{1}{\sqrt{e^g+c}}dg$ depends on sign of $c$. For a general form it indeed gives an answer
$\frac{-2}{\sqrt c}\color{blue}{\operatorname{artanh}}{\frac{\sqrt{e^g+c}}{\sqrt c}}$, but for $c=-1$ it
it gives an answer $2\color{blue}{\operatorname{artan}}{\sqrt{e^g-1}}$. So I gave to it an integral  $\int\frac{1}{\sqrt{e^g\color{blue}-c}}dg$ and obtained an answer $\frac{2}{\sqrt c}\color{blue}{\operatorname{artan}}{\frac{\sqrt{e^g-c}}{\sqrt c}}$.
Since the left hand side of the equation \ref{4} is non-negative and at the right hand side it should have the red minus sign, $c_1$ should be non-positive and so the equation transforms to
$$\frac{dg(\tau)}{d\tau}=2\mathcal J\sqrt{-c_1- e^{g(\tau)}}.$$
But $\int\frac{1}{\sqrt{-c_1-e^g}}dg$ equals $\frac{-2}{\sqrt{–c_1}}\color{blue}{\operatorname{artanh}}\frac{\sqrt{-c_1-e^g}}{\sqrt{–c_1}}.$ But here we again have an archyperbolic function, so I guess that I have misunderstood something, thus we shouldn't have the red minus.  Then we have an equation
$$\frac{dg(\tau)}{d\tau}=2\mathcal J\sqrt{e^{g(\tau)}+c_1}.$$
Its general solution  should be
$$\frac{1}{\sqrt{–c_1}}\operatorname{artan}\frac{\sqrt{e^{g(\tau)}+c_1}}{\sqrt{–c_1}}=\mathcal J\tau+c_2.$$
This should imply
$$\frac{e^{g(\tau)}+c_1}{-c_1}=\tan^2 (\sqrt{-c_1}(\mathcal J\tau +c_2))$$
So $$e^{g(\tau)}=-c_1-c_1\tan^2 (\sqrt{-c_1}(\mathcal J\tau+c_2))=\frac {-c_1}{\sin^2 (\sqrt{-c_1}(\mathcal J\tau+c_2) +\tfrac\pi2)}.$$

But I can think of no way of finding the constants of integration ($c_1$ and $c_2$) using boundary conditions $$g(0)=g(\beta)=0$$

Given a general solution $e^{g(\tau)}=\left(\frac{\frac{c}{\mathcal{J}}}{\sin c(\tau+\tau_0)}\right)^2$ for $\tau\ge 0$, we have $1=\left(\frac {\frac{c}{\mathcal{J}}}{\sin c\tau_0}\right)^2=\left(\frac {\frac{c}{\mathcal{J}}}{\sin c(\beta+\tau_0)}\right)^2$. This should imply  $\frac{c}{\mathcal{J}}=\pm \sin c\tau_0=\pm \sin c(\beta+\tau_0)$ and then by routine trigonometric transformations lead to solutions [MS, 2.18-19], [S, 134].