text:
Q: How can I factor our my shell scripts inside my .ebextensions directory? I'm customising the elastic beanstalk host machine by executing some shell commands.
I have this working fine when the commands are embedded in an ebextension config script.  But I want to write my customisation stuff in normal shell script files, instead of being embedded in YAML syntax that my editor doesn't understand.
So this works:
.ebextensions/01_do_stuff.config:
commands:
  01echostuff:
    ignoreErrors: false
    command: |
      echo "Do a bunch of elaborate stuff"

But I'd rather break my customisation stuff out into a proper shell script and then just launch it with an ebextension config command.
.ebextensions/myscripts/do_stuff.sh
echo "Do a bunch of elaborate stuff"

.ebextensions/01_do_stuff.config:
commands:
  01echostuff:
    ignoreErrors: false
    command: myscripts/do_stuff.sh

Both files (the shell and config) are packaged up in the beanstalk archive file and uploaded as part of the zip archive, I just want beanstalk to deploy my scripts along with the config files from the EB archive and allow me to execute them.

A: *

*There is a difference between running commands and container_commands

*You will want to trigger your shell script as container_commands which will then be able to access scripts within your application version (zip file)


text:
Q: PHP Submit button doesn't have any effect (PhpStorm) I updated the question.
Since the last code was pretty complex and even after fixing the stuff it didn't work, I executed the below simple code to check if things work. Even this code doesn't work. Whenever I click on the submit button, it again returns a 404 error.
Yes, I placed the PHP code in the body as well to check if this work but it doesn't.
<?php
if(isset($_POST['submit'])) {
echo("Done!!!!");

} else {
?>

<title>Echo results!</title>

<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
    <input name="submit" type="submit" value="submit"/>

</form>

<?php
}

?>

A: Try giving the button_create as name of the submit button

A: <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">

if(isset($_POST['button_create'])) {

<input type="submit" name="button_create" id="button_create" value="Create Table!">

change these lines see how you go from there

A: There are a couple of things wrong here, method should be POST instead of GET. The name attribute of text fields should be used when receiving the values. The submit button name should be used to check whether the button is clicked or not. See the example given below.
<?php
  if (isset($_POST['submit'])) {
    $ex1 = $_POST['ex1'];
    $ex2 = $_POST['ex2'];
    echo $ex1 . " " . $ex2;
  }
?>
<form action="" method="post">
  Ex1 value: <input name="ex1" type="text" />
  Ex2 value: <input name="ex2" type="text" />
  <input name="submit" type="submit" />
</form>

A:

      Echo results!

<?php
    if(isset($_POST['submit'])) {
        echo("Done!!!!");
    } else {

?>
    <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
        <input name="submit" type="submit" value="submit"/>
    </form>

<?php
    }
?>

this is for your updated question

redpajama_set_name: RedPajamaStackExchange


text:
Q: Font in footer changes despite footer already having CSS class declared I have a design which uses DIV with flex, at https://jsfiddle.net/1s2mpba6/, but the main problem here relates to use of webfonts, one area, despite not having a webfont, seems to have been replaced even though the body font is used.
I get this when it should be Helvetica:

These are the areas of the HTML and CSS which seem to be problematic:

header.california-m {
  background-color: #B22222;
  border-radius: 10px;
  color: #FFF;
  padding: 30px;
  width: 840px;
}

footer.california-m {
  background-color: #333;
  color: #FFF;
  padding: 30px;
  width: 840px;
  margin-bottom: 20px;
}

footer.california-m h2 {
  margin-left: 20px;
}

@font-face {
  font-family: Fabriga Regular;
  src: url("https://c.atcdn.co.uk/fonts/ATFabriga-Regular.eot?v=1.1.0");
  src: url("https://c.atcdn.co.uk/fonts/ATFabriga-Regular.eot?#iefix&v=1.1.0") format("embedded-opentype"), url("https://c.atcdn.co.uk/fonts/ATFabriga-Regular.woff2?v=1.1.0") format("woff2"), url("https://c.atcdn.co.uk/fonts/ATFabriga-Regular.woff?v=1.1.0") format("woff"), url("https://c.atcdn.co.uk/fonts/ATFabriga-Regular.ttf?v=1.1.0") format("truetype"), url("https://c.atcdn.co.uk/fonts/ATFabriga-Regular.svg?v=1.1.0#Regular") format("svg");
  font-weight: 400;
  font-style: normal
}

@font-face {
  font-family: Fabriga Medium;
  src: url("https://c.atcdn.co.uk/fonts/ATFabriga-Medium.eot?v=1.1.0");
  src: url("https://c.atcdn.co.uk/fonts/ATFabriga-Medium.eot?#iefix&v=1.1.0") format("embedded-opentype"), url("https://c.atcdn.co.uk/fonts/ATFabriga-Medium.woff2?v=1.1.0") format("woff2"), url("https://c.atcdn.co.uk/fonts/ATFabriga-Medium.woff?v=1.1.0") format("woff"), url("https://c.atcdn.co.uk/fonts/ATFabriga-Medium.ttf?v=1.1.0") format("truetype"), url("https://c.atcdn.co.uk/fonts/ATFabriga-Medium.svg?v=1.1.0#Medium") format("svg");
  font-weight: 400;
  font-style: normal
}

@font-face {
  font-family: ATVFabriga;
  src: url("https://c.atcdn.co.uk/fonts/ATVFabriga.woff2") format("woff2");
  font-weight: 400;
  font-style: normal;
}

.columns-vehicleresult+h1,
h2,
h3 {
  font-family: Fabriga Regular, Helvetica, sans-serif;
}

.columns-vehicleresult .column p.autog1 {
  font-family: Fabriga Regular, Helvetica, sans-serif;
}

.columns-vehicleresult .column p.autog1 b {
  line-height: 16px;
}

.atc-type-picanto {
  font-family: ATVFabriga, Helvetica, sans-serif;
}

1 Anytown Road, Anytown 1

☎ 555 0100

However, I've not used a font-family for header or footer so why is this only happening to the footer and what do I need to fix?
Functionally, it works well, aesthetically, it's a small thing to fix, advice welcomed!
It should be in Helvetica as with the rest of the text for body declared in CSS, apart from the .columns-vehicle-result which use a webfont.

A: The content of your footer are two h2 elements, and the rule with selector .columns-vehicleresult + h1, h2, h3 applies to those.
If the formatting of that rule is supposed to only apply to headline elements that immediately follow a .columns-vehicleresult, for all three of those headline levels - then this would need to become
.columns-vehicleresult + h1, .columns-vehicleresult + h2, .columns-vehicleresult + h3 { }


text:
Q: Are TempData Keys Case Sensitive? Not sure if this has been asked, I could not find it searching the title provided.  My question is:
Are TempData keys in ASP.NET case sensitive?
Example:
TempData["sampleKey"] = 5;

If I try to access it using:
TempData["SampleKey"]

will I get the value?
EDIT:
I understand this is easy to try (and I have now) the reason I posted this question was because I could not find a solution by searching.  Trying it will always be the best way to figure something out, but I thought I would ask the question anyway to have it out there for all to see.

A: They are not case sensitive. You can put in whatever case you want as the key, and it still comes up every time. Why they chose to do it this way, who knows...
EDIT
This is also true for ViewData.


text:
Q: How do I set a variable as the user id I want to write a start up script in tsch that creates a directory some where named with the current user id. I was hoping the following would work.
Set A = (id -u -n)

But I'm not sure how to handle the output of the command id properly for this kind of variable assignment.

A: You were very close, you use this instead:
set A=`id -u -n`

The ` characters tell tcsh to run the command and then set assigns the output to A.
You can make that variable read only too, with:
set -r A=`id -u -n`

After doing so, attempting to override its value will give:
> set A=foo
set: $A is read-only.


text:
Q: Automatically answer to input prompt of batch script run by Python while running bash script from python I have a batch file which is data.sh . so I am running this using python
and data.sh code is something like this
configure()
{
    read -p '--> Enter  key ID: ' key_id
    read -p '--> Enter  secret key: ' secret_key

    echo "$key_id"
    echo "$secret_key"
}

I am running this something like this
import subprocess

rc = subprocess.call("data.sh")

I want to pass these both pass key_id and secret_key  using python code. how I can achieve this ?

A: Like MattDMo said in the comment, configure does not use any command line args. If you change it to use command line args ($1 is the first command line arg, $2 is the second etc...), you can change the subprocess.call() function call to use a list of arguments. The first arg passed in the list will be the executable and the other arguments will be passed to the the executable as command line args. See the docs for subprocess.call here. There's a good example calling the ls executable with a command line arg of -l. You wouldn't need to use any dashes(like -l in the ls example), you could just pass the key id as the first argument, and the secret key as the second. This would look like the following:
Python:
rc = subprocess.call(["data.sh", key_id, secret_key])

Shell:
configure()
{
    key_id=$1
    secret_key=$2
    echo "$key_id"
    echo "$secret_key"
}

A: If you don't want to change the script to take command-line arguments, you can do
subprocess.Popen(["./data.sh"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True).communicate('key123\nabcd')


text:
Q: Correct use of Ressource Controller in Laravel I use the Laravel Ressource Controller but I am not sure if I use it the right way. I start with a easy view return which I put in the create function. In this view i write a name into a textfield and click the submit button which runs the function index. Defaul index function is only index() I changed it to index(Request $request) because of the post request. But I don't believe that index is the right function for that need. Here is the complete Controller.
public function index(Request $request)
{
    $username = $request->username;
    $user = User::where('name', $username)->select('id', 'name')->first();

    return view('invitation.username')->with('user', $user);
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
    return view('invitation.username');
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    //
}

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    //
}

/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    //
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
    //
}

Where to put the code? What is the correct function for my needs? Or should I create a new function?

A: Resource controllers may not be the best for this pattern.

*

*Index - show a listing of the resources for the model associated with the controller

*Create - show the form for creating the model

*Store - Accept the POST request from the Create form

*Show - Show an individual resource

*Edit - Show the form for editing a model

*Update - Accept the PUT request from the editing form to update the model.

For your case, I think the function nomenclature that would be more appropriate would be:
public function search()
{
    return view('invitation.search');
}

Then to display those results:
public function results()
{
    return view('invitation.results')
        ->with('user', User::where('name', request()->input('username'))->first());
}

Although this could be expounded and extrapolated out further to add support for additional field searching.


text:
Q: Differences between Matlab FFT and Opencv DFT c++ code I'm trying to convert code from Matlab to OpenCV,
I apply FFT\DFT on top of an image, multiply by amplitude (scale it) than bring the image back using dft.
I receive different results using matlab fft and Opencv DFT, which is exacly what am I trying to solve here.
What am I trying to solve here is the following:
I'd like to receive an identical results to the matlab, but still using an optimal DFT size in the opencv command.
In matlab I pad the image for the FFT usage, 2*N + 1 .
In opencv I pad the image in the size given to me by  the function called:
  getOptimalDFTSize

What's really bother me is the fact that if I discard the getOptimalDFTSize  command in opencv, and use 2*N +1 I receive an identical result to the Matlab.
But if I use the getOptimalDFTSize   command, the results are totally different.
I insist to use the getOptimalDFTSize   because it should make my code faster.
The matlab code:
building the filter
   [m,n] = size(img);
  %M = 2*m+1; N = n*2+1;
  M = 2*m; N = n*2;

  [X, Y] = meshgrid(1:N,1:M);
  CentX = ceil(N/2);
  CentY = ceil(M/2);
  dist = (X-CentX).*(X-CentX)+(Y-CentY).*(Y-CentY);
  H = (GammaH-GammaL)*(1-exp(-dist/(2*D0.^2)))+GammaL;

  % applying the filter
  IMG =fft2(Limg,M,N);
  H = fftshift(H);
  Iret = real(ifft2(IMG.*H));
  Iret = Iret(1:m,1:n);
  Iend = exp(Iret)-1;

My Opencv c++ code
//--------------------------UserInputStart
double m_GammaL = 0.02;
double m_GammaH = 1.2;
double m_D0 = 30;
//--------------------------UserInputEnd

int imageType = /*CV_64FC1 */CV_32F;
// Convert the input image into float
Mat inputImage32f;
inputImage8uchar->convertTo(inputImage32f,imageType);

// Convert the image from 0 to 1 scale , matlab corespondance : Limg = log(im2double(img)+1);
inputImage32f = inputImage32f / 255;
inputImage32f = inputImage32f + 1;

// Create a log image
Mat logImage;
cv::log(inputImage32f,logImage);

// Apply the filter

// Transform the image into the special domain
Mat paddedLogImage;                            //expand input image to optimal size
int m = getOptimalDFTSize( logImage.rows );
int n = getOptimalDFTSize( logImage.cols ); // on the border add zero pixels
copyMakeBorder(logImage, paddedLogImage, 0, m - logImage.rows, 0, n - logImage.cols,
    BORDER_CONSTANT, Scalar::all(0));

Mat homoFilter(paddedLogImage.rows,paddedLogImage.cols,imageType);
Mat*  p_homoFilter = &homoFilter;
// Handle the homomorphic filter
CreateHomomorphFilter(p_homoFilter,paddedLogImage.cols,paddedLogImage.rows,m_GammaL, m_GammaH , m_D0);

// Shift the filter
(*p_homoFilter) = (*p_homoFilter)(Rect(0, 0, (*p_homoFilter).cols & -2, (*p_homoFilter).rows & -2));
int cx = (*p_homoFilter).cols/2;
int cy = (*p_homoFilter).rows/2;

Mat q0((*p_homoFilter), Rect(0, 0, cx, cy));   // Top-Left - Create a ROI per quadrant
Mat q1((*p_homoFilter), Rect(cx, 0, cx, cy));  // Top-Right
Mat q2((*p_homoFilter), Rect(0, cy, cx, cy));  // Bottom-Left
Mat q3((*p_homoFilter), Rect(cx, cy, cx, cy)); // Bottom-Right

// swap quadrants (Top-Left with Bottom-Right)
Mat tmp;
q0.copyTo(tmp);
q3.copyTo(q0);
tmp.copyTo(q3);

// swap quadrant (Top-Right with Bottom-Left)
q1.copyTo(tmp);
q2.copyTo(q1);
tmp.copyTo(q2);

Mat complexI;
Mat planes[] = {Mat_<float>(paddedLogImage), Mat::zeros(paddedLogImage.size(), imageType)};
merge(planes, 2, complexI);         // Add to the expanded another plane with zeros

// this way the result may fit in the source matrix
dft(paddedLogImage, complexI,/*cv::DFT_SCALE|*/cv::DFT_COMPLEX_OUTPUT);
split(complexI, planes);

//planes[0] = planes[0].mul((*p_homoFilter));

multiply(planes[0],(*p_homoFilter),planes[0],1,imageType);
multiply(planes[1],(*p_homoFilter),planes[1],1,imageType);

merge(planes, 2, complexI);

// Back to image scope
idft(complexI, complexI,cv::DFT_SCALE|cv::DFT_INVERSE/*|cv::DFT_REAL_OUTPUT*/);
split(complexI, planes);

// Use only the planes[0] which is the real number
complexI = planes[0];

// Crop the relevant image values
Mat outputImage32f(complexI, Rect(0, 0, inputImage8uchar->cols,inputImage8uchar->rows));

What am I trying to solve here is the following: I'd like to receive an identical results to the matlab, but still using an optimal DFT size in the opencv command.

Regarding to the opencv command , Get optimal DFT size
getOptimalDFTSize
Returns the optimal DFT size for a given vector size.
DFT performance is not a monotonic function of a vector size. Therefore, when you calculate convolution of two arrays or perform the spectral analysis of an array, it usually makes sense to pad the input data with zeros to get a bit larger array that can be transformed much faster than the original one. Arrays whose size is a power-of-two (2, 4, 8, 16, 32, ...) are the fastest to process. Though, the arrays whose size is a product of 2's, 3's, and 5's (for example, 300 = 5*5*3*2*2) are also processed quite efficiently.
The function getOptimalDFTSize returns the minimum number N that is greater than or equal to vecsize so that the DFT of a vector of size N can be processed efficiently. In the current implementation N = 2 p * 3 q * 5 r for some integer p, q, r.
Solved
It took me a while to solve this problem , eventually there was no differences in the code, however there was a difference in the sampling rate between Matlab and OpenCV.
If I'd change the sampling rate in OpenCV things would have worked out but I'd have to pay in higher running time
I guess Opencv supported  DFT vs Matlab with FFT standard


text:
Q: Entity Framework with existing classes I have searched every way I can think of for the answer to this, so forgive me if I have overlooked a post...
I have a project containing model classes that I want to remain database-ignorant (pretend someone handed me the code and said "you're not allowed to modify one character of these classes"). I want to persist these to SQL Server using Entity Framework. So far, I have been able to use the fluent API to map anything that EF couldn't determine logically. But I have hit a block with the following:
public class PhotoPost {
    // mapped as Key with fluent API - comes from blog provider
    public string PostID { get; set; }
    public string Caption { get; set; }
    public Collection<Photo> Photos { get; set; }
}

public class Photo {
    public string Url { get; set; }
    public Image LoadImage() { … }
}

I have a class, PhotoPost, which represents a type of Post on a Blog. The PhotoPost instance has a collection of objects of type Photo, all of which need to be persisted to the database. My problem is that the Photo doesn't really have a primary key. Blog provider doesn't guarantee the Url will not change, and I can't touch this code to add an arbitrary ID. Furthermore, I don't really want an ID. The code that is going to interact with these objects shouldn't/won't know whether these objects came from the blog's API or from a local database (or XML, ...), so I don't really want to clutter up my code with boilerplate in subclassing these objects in another project just to add IDs everywhere (and constructors to create subclasses with IDs from parent classes without, as above) to make EF happy.
Is subclassing to add IDs my only option, or is there a way that I can meet in the middle, between "entity" and "complex type"? (From what I understand, complex types must be one-to-one with their parent entities.)


text:
Q: lxml alternative in Java? I have been extensively using lxml for developing algos. But now, due to performance issues, I have to migrate to Java. Moral is, can I find as awesome as lxml dom parser in Java?
> Key requirements :

1) feature like text_content()
   2) iterchildren and
   3) iterparent() and itersiblings()--- (if xpath is there, I think we can
   do such traversing, not sure).

Jsoup is famous there, but not sure if all can be done. I just want to port algorithms not heavy rewriting. Please suggest.
Thanks.
Why Java :
I am doing complex nlp and dom parsing tasks. Python is first choice and will remain.Writing c-extension is one thing, and performing complex nlp tasks is another, and merging two is yet another thing. Hence Java. Nothing offensive.

A: Saxon is your best bet in my opinion http://saxon.sourceforge.net . A bunch of examples can be found in this download of saxon-resources9-4.zip found here: http://sourceforge.net/projects/saxon/files/Saxon-HE/9.4/ like xpath expressions:
    XPathExpression findLine =
        xpe.compile("//LINE[contains(., $word)]");
    XPathExpression findLocation =
        xpe.compile("concat(ancestor::ACT/TITLE, ' ', ancestor::SCENE/TITLE)");
    XPathExpression findSpeaker =
        xpe.compile("string(ancestor::SPEECH/SPEAKER[1])");

A: xerces is a great for xml. You would use xerces via JAXP.


text:
Q: отсортирвать трехмерный массив по сумме массивов Задача:
есть массив трехмерный:
  for($i=0; $i < 30; $i++){
        for($j=0; $j < 20; $j++){
            for($k=0; $k < 10; $k++){
                $threeArr[$i][$j][$k] = rand(1,15);
            }
        }
    }

Отсортировать массивы третьего уровня в массиве в порядке убывания значений сумм вложенных в них массивов.
как можно отсортирвать?

A: Нужно так?
 for($i=0; $i < 30; $i++){
    for($j=0; $j < 20; $j++){
        for($k=0; $k < 10; $k++){
            $threeArr[$i][$j][$k] = rand(1,15);
        }
        $summ=array_sum($threeArr[$i][$j]);
        $threeArr[$i][$j]['summ']=$summ;
    }
    usort($threeArr[$i], function($a,$b){return ($a['summ']-$b['summ']);});
}

echo '<pre>'; print_r($threeArr);


text:
Q: Cannot label dendrograms in R I'm trying to do a hierarchical analysis using Hclust(), but I can't get the names of each case to appear in the dendrogram. Only their numerical identifier appears. The strange thing is that I do the same procedure with my data and with the USArrests database integrated in R. With USArrests it works very well, but not with my data frame, which is built by importing it from Excel.
This I do with my data (df2, a data frame):

d2<-hclust(dist(df2))
Warning message:
In dist(df2) : NAs introduced by coercion

Then plot(d2, hang = -1) delivers the dendrogram, but not the label names, only the numerical identifier.
The warning I think is for the names of the observations, which are characters, but the USArrests base also has a character variable, and the dendrogram appears with the names of the labels. The only difference I see is that in my data, the names of the observations appear justified on the right, and in USArrests on the left:
> head(USArrests)
           Murder Assault UrbanPop Rape
Alabama      13.2     236       58 21.2
Alaska       10.0     263       48 44.5
Arizona       8.1     294       80 31.0
Arkansas      8.8     190       50 19.5
California    9.0     276       91 40.6
Colorado      7.9     204       78 38.7
> head(df2)
            Mort_inf Esp_Vida_M Esp_vida_H
1 Argentina     25.6         75         68
2  Barbados     20.3         78         73
3   Bolivia     75.0         64         59
4    Brazil     66.0         67         57
5     Chile     14.6         78         71
6  Colombia     28.0         75         69

I don't understand what's going on. Any help would be appreciated.
Luis
The result of dput() is:
> dput(head(df2))
structure(list(c("Argentina", "Barbados", "Bolivia", "Brazil",
"Chile", "Colombia"), Mort_inf = c(25.6, 20.3, 75, 66, 14.6,
28), Esp_Vida_M = c(75, 78, 64, 67, 78, 75), Esp_vida_H = c(68,
73, 59, 57, 71, 69)), row.names = c(NA, 6L), class = "data.frame")

Thanks...

A: Tip labels in the dendrogam correspond to the row.names in the data.frame object. Try the following:
row.names(df2)<-df2[,1]

Here's the resulting dendrogram


text:
Q: CSS - layout of the sidebar starting from the left side of the screen (see picture) How i can code layout like this: http://i.imgur.com/4kgVMJt.png
Here demo: http://jsfiddle.net/ymC82/
current code html:

        Sidebar

          Content

current code css:
*{
    margin: 0;
    padding: 0;
}

.wrapper{
    max-width: 600px;
    margin: 0 auto;
}

aside{
    padding: 50px 0;
    width: 30%;
    float: left;
    display: inline-block;
    background: #aaa;
}

article{
    padding: 50px 0;
    width: 70%;
    float: left;
    display: inline-block;
    background: #777;
}

red line is a container.
please help with this.

A: Quick-and-dirty solution: a background div. http://jsfiddle.net/VwWjp/
div.halfbg{
    background-color:#aaa;
    min-width:180px;
    width:calc(50% - 120px);
    position:absolute;
    top:0;
    left:0;
    bottom:0;
    z-index:-999;
}

A: Using CSS3 property box-sizing, you can achieve easily this kind of layout.
HTML

Content Goes Here

Content Goes Here

CSS
 *{
margin: 0;
padding: 0;
}

.wrapper{
 margin: 0 auto;
}

aside{
padding:50px 0 50px 10%;
width: 30%;
float:left;
background: #aaa;
box-sizing:border-box;
-webkit-box-sizing:border-box;
}

article{
padding:50px 10% 50px 0;
width: 70%;
float:left;
background: #777;
box-sizing:border-box;
-webkit-box-sizing:border-box;
}

Have a Fiddle DEMO


text:
Q: The method getinstance(Context) is undefined for the type AccessibilityManager I'm trying to create my own ImagePreference that I will use in my app preferences in order to pick the picture the user chooses to represent himself.
I'm not too sure about what I'm doing, but basically I'm mimicking some other preference classes. So far I'm only having trouble with this method:
public class ImagePreference extends Preference {
...
    void sendAccessibilityEvent(View view) {
        // Since the view is still not attached we create, populate,
        // and send the event directly since we do not know when it
        // will be attached and posting commands is not as clean.
        AccessibilityManager accessibilityManager = AccessibilityManager.getInstance(getContext());
        if (mSendClickAccessibilityEvent && accessibilityManager.isEnabled()) {
            AccessibilityEvent event = AccessibilityEvent.obtain();
            event.setEventType(AccessibilityEvent.TYPE_VIEW_CLICKED);
            view.onInitializeAccessibilityEvent(event);
            view.dispatchPopulateAccessibilityEvent(event);
            accessibilityManager.sendAccessibilityEvent(event);
        }
        mSendClickAccessibilityEvent = false;
    }

I have just copied this code from the TwoStatePreference class. I'm not even sure I need this method at all, but the compiler complains saying that the AccessibilityManager class does not contain a getInstance method.
I thought this could be a problem with the imports, but I'm importing the same classes as TwoStatePreference does, i.e.:
import android.view.accessibility.AccessibilityManager;

I have lost already several hours with this problem. Any idea of why the compiler is complaining?
Thanks!

A: Indeed, the AccessibilityManager class has no method called getInstance().  From the docs:

To obtain a handle to the accessibility manager do the following:
AccessibilityManager accessibilityManager =
    (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);

So really all you need is a Context.  Lucky, you've got a View, which itself is a Context, and holds references to it's parent contexts.

A: This method had been hidden.
The source code:

 /**
 * Get an AccessibilityManager instance (create one if necessary).
 *
 * @param context Context in which this manager operates.
 *
 * @hide
 */
public static AccessibilityManager getInstance(Context context)


text:
Q: How to fetch location markers from firebase realtime database and add to map view in Xcode with swift So I am trying to replace the hard coded version of the array data with a download from firebase realtime database and I want to store that download into 4 separate arrays or 1 array of another array per night club
firebase realtime database json structure

I haven't tried much as I am new to firebase so I don't really know, any help would be very appreciated
// ViewControllerThree.swift
import Foundation
import UIKit
import MapKit
import CoreLocation
import FirebaseDatabase

class ViewControllerThree: UIViewController, CLLocationManagerDelegate, UITableViewDataSource, UITableViewDelegate { // new last 2

@IBOutlet weak var clubInfo: UIView!
@IBOutlet weak var mapView: MKMapView!

@IBOutlet weak var miniTableView: UITableView! // new

var locationManager = CLLocationManager()
var artworks: [Artwork] = []

var nightClubs = [NightClubs]() // new new

override func viewDidLoad() {
    super.viewDidLoad()
    miniTableView.dataSource = self
    miniTableView.delegate = self

    //dataService()
    DataService.ds.REF_BARS.observeSingleEvent(of: .value, with: { (snapshot) in
        print(snapshot.value as Any)
        if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
            for snap in snapshot {
                print(snap)
                if let barData = snap.value as? Dictionary<String, AnyObject> {
                    let bar = NightClubs(barData: barData)
                    self.nightClubs.append(bar)
                    print(self.nightClubs)
                    self.miniTableView.reloadData()
                }
                self.miniTableView.reloadData()
            }
            self.miniTableView.reloadData()
        }
        self.miniTableView.reloadData()
    })
    clubInfo.layer.cornerRadius = 4

    self.locationManager.requestAlwaysAuthorization()
    self.locationManager.requestWhenInUseAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
        mapView.showsUserLocation = true
    } else {
        print("Location service disabled, Give permission or connect to the internet");
    }

    mapView.delegate = self
    let artwork = Artwork(title: "Alley",
                          locationName: "Barrie",
                          discipline: "Night Club",
                          coordinate: CLLocationCoordinate2D(latitude: 44.3894, longitude: -79.6889)
                         )
    mapView.addAnnotation(artwork)
    mapView.register(ArtworkView.self,
                     forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
    getLocations()
    getTitleList()
    titleMaker()
    //pullLocations()
}

public func dataService() {
    DataService.ds.REF_BARS.observeSingleEvent(of: .value, with: { (snapshot) in
        print(snapshot.value as Any)
        if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
            for snap in snapshot {
                print(snap)
                if let barData = snap.value as? Dictionary<String, AnyObject> {
                    let bar = NightClubs(barData: barData)
                    self.nightClubs.append(bar)
                    print(self.nightClubs)
                    self.miniTableView.reloadData()
                }
                self.miniTableView.reloadData()
            }
            self.miniTableView.reloadData()
        }
        self.miniTableView.reloadData()
    })
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return nightClubs.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "countCell") as! countCell
    //let barz = nightClubs[indexPath.row]
    let nightClub: NightClubs

    nightClub = nightClubs[indexPath.row]

    cell.goingCountLabel.text = nightClub.goingCount
    cell.liveCountLabel.text = nightClub.liveCount
    return cell
}

let regionRadius: CLLocationDistance = 1000

func centerMapOnLocation(location: CLLocation) {
    let coordinateRegion = MKCoordinateRegion.init(center: location.coordinate,
        latitudinalMeters: regionRadius, longitudinalMeters: regionRadius)
    mapView.setRegion(coordinateRegion, animated: true)
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation:CLLocation = locations[0] as CLLocation
    manager.stopUpdatingLocation()
    let coordinations = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude,longitude: userLocation.coordinate.longitude)
    let span = MKCoordinateSpan.init(latitudeDelta: 0.1,longitudeDelta: 0.1)
    let region = MKCoordinateRegion(center: coordinations, span: span)
    mapView.setRegion(region, animated: true)
}

var titleArray = [String]()
var locationNameArray = [String]()
var disciplineArray = [String]()
var coordinateArray = [CLLocationCoordinate2D]()
static var titleArraytwo = [String]()

public func titleMaker(){
    ViewControllerThree.titleArraytwo = titleArray
}

public func pullLocations() {
    let nightClub: NightClubs

    titleArray.append(nightClub.name) // to add all nightClub.name to this array
    locationNameArray.append("locationName") // to add all nightClub.location to this array
    disciplineArray.append("type") // to add all nightClub.type to this array
    coordinateArray.append(CLLocationCoordinate2D(latitude: 0, longitude: 0)) // to add all nightClub.latitude and nightClub.longitude to this array
}

public func getLocations() {

    titleArray.append("Alley")
    titleArray.append("Donaleigh's Irish Public House")
    titleArray.append("Queens")
    titleArray.append("The Ranch")
    titleArray.append("Rebel")
    titleArray.append("Moda")
    titleArray.append("Fiction")
    titleArray.append("Partytown")
    titleArray.append("Avenue")
    titleArray.append("Aria")
    titleArray.append("Lavish")
    titleArray.append("TABU")
    titleArray.append("Trappers Alley")
    titleArray.append("Phil's Grandsons Place")
    titleArray.append("Dallas")
    titleArray.append("The Pub On King")
    titleArray.append("Prohibition")
    titleArray.append("Yuk yuks Comedy club")
  // titleArraytwo = titleArray

    locationNameArray.append("Barrie")
    locationNameArray.append("Barrie")
    locationNameArray.append("Barrie")
    locationNameArray.append("Barrie")
    locationNameArray.append("Toronto")
    locationNameArray.append("North York") //
    locationNameArray.append("Toronto")
    locationNameArray.append("Guelph")
    locationNameArray.append("Vaughn")
    locationNameArray.append("Peterborough")
    locationNameArray.append("London")//
    locationNameArray.append("Guelph")
    locationNameArray.append("Guelph")
    locationNameArray.append("Waterloo")
    locationNameArray.append("kitchener")
    locationNameArray.append("waterloo") //
    locationNameArray.append("London")
    locationNameArray.append("London")

    disciplineArray.append("Night Club")    // Alley
    disciplineArray.append("Bar")           // donaleighs
    disciplineArray.append("Night Club")    // queens
    disciplineArray.append("Night Club")    // ranch
    disciplineArray.append("Night Club")    // rebel
    disciplineArray.append("Night Club")    // moda
    disciplineArray.append("Night Club")    // Fiction 180 Pearl Street, Toronto, ON, M5J1J2
    disciplineArray.append("Night Club")    // party town nightclub 100 carden st
    disciplineArray.append("Night Club")    // Avenue Night Club 2800 Hwy 7 W, Concord, ON L4K 1W8
    disciplineArray.append("Night Club")    // ARIA club 331 George Street North, Peterborough, ON K9H 3P9
    disciplineArray.append("Night Club")    // LAVISH club 238 Dundas St, London, ON N6A 1H3
    disciplineArray.append("Night Club")    // TABU nightclub 96 macdonell st, guelph N1H4e5
    disciplineArray.append("Night Club")    // Trappers Alley night club
    disciplineArray.append("Night Club")    // Phil's Grandson's Place
    disciplineArray.append("Night Club")    // Dallas
    disciplineArray.append("Bar")           // the pub on king
    disciplineArray.append("Night Club")    // prohibition
    disciplineArray.append("Bar")           // Yuk yuks comedy club // prime money

    coordinateArray.append(CLLocationCoordinate2D(latitude: 44.3894, longitude: -79.6889)) // johnson's
    coordinateArray.append(CLLocationCoordinate2D(latitude: 44.3894, longitude: -79.6891)) // donaleighs
    coordinateArray.append(CLLocationCoordinate2D(latitude: 44.3895, longitude: -79.6868)) // queens
    coordinateArray.append(CLLocationCoordinate2D(latitude: 44.3903, longitude: -79.6915)) // ranch
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.6410, longitude: -79.3547)) // rebel
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.7761, longitude: -79.4935)) // moda
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.6476, longitude: -79.3891)) // fiction
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.5451, longitude: -80.2468)) // partytown
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.7962, longitude: -79.5190)) // avenue
    coordinateArray.append(CLLocationCoordinate2D(latitude: 44.3038, longitude: -78.3201)) // aria
    coordinateArray.append(CLLocationCoordinate2D(latitude: 42.9847, longitude: -81.2468)) // LAVISH Nightclub
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.5451, longitude: -80.2470)) // tabu
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.5452, longitude: -80.2469)) // trappers alley
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.4752, longitude: -80.5244)) // phil grandson place
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.4520, longitude: -80.4950)) // dallas
    coordinateArray.append(CLLocationCoordinate2D(latitude: 43.4678, longitude: -80.5232)) // pub on king
    coordinateArray.append(CLLocationCoordinate2D(latitude: 42.9841, longitude: -81.2505)) // prohib
    coordinateArray.append(CLLocationCoordinate2D(latitude: 42.9896, longitude: -81.2192)) // yuk yuk
}

    public func getTitleList(){
        // var titles = titleArray // fix code
        var names = locationNameArray
        var type  = disciplineArray
        var coords = coordinateArray

        while 0 < titleArray.count {
          let location = Artwork(title: titleArray.remove(at: 0),
                                 locationName: names.remove(at: 0),
                                 discipline: type.remove(at: 0),
                                 coordinate: coords.remove(at: 0))
            mapView.addAnnotation(location)
        }
    }
}

I am trying to replace func getLocations() with func pullLocations() as it would save me 100 lines and make it dynamic

A: you can simply replace your old tableView forRowAt func with
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "countCell") as! countCell
    let nightClub: NightClubs
    nightClub = nightClubs[indexPath.row]

    let artwork = Artwork(title: nightClub.name,
                          locationName: nightClub.location,
                          discipline: nightClub.type,
                          coordinate: CLLocationCoordinate2D(latitude: Double(nightClub.latitude)!, longitude: Double(nightClub.longitude)!)
    )
    mapView.addAnnotation(artwork)
    cell.goingCountLabel.text = nightClub.goingCount
    cell.liveCountLabel.text = nightClub.liveCount
    return cell
}

then remove your hardcoded Artwork objects and its relations


text:
Q: Python: Read large CSV in chunk Requirement: Read large CSV file (>1million rows) in chunk
Issue: Sometimes the generator yields the same set of rows twice even though the file has unique rows. But some runs it looks fine with no duplicates
Looks like I am missing something in the code, I am not able to figure out
Want to make sure it doesn't yield the same object over and over with different contents
Code:
def gen_chunks(self,reader, chunksize=100000):
    chunk = []
    for i, line in enumerate(reader):
        if (i % chunksize == 0 and i > 0):
            yield list(map(tuple, chunk))
            chunk = []
        chunk.append(line)
    yield list(map(tuple, chunk))

def execute(self, context):
    with tempfile.NamedTemporaryFile() as f_source:
        s3_client.download_file(self.s3_bucket, self.s3_key, f_source.name)
        with open(f_source.name, 'r') as f:
            csv_reader = csv.reader(f, delimiter='|')
            for chunk in self.gen_chunks(csv_reader):
                logger.info('starting in chunk process')
                orcl.bulk_insert_rows(table=self.oracle_table,rows=chunk, target_fields=self.target_fields,  commit_every=10000)

A: Idk if you have an option to try pandas, if yes then this could possibly be your answer.
I find pandas faster when working with millions of records in a csv,
here is some code that will help you
import pandas as pd

chunks = pd.read_csv(f_source.name, delimiter="|", chunksize=100000)
for chunk in chunks:
    for row in chunk.values:
        print(row)

pandas provides a lot of options with read_csv :
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html


text:
Q: DB2 Stored Procedures- looping through values? Okay, so I'm a novice at writing stored procedures.  I'm trying to perform a function similar to a foreach() you would see in a programming language.  Right now I have a temp table populated with the values I'd like to loop through.  I would like to (for each value in this table) execute a SQL statement based upon that value.  So, here's my pseudocode to illustrate what I'm really after here:
foreach(value in my temp table) {
  SELECT * FROM TABLE WHERE column_x = value
}

No I know nothing of stored procedures so how can I get this done?  Here's my script so far:
DROP TABLE SESSION.X;

CREATE GLOBAL TEMPORARY TABLE
  SESSION.X (
    TD_NAME CHAR(30)
  );

INSERT INTO
  SESSION.X
    SELECT DISTINCT
      TD_NAME
    FROM
      DBA.AFFIN_PROG_REPORT
    WHERE
      TD_NAME IS NOT NULL;

Any help is very much appreciated!

A: You need, by example, a cursor.
See the example: https://stackoverflow.com/a/4975012/3428749
See the documentation: https://msdn.microsoft.com/pt-br/library/ms180169(v=sql.120).aspx


text:
Q: Detect all accents not found in English or French I find myself needing to detect whether a string contains any characters that do not exist in English or French. The string is gathered via HTML input field.
I have found a few examples of how to normalize the string, but this is NOT what I need to do (french accents should not be normalized).
So far, I find myself doing this:
if (str.includes(invalidAccents)){
    //do something
} else {
    //do something else
}

with a list I put together stored in an array:
var invalidAccents = [
    'á', 'ã', 'ä', 'å', 'ą', 'æ',
    'ĉ', 'ć',
    'ę',
    'ĝ',
    'ĥ',
    'í', 'ì', 'ł',
    'ĵ',
    'ñ', 'ń',
    'ó', 'ò', 'õ', 'ö', 'ø', 'œ', 'ó',
    'ŝ', 'ś',
    'ú', 'ŭ',
    'ÿ', 'ý',
    'ž', 'ź', 'ż',
    'ª',
    'ð',
    'ß',
    'ƒ',
    'þ',
    'µ',
    'Á', 'Ã', 'Ä', 'Å', 'Ą', 'Æ',
    'Ĉ', 'Ć',
    'Ę',
    'Ĝ',
    'Ĥ',
    'Í', 'Ì', 'Ł',
    'Ĵ',
    'Ñ', 'Ń',
    'Ó', 'Ò', 'Õ', 'Ö', 'Ø', 'Ó', 'Œ',
    'Ŝ', 'Ś',
    'Ú', 'Ŭ',
    'Ÿ', 'Ý',
    'Ž', 'Ź', 'Ż',
    'Ð',
    'Þ'
];

but this is far from efficient and far from exhaustive.
Does anyone have an alternative solution or at least a place where I can find a complete list of accents to complete what I've got going?

A: Well, the short answer is: aside using lists, you can use Unicode ranges, but this way requires to iterate strings and check each character separately..
See charCodeAt and such.
If you look at Unicode table, you can see that codes 192-214, 217-221, 224-229 etc correspond to symbols with accents (I'd recommend to check it youself, I'm not sure whether 'ß' is called a symbol with accent).
Iterating to check those can look like:
function containsAccented(str) {
    const ranges = [[192,214], [217,221], ....];
    for(let c of str) {
        let code = c.charCodeAt(0);
        for(let range of ranges)
            if(code >= range[0] && code <= range[1])
                return true;
    }
    return false;
}

If you want to automate somehow creating the ranges themselves, you have to find a proper definition of "not found in English or French" and whether some service describes those, not sure if there's any.

A: You are probably best off approaching this somewhat differently: check if the string only contains valid characters, rather than checking if it doesn't contain invalid characters. Once you've figured what range would work best, you can use a regular expression to solve this kind of task. For example, let's say the acceptable characters are A-Z, irregardless of case; and whitespace is okay too. We would create this regular expression:
var validCharactersRegexp = /^[a-zA-Z\s]+$/i;

That looks like a pretty big code, if you aren't familiar with regexps! Let's break it down:

*

*The whole thing is wrapped in slashes (/). This is the syntax that JavaScript uses for regular expressions. (We could do = new RegExp('^[a-zA-Z\s]+$', 'i') and get the same result, but /blah/ syntax is more concise and common.)

*^ means that when we use this regexp, we'll be starting at the very beginning of the string.

*[A-Z\s] is a regular expression shorthand that means "any of these characters, but not any other character". A-Z are our letters; \s means any whitespace character.

*The +$ part means we'll be searching for whatever's immediately before the +, until we reach $ - that's similar to ^, but it means the end of the string. Essentially, this means we'll be searching the entire string and making sure that every character in it matches the regular expression code before +.

*At the end, after the /, the i is a flag which means that the regular expression should be case-insensitive. (There are several flags available to us in JavaScript, but i is the only one that matters here.)

Now that we've got our actual regular expression, we have to use it to check if an input string is valid - that is, if it matches our regular expression. We'll use the .test() function to do that:
function isValid(string) {
    return validCharactersRegexp.test(string);
}

Just to show this works, here's a quick demo:

var validCharactersRegexp = /^[A-Z\s]+$/i;

function isValid(string) {
    return validCharactersRegexp.test(string);
}

// Should be true.
console.log(isValid('apple'));

// Should also be true.
console.log(isValid('BaNaNa'));

// Should also be true!
console.log(isValid('Thou art a programmere'));

// Should be false - we didn't include punctuation in our regular expression after all.
console.log(isValid('Art thou a programmere?'));

// Should be false - "à" isn't in our regular expression.
console.log(isValid('Voilà'));

(PS: If you really wanted to use a blacklist, i.e. to search for invalid characters rather than valid ones, a regular expression would work for that too. Just do [^...], where ... are the characters that aren't allowed. The caret means the [..] will behave the opposite as normal - it'll match only if the current character is not one of the ones it specifies. Remember to adjust the regular expression accordingly - in this case, instead of searching for all characters being valid, we're searching for any character being invalid. So no need for ^[..]+$ - instead we'd just do /[^...]/.test(string), to see if an invalid character appears anywhere in the string.)

A: Create a list of the valids one, this list is kwown and short.
You can find inspiration with the iso-8859-15 charset:
https://fr.m.wikipedia.org/wiki/ISO/CEI_8859-15


text:
Q: Titanic Dataset. Logistic Regression Model. Confusion Matrix gives 0 as output I am running the logistic regression model on the Titanic Dataset with the below code:
#Modeling

#Split into train and test and fit the logistic regression model

titanic_train <- titanic_complete[1:891,]
titanic_test <- titanic_complete[892:1309,]

##############Logistic Regression ###############################

glm_model = glm(Survived~.,data= titanic_train, family = 'binomial')
summary(glm_model)

## Using anova() to analyze the table of devaiance
anova(glm_model, test="Chisq")

final_model = glm(Survived~Sex + Pclass + Age + SibSp + Cabin_f, data = titanic_train, family = 'binomial')
summary(final_model)

varImp(glm_model)

glm.pred <-predict(final_model, titanic_test, type = 'response')
glm.pred <- ifelse(glm.pred > 0.5, "yes", "no")

glm.pred

confusionMatrix(glm.pred, titanic_test$Survived)

As a result I've got this error message:
> confusionMatrix(glm.pred, titanic_test$Survived)
[1] no  yes
<0 rows> (or 0-length row.names)
In Ops.factor(predictedScores, threshold) :
  '<' not meaningful for factors

Cannot understand this error message and what is wrong. The model is working fine on the train data.
I assume it is related to the threshold i apply to the Survived variable (which is a factor variable - 1,0).


text:
Q: Citrix remote disconnect / Remote disconnect source Consider xen app server hosting published application. Is it possible to find out if the remote disconnect  was triggered by citrix or other source ?

A: if it was disconnect by Citrix then it normally because of the idle timeout and if this is the case then there will be a event in the windows event stating that the session was disconnected because of idle timeout


text:
Q: delphi graphical component to activex I made a graphical component which ancestor has to be TGraphiccontrol because I need to paint to the canvas.
Now I want to convert this component to an activex control but that seems to be only possible when the component is a descendant from TWincontrol.
How do I solve this problem?

A: It is incorrect that you must only use a TGraphicControl in order to paint. Base your control on TCustomControl instead. This provides you with a canvas which you can use the same way, and is inherited from the TWinControl.


text:
Q: Pass a variable in an html template in django I need to create in a html django template a form with a select dinamically created: I read values from a txt file and I store it in a dict, when I call the render to response I pass this dict but when I try to print its values in the template it doesn't print anything.
This is my views:
def home(request):

   i=0
   d = {}
   with open("static/my_file.txt") as f:
      for line in f:
        key=i
        val = line.rstrip()
        d[int(key)] = val
        i=i+1

   return render_to_response('home.html', var=d)

and this is the print in the html template:
{% for val in var %}
   {{ val.value }}
{% endfor %}

Can help me?

A: The Django documentation for for-loops in templates shows that the syntax for dicts is slightly different. Try:
{% for key, value in var.items %}
    {{ value }}
{% endfor %}

A: Try this instead of the above jinja file.
If you need just values of var, and if var is dictionary, then this below code would work for you.
{% for val in var.values() %}
   {{ val }}
{% endfor %}

A: you have error in view, you need to pass context as dictionary
    from django.shortcuts import render
def home(request):

   i=0
   d = {}
   with open("static/my_file.txt") as f:
      for line in f:
        key=i
        val = line.rstrip()
        d[int(key)] = val
        i=i+1

   return render(request,'home.html', {'var':d})

A: If you want to pass just the variable or all variable available (local variable) in the view.py to your template just pass locals() in your case should be:
view.py:
def home(request):

   i=0
   d = {}
   with open("static/my_file.txt") as f:
      for line in f:
        key=i
        val = line.rstrip()
        d[int(key)] = val
        i=i+1

   return render('home.html', locals())

template:
{% for key,value in d.items %}
   {{ value }}
{% endfor %}


text:
Q: Select the first 10 rows - Laravel Eloquent So far I have the following model:
class Listing extends Eloquent {
     //Class Logic HERE
}

I want a basic function that retrieves the first 10 rows of my table "listings" and passes them on to the view (via a controller?).
I know this a very basic task but I can't find a simple guide that actually explains step-by-step how to display a basic set of results, whilst detailing what is required in the model, controller and view files.

A: this worked as well IN LARAVEL 8
Model::query()->take(10)->get();

A: The simplest way in laravel 5 is:
$listings=Listing::take(10)->get();

return view('view.name',compact('listings'));

A: Another way to do it is using a limit method:
Listing::limit(10)->get();

This can be useful if you're not trying to implement pagination, but for example, return 10 random rows from a table:
Listing::inRandomOrder()->limit(10)->get();

A: First you can use a Paginator. This is as simple as:
$allUsers = User::paginate(15);

$someUsers = User::where('votes', '>', 100)->paginate(15);

The variables will contain an instance of Paginator class. all of your data will be stored under data key.
Or you can do something like:
Old versions Laravel.
Model::all()->take(10)->get();

Newer version Laravel.
Model::all()->take(10);

For more reading consider these links:

*

*pagination docs

*passing data to views

*Eloquent basic usage

*A cheat sheet

A: This also worked in Laravel 9
Model::query()->take(10)->get();


text:
Q: karma: unit testing controller that listens on angular-ui-router event I try to unit test an angularJS controller with Kara/Sinon/Jasmine.
The controller listens to state changes from angular-ui-router to call a service.
I stubbed the service method (update) using sinon and i use $broadcast to throw the event in the tests.
I use $apply to fire the event.
However, it seems the controller does not seem to react.
I try to check for teh sinon stubbed method and i also use console.log to see weather or not the controller reacts - but it does not.
It does in the manual browser test, so i guess it is my test that needs to be fixed (should be the other way round, i know).
What am i doing wrong here?
the karma test specs:
'use strict';
describe('controllers', function() {
    beforeEach(module('myApp.controllers'));
    beforeEach(module('myApp.services'));
    beforeEach(module('ui.router'));

    describe('myAppController', function() {
        var scope, ctrl;

        beforeEach(inject(function(
            $rootScope, $controller, $injector,ParamsHelper) {

            scope = $rootScope.$new();
            scope.ParamsHelperStub  = sinon.stub(ParamsHelper, 'update');

            ctrl = $controller('myAppController', {
                $scope: scope,
                ParamsHelper: scope.ParamsHelperStub
            });

        }));

        it('should use ParamsHelper if is deepLink', function() {
            var event       = {};
            var toState     = {name:'regions'};
            var toParams    = ['test'];
            scope.AppSettingsStub.state.isDeepLink = true;
            scope.$broadcast("$stateChangeStart", event, toState, toParams);
            scope.$apply();

            expect(scope.ParamsHelperStub.calledWith(['test'])).toBeTruthy();
        });

    });
});

From the controller:
...

rootScope.$on('$stateChangeStart',
  function(event, toState, toParams) {
    console.log('VibeController: $stateChangeStart Event catched');
    ParamsHelper.update(toParams);

    ...

A: The problem was in the scope.
To fire an event that can be recognized by the controller i need to fire it in the rootScope context.
I added the rootScope in the initial injection and then edited the broadcasting command accordingly:
describe('myAppController', function() {
  var scope, ctrl, rootScope;

  beforeEach(inject(function(
    $rootScope, $controller, $injector, ParamsHelper) {

    rootScope = $rootScope;

    ...

    rootCope.$broadcast("$stateChangeStart", event, toState, toParams);


text:
Q: Injection new stylesheet rules I am using some javascript on my page to put some addons on page, but javascript add some css styles and those new css styles override existing css styles on page.
Is there a way to disable new css styles. I know I can use javascript to delete new created css rules, but I dont want to use javascript. Is it posible?
Thanks

A: Just look at this css path and do the next code:
 $("rel").each(function(){
      if($(this).attr("href")=="insert you path here"){
        $(this).attr("disabled", "disabled");
       }
    });

A: You can try to raise the priority of your css rules by some simply tricks.
For example, you can give an id attribute to your most external container element in the html, for example id="yourContainerId".
Then you can raise the priority of your css classes by prepending #yourContainerId to all your classes that you want to raise:
#yourContainerId .yourClass1 {

}

#yourContainerId .yourClass2 {

}

etc..
if you want to know more about css priority, this is a good resource:
http://www.w3.org/wiki/CSS/Training/Priority_level_of_selector
Note: this trick cannot work in some particular conditions, because if your javascript writes inline style on your html elements there is nothing to do, you can only remove them with js.
Tell me if you need a jsFiddle example


text:
Q: Firebase - Should Anonymous UID get deleted after Existing user is Logged In? I have Anonymous enabled as one of my Sign-in providers so that a user can browse my app without actually needing to login.
Once an anonymous user is created, they get a random uid

If that user never created an account, when they do sign up via email or phone, they get a new uid.
But if the user had previously signed up, then signs out, when they open the app they'll have random uid. When they sign in with their actual email or phone, they'll end up using their actual uid, at which point the random uid will be useless. Should I delete that random uid from the database or keep it there? I haven't found anything that suggests what to do with anonymous uids that are no longer in use.
For example:
let anonymousUserUID = Auth.auth().currentUser?.uid // "abc..."
let anonymousUser = Auth.auth().currentUser

let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationID, verificationCode: verificationCode)

Auth.auth().signIn(with: credential, completion: { (authDataResult, error) in

   guard let userId = authDataResult?.user.uid else { return }

   let usersRef = Database.database().reference()
        .child("users")
        .child(userId)
   usersRef.observeSingleEvent(of: .value, with: { [weak self](snapshot) in

        if snapshot.exists() {
           // turns out this anonymous user is already registered and their uid is "xyz..."

           // is it a good practice to now delete the anonymousUser?
        }
    })
})

A: As shown in the documentation on Firebase Authentication limits, each project can have up to 100 million anonymous accounts.
Leaving the UIDs for abandoned anonymous user accounts in the system is mostly harmless. But if you get millions of them or they get in the way for another reason, you can delete them.


text:
Q: Can Safari be set to "search on type" within the page displayed without having to use CMD + F? This used to be a feature of Firefox, yeah, the awesome browser that would blow Google Chrome out of the water on any day of the week and twice on Sunday.
So, if it is, how is it possible on Safari?


text:
Q: Missing semicolon error for functions returning iterator I am trying to make a rough abstract implementation of an Interval Tree, but I am getting a strange error. All of my functions that return a std::map<ui16, Node>::iterator are giving me the error:

error C2146: syntax error : missing ';' before identifier 'FOO'

Where FOO is the name of the function.
ui16 is simply a typedef unsigned short.
Any ideas?
#include "stdafx.h"
#include <map>

//Very rough implementation of a specialized interval tree
//TODO: Replace std::map with a custom red-black tree implementation or something similar

template <typename T>
class IntervalTree {
public:

    struct Node {
        Node(T Data, ui16 Length) : data(Data), length(Length) {}
        T data;
        ui16 length;
    };

    inline void clear() {
        std::map<ui16, Node>().swap(_tree);
    }

    inline std::map<ui16, Node>::iterator getInterval(ui16 index) const {
        auto it = _tree.lower_bound(index);
        if (it->first != index) {
            return it--;
        }
        return it;
    }

    inline std::map<ui16, Node>::iterator insert(std::pair<ui16, Node> pair) {
        return _tree.insert(pair);
    }

    std::map<ui16, Node>::iterator insert(ui16 index, T data) {
        //Find containing interval
        auto it = _tree.lower_bound(index);
        if (it->first != index) {
            it--;
        }
        //Its already in the tree
        if (it->second.data == data) {
            return it;
        }

        //If the interval is only 1, just change its value
        if (it->second.length == 1) {
            it->second.data = data;
            return it;
        }

        //Check if its at the right edge of the interval
        if (index == it->first + it->second.length - 1) {

            auto next = it + 1;
            //if it should add to the next interval
            if (data == next->second.data) {
                it->second.length--;
                it = _tree.insert(make_pair(index, Node(data, next->second.length + 1)));
                _tree.erase(next);
                return it;
            } else { //else we should add an interval and modify left interval
                //Modify left interval
                it->second.length--;
                //Insert new interval
                return _tree.insert(make_pair(index, Node(data, 1)));
            }
        } else if (index == it->first) { //if its at the beginning of the interval
            //Insert right interval
            _tree.insert(make_pair(index + 1, Node(it->second.data, it->second.length - 1)));
            _tree.erase(it);
            _tree.insert(make_pair(index, Node(data, 1)));
        } else { //else its in the middle of the interval
            //Insert right interval
            _tree.insert(make_pair(index + 1, Node(it->second.data, it->second.length - (index - it->first) - 1)));
            //Modify left interval
            it->second.length = index - it->first;
            //Insert new middle interval
            return _tree.insert(make_pair(index, Node(data, 1)));
        }
        return _tree.end();
    }

    inline std::map<ui16, Node>::iterator begin() const { return _tree.begin(); }
    inline std::map<ui16, Node>::iterator end() const { return _tree.end(); }

private:
    std::map <ui16, Node> _tree;
};

A: C2146 gives a rather unhelpful error message but ultimately the problem is you're missing the typename keyword where there are dependent scopes. iterator depends on the instantiation of std::map<ui16, Node> and requires the typename keyword to disambiguate your usage. For more information, please consult Where and why do I have to put the "template" and "typename" keywords?. For a more helpful error message, see the following example from gcc:
main.cpp:83:12: error: need 'typename' before
'std::map<short unsigned int, IntervalTree<T>::Node>::iterator'
because 'std::map<short unsigned int, IntervalTree<T>::Node>' is a dependent scope

     inline std::map<ui16, Node>::iterator begin() const { return _tree.begin(); }

Just replace std::map<ui16, Node>::iterator with typename std::map<ui16, Node>::iterator and you're good to go.


text:
Q: Tune SQL Server Express using Profiler? I have a SQL Server 2005 database... a copy of it is running in development on a full version of SQL server. Another copy is running in SQL Server 2005 Express on a web server.
I've used SQL Profiler and saved a Tuning trace log from activity on the SQL Express copy of the database.
I want to use the saved trace log in the Database Engine Tuning Advisor...
If I try when connecting the Advisor to the Express database, I am told that Express is not supported.
If I try when connecting the Advisor to the SQL Server database, I get empty results.
Is there any way to do this?

A: I think you would need a copy of the database from the Express instance restored to the full instance.  The advisor looks at the schema to make it's tuning advice.

A: You should be able to tune an identical database on the local development server using trace data collected from a remote production server (Express).
But you cannot use trace tables stored in the remote server to do this.
According to Considerations for Using Database Engine Tuning Advisor, "Database Engine Tuning Advisor cannot tune a workload in a trace table that resides on a remote server"
But I guess you are using trace files, so this should not be an issue.
If you don't get any recommendations, you should first check the list on the previously mentioned MSDN page:

Database Engine Tuning Advisor might
  not make recommendations under the
  following circumstances:
The table being tuned contains less
  than 10 data pages.
The recommended indexes would not
  offer enough improvement in query
  performance over the current physical
  database design.
The user who runs Database Engine
  Tuning Advisor is not a member of the
  db_owner database role or the sysadmin
  fixed server role. The queries in the
  workload are analyzed in the security
  context of the user who runs the
  Database Engine Tuning Advisor. The
  user must be a member of the db_owner
  database role.

A: I think all you need to do is trace the DB to a table  and then point tuning advisor at the data in the table that contains the trace results.  That way I dont think you need to move any databases around.

A: I also found that I could edit the trace file in SQL Profiler and remove any columns that specify the login or database name.  After that, the Tuning Advisor worked.


text:
Q: Expose CSRF tokens to the client-side I have a web application that consists of two parts:

*

*app-front React application, that deployed in AWS CloudFront, and avaliable via app-example.com

*app-api Node.js + Koa application, that deployed in EC2 instance (behind load balancer), and avaliable via api.app-example.com

app-api has CSRF protection, that uses a secret key in user session and token that is verified on the server side. (https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Synchronizer_Token_Pattern)
How can app-api expose CSRF tokens to the app-front ?
There are several ways:

*

*Include the token in html pages:
<meta name="csrf-token" content="{{csrfToken}}">
But this method does not work for me, because app-api doesn't serve html pages (app-front located in AWS CloudFront)

*Set CSRF tokens in cookies via AJAX
server.get('/csrf', (req, res) => {
    res.cookie('_csrf' , res.locals._csrf, {expire : new Date() + 9999});
    return res.json({
        "status": "success"
    })
})
But this is an additional request that I would like to avoid.
Maybe there is another solution?


text:
Q: Nginx Reverse Proxy 301 Redirects I'm trying to set up an nginx proxy in a way I'm not sure will work... Basically, I have 3 servers running. Server A is an nginx reversed proxy. Server B and C are backend servers. When a client requests http://domain.com/file.jpg, it hits Server A than passes the request back to Server B. The file could be on server B or C. If server B doesn't have the file, it sends a 301 redirect to the file on Server C. The problem with this is the 301 goes back to the browser and changes the URL in the client.
I'm wondering if it's possible to have the 301 stay internal. Nginx would see and follow the 301 to the correct file location on Server C, but the client wouldn't know the difference. The client shouldn't be able to tell whether the file is on B or C, or even know the addresses of them...
Thanks!

A: You can consider using proxy_next_upstream for that.
http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_next_upstream

A: Using upstream to setup load balancing for reverse proxy, it fill auto fetch data from 2 backend server.


text:
Q: Estimating truncation point in Gaussian mixture I have data modeled as a mixture of two Gaussian distributions. The data is "clipped" i.e., there is data only for values greater than a threshold $t$, even though it is feasible for data to exist in the range $(-\inf, t]$. How can I estimate the probability distribution of $t$, given the data?

A: There are (at least) two possible models associated with this question:

*

*A truncated Gaussian mixture$$p{\cal N}^+(\mu_1,\sigma_1,t)+(1-p){\cal N}^+(\mu_2,\sigma_2,t)$$where $t$ is the truncation point and ${\cal N}^+(\mu_2,\sigma_2,t)$ denote the truncated Normal distribution with density $\sigma_1^{-1}\varphi(\sigma_1^{-1}[x-\mu_1])\Phi^{-1}(\sigma_1^{-1}[\mu_1-t])$

*A censored Gaussian mixture$$p{\cal N}(\mu_1,\sigma_1)+(1-p){\cal N}(\mu_2,\sigma_2)$$where all $n_t$ observations less than $t$ are not observed (but accounted for). If $n_t$ is unknown, this model is equivalent to the first one.

If we adopt a Bayesian approach with a prior $\pi(\theta)$ on the parameter $\theta=(\mu_1,\mu_2,\sigma_1,\sigma_2,p,t)$, a Gibbs sampler can be constructed by

*

*allocating the observations $x_1,\ldots,x_n$ to either component with probabilities $$p\sigma_1^{-1}\varphi(\sigma_1^{-1}[x_i-\mu_1])\Phi^{-1}(\sigma_1^{-1}[\mu_1-t])$$ and $$(1-p)\sigma_2^{-1}\varphi(\sigma_2^{-2}[x_i-\mu_2])\Phi^{-1}(\sigma_2^{-1}[\mu_2-t])$$ (up to a constant), thus creating a latent vector $(z_1,\ldots,z_n)$;

*simulating $(\mu_1,\mu_2,\sigma_1,\sigma_2,p)$ conditional on $t$,$(z_1,\ldots,z_n)$ and $x_1,\ldots,x_n$ (which may involve a Metropolis-Hastings step);

*simulating $t$ conditional on everything else, which involves a Metropolis-Hastings step.

In the case of the censored mixture (#2), the $n_t$ censored observations are also to be simulated on step 1.


text:
Q: R: Expand rows according to start and end date and calculate hours between days My question extends this one: Generate rows between two dates into a data frame in R
I have a dataset on admissions, discharges and lengths of stay (Stay_in_days) of patients from a hospital. It looks like this:
ID Admission           Discharge             Stay_in_days
1    2020-08-20 15:25:03 2020-08-21 21:09:34 1.239
2    2020-10-04 21:53:43 2020-10-09 11:02:57 4.548
...

Dates are in POSIXct format so far.
I aim for this:
ID   Date                 Stay_in_days
1    2020-08-20 15:25:03  0.357
1    2020-08-21 21:09:49  1.239
2    2020-10-04 21:53:43  0.087
2    2020-10-05 00:00:00  1.087
2    2020-10-06 00:00:00  2.087
2    2020-10-07 00:00:00  3.087
2    2020-10-08 00:00:00  4.087
2    2020-10-09 11:02:57  4.548
...

What I have done so far:
M <- Map(seq, patients$Admission, patients$Discharge, by = "day")
patients2 <- data.frame(
  ID = rep.int(patients$ID, vapply(M, length, 1L)),
  Date = do.call(c, M)
)

patients <- patients %>%
mutate(
 Date2=as.Date(Date, format = "%Y-%m-%d"),
 Dat2=Date2+1,
 Diff=difftime(Date2, Date, units = "days")
)

but this gives me:
ID   Date                 Date2      Diff
1    2020-08-20 17:25:03  2020-08-21 0.375
1    2020-08-21 17:25:03  2020-08-22 0.357
2    2020-10-04 23:53:43  2020-10-05 0.087
2    2020-10-05 23:53:43  2020-10-06 0.087
2    2020-10-06 23:53:43  2020-10-07 0.087
2    2020-10-07 23:53:43  2020-10-08 0.087
2    2020-10-08 23:53:43  2020-10-09 0.087
...

Strangely enough, it adds two hours to the Admission date but calculates the correct length of stay. Can someone explain?
Here is some data:
structure(list(ID = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20), Admission = structure(c(1597937103.872,
1598717768.704, 1599060521.984, 1599758087.168, 1599815496.704,
1600702198.784, 1600719631.36, 1601065923.584, 1601119400.96,
1601215476.736, 1601236710.4, 1601416934.4, 1601499640.832, 1601545647.104,
1601587328, 1601644868.608, 1601741206.528, 1601848423.424, 1601901245.44,
1601913828.352), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
    Discharge = structure(c(1598044189.696, 1598897337.344, 1599144670.208,
    1599845118.976, 1599842366.464, 1602733683.712, 1603372135.424,
    1601125168.128, 1601314173.952, 1605193905.152, 1602190259.2,
    1601560720.384, 1601737143.296, 1602705634.304, 1602410460.16,
    1602698425.344, 1601770566.656, 1602241377.28, 1602780476.416,
    1602612048.896), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
    Stay_in_days = c(1.239, 2.078, 0.974, 1.007, 0.311, 23.513,
    30.7, 0.686, 2.254, 46.047, 11.036, 1.664, 2.749, 13.426,
    9.527, 12.194, 0.34, 4.548, 10.176, 8.081)), row.names = c(NA,
-20L), class = c("tbl_df", "tbl", "data.frame"))

Thanks in advance for your help!

A: You can achieve this with pivot_longer from tidyr.
Edit: with comments:
df1 <- df %>%
  select(ID = ID, date1 = Admission, date2 = Discharge, Stay_in_days) %>% # prepare for pivoting
  pivot_longer(
    cols = starts_with("date"),
    names_to = "Date1",
    values_to = "Date",
  ) %>% # pivot to longformat
  select(-Date1) %>% # remove temporary Date1
  relocate(Stay_in_days, .after = Date) %>% # change column order
  group_by(ID) %>%
  mutate(idgroup = rep(row_number(), each=1:2, length.out = n())) %>% # id for admission = 1 and for discharge id = 2
  mutate(Stay_in_days = replace(Stay_in_days, row_number() == 1, 0)) %>%  # set Admission to zero
  ungroup()

A: Though it is a bit crude but it'll work
library(tidyverse)
library(lubridate)

df %>%
  pivot_longer(cols = -c(ID, Stay_in_days), names_to = "Event", values_to = "DATE") %>%
  group_by(ID) %>%
  mutate(dummy = case_when(Event == "Admission" ~ 0,
                           Event == "Discharge" ~ max(floor(Stay_in_days),1))) %>%
  complete(dummy = seq(min(dummy), max(dummy), 1)) %>%
  mutate(Event = ifelse(is.na(Event), "Dummy", Event),
         DATE = if_else(is.na(DATE), first(DATE)+dummy*24*60*60, DATE),
         Stay_in_days = case_when(Event == "Admission" ~ as.numeric(difftime(ceiling_date(DATE, "day"), DATE, units = "days")),
                                   Event == "Discharge" ~ Stay_in_days,
                                   TRUE ~ dummy + as.numeric(difftime(ceiling_date(first(DATE), "day"), first(DATE), units = "days")))) %>%
  select(ID, DATE, Stay_in_days)

# A tibble: 199 x 3
# Groups:   ID [20]
      ID DATE                Stay_in_days
   <dbl> <dttm>                     <dbl>
 1     1 2020-08-20 15:25:03        0.358
 2     1 2020-08-21 21:09:49        1.24
 3     2 2020-08-29 16:16:08        0.322
 4     2 2020-08-30 16:16:08        1.32
 5     2 2020-08-31 18:08:57        2.08
 6     3 2020-09-02 15:28:41        0.355
 7     3 2020-09-03 14:51:10        0.974
 8     4 2020-09-10 17:14:47        0.281
 9     4 2020-09-11 17:25:18        1.01
10     5 2020-09-11 09:11:36        0.617
# ... with 189 more rows

Explanation of logic For the first date in every ID, the stay_in_days gives the duration from admission date-time to following 24 Hrs.  For intermediate dates, it just adds 1 to previous value.  For discharge_date it retains the stay value calculated prior to pivoting.  Hope this was you after.
Explanation of code After pivoting longer, I used a dummy column to create intermediate date-time objects.  After that I just mutate the columns for generating output as described above.


text:
Q: Function to bind member functions to object instances in C++ Recently, I've frequently been binding member functions to instances of objects.  Rather than using a combination of std::bind, std::mem_fn and std::ref, I'd like to combine all of these into one function to handle it all automatically.
For example, consider the following code:
#include <functional>
#include <iostream>
#include <string>

// This is the function I'd like to have working:
template <class T, typename RETURN_TYPE, typename... Arguments>
std::function<RETURN_TYPE(Arguments...)> obj_bind(RETURN_TYPE (T::*in_fun)(), T & obj, Arguments... params)
{
  return std::bind( std::mem_fn(in_fun), std::ref(obj), params...);
}

int main()
{
  // Standard use of push_back member function (our test case):
  std::string test_obj = "Test 1: ";
  test_obj.push_back('A');
  std::cout << test_obj << std::endl;

  // This WORKS:
  auto test_fun = std::bind( std::mem_fn(&std::string::push_back), std::ref(test_obj), 'B');

  // But I'd like to use this instead:
  // auto test_fun = obj_bind( &std::string::push_back, test_obj, 'C');

  test_obj = "Test 2: ";
  test_fun();
  std::cout << test_obj << std::endl;
}

My obj_bind function actually works fine on member functions with no arguments, so I'm pretty sure my problem lies in how I'm handling those, but after several failed attempts to fix it, I thought I'd try here for advice.

A: Before diving into fixing your binder, a few notes:

*

*You don't really need to use std::mem_fn() for the first argument of std::bind() as std::bind() already knows how to deal with member function pointers.

*The type of taking an address of a member function is undefined. That is, you can't really on std::string::push_back being a member function pointer taking just one argument.

*Instead of using std::ref(testobj) you could jut juse &testobj.

You can't deduce a member function like this if it needs to have argument: you'll need to specify the argument:
template <class T, typename RETURN_TYPE, typename...Args, typename... Arguments>
std::function<RETURN_TYPE(Arguments...)>
obj_bind(RETURN_TYPE (T::*in_fun)(Args...), T & obj, Arguments... params) {
    ...
}

This gets you over the immediate error. The next problem is that you somehow related the bound arguments to the type of function being called. Of course, that's not how it works. In your case, the resulting argument actually doesn't take any arguments, i.e., you'd have a declaration like this:
template <class T, typename RETURN_TYPE, typename... Args, typename... Arguments>
std::function<RETURN_TYPE()>
obj_bind(RETURN_TYPE (T::*in_fun)(Args...), T & obj, Arguments... params) {
    ...
}

In case you actually use a placeholder with your function, the returned std::function<RC(...)> would actually take some argument. Figuring these arguments out is somewhat non-trivial. When restricting the argument type to a pointer to function or a pointer to member function it should be doable to return an appropriate function object, though.
Just for the fun of it, here is an implementation which seems to deal with placeholders (it isn't thoroughly tested, though):
#include <functional>
#include <iostream>
#include <string>

using namespace std::placeholders;

struct foo
{
    void f(int i, double d, char c) {
        std::cout << "f(int=" << i << ", double=" << d << ", char=" << c << ")\n";
    }
};

template <typename...> struct type_list;

template <typename, typename, typename, typename> struct objbind_result_type;
template <typename RC, typename... RA>
struct objbind_result_type<RC, type_list<RA...>, type_list<>, type_list<> > {
    typedef std::function<RC(RA...)> type;
};

template <typename RC,
          typename... RA,
          typename A0, typename... A,
          typename B0, typename... B>
struct objbind_result_type<RC, type_list<RA...>,
                           type_list<A0, A...>,
                           type_list<B0, B...> >;

template <bool, typename, typename, typename, typename, typename>
struct objbind_result_type_helper;
template <typename A0, typename RC, typename... RA, typename... A, typename...B>
struct objbind_result_type_helper<true, A0, RC, type_list<RA...>, type_list<A...>, type_list<B...> > {
    typedef typename objbind_result_type<RC, type_list<RA..., A0>, type_list<A...>, type_list<B...> >::type type;
};

template <typename A0, typename RC, typename... RA, typename... A, typename...B>
struct objbind_result_type_helper<false, A0, RC, type_list<RA...>, type_list<A...>, type_list<B...> > {
    typedef typename objbind_result_type<RC, type_list<RA...>, type_list<A...>, type_list<B...> >::type type;
};

template <typename RC,
          typename... RA,
          typename A0, typename... A,
          typename B0, typename... B>
struct objbind_result_type<RC, type_list<RA...>,
                           type_list<A0, A...>,
                           type_list<B0, B...> > {
    typedef typename objbind_result_type_helper<bool(std::is_placeholder<B0>::value), A0,
                                                RC, type_list<RA...>,
                                                type_list<A...>,
                                                type_list<B...> >::type type;
};

// This is the function I'd like to have working:
template <class T, typename RETURN_TYPE, typename...Args, typename... Arguments>
typename objbind_result_type<RETURN_TYPE, type_list<>, type_list<Args...>, type_list<Arguments...> >::type
obj_bind(RETURN_TYPE (T::*in_fun)(Args...), T & obj, Arguments... params)
{
  return std::bind(in_fun, &obj, params...);
}

int main()
{
  foo fo;
  auto fun = obj_bind(&foo::f, fo, _1, 2.34, _2);
  fun(17, 'b');
}


text:
Q: How to make a responsive amp-carousel Is there any way to make a responsive amp-carousel?
I've tried to use the attribute layout="responsive" on images within the carousel, but it doesn't work.

A: As documented here: https://github.com/ampproject/amphtml/blob/master/extensions/amp-carousel/amp-carousel.md amp-carousel does not currently support layout="responsive"
That means that you can't currently create a responsive amp-carousel.
Please file a new issue: https://github.com/ampproject/amphtml/issues/new to track this feature request.

A: I filed a new issue on GitHub and layout="responsive" is supported if:

*

*the amp-carousel is type="slides".

*the user adds a CSS rule targeting amp-img img to set object-fit: contain.

A: Per @Bruno's answer this will work if you use layout="responsive" and type="slides" and you enable the amp dev channel - https://cdn.ampproject.org/experiments.html
Obviously this is not yet in production.

A: Mate, use amp-base-carousel instead:
<amp-base-carousel loop="true"  width="600" height="400" layout="responsive">
        <amp-img src="https://source.unsplash.com/Ji_G7Bu1MoM/600x400" width="600" height="400" layout="responsive"></amp-img>
        <amp-img src="https://source.unsplash.com/4yCXNMLP9g8/600x400" width="600" height="400" layout="responsive"></amp-img>
        <amp-img src="https://source.unsplash.com/QrgRXH81DXk/600x400" width="600" height="400" layout="responsive"></amp-img>
        <amp-img src="https://source.unsplash.com/8QJSi37vhms/600x400" width="600" height="400" layout="responsive"></amp-img>
    </amp-base-carousel>


text:
Q: How do I get phone numbers from file in correct format using awk? Working script needs tweaking These are the files:
project2.phone:
  Dave,7348389800
  Barry,3131234567
  Carl,2483445576
  Marci,3134491390
  Tom,2484962204
  Alden,6165564458

project2.day:
  Barry,tuesday
  Carl,friday
  Tom,sunday
  Alden,wednesday
  Dave,thursday
  Marci,saturday

My output looks like this:
Day            Name         Phone
 ____________________________________
SUNDAY         Tom       2484962204
MONDAY         Nobody
TUESDAY        Barry     3131234567
WEDNESDAY      Alden     6165564458
THURSDAY       Dave      7348389800
FRIDAY         Carl      2483445576
SATURDAY       Marci     3134491390
SUNDAY         Tom       2484962204

I need the output to look like this:
Day            Name         Phone
 ____________________________________
SUNDAY         Tom      (248)496-2204
MONDAY         Nobody
TUESDAY        Barry    (313)123-4567
WEDNESDAY      Alden    (616)556-4458
THURSDAY       Dave     (734)838-9800
FRIDAY         Carl     (248)344-5576
SATURDAY       Marci    (313)449-1390
SUNDAY         Tom      (248)496-2204

I can not get the phone numbers in correct format.
It only works when I use awk -F, -f project2.ksh project2.phone project2.day.
I need to be able to run ksh project2.ksh to get the output.
This is the script:
project2.ksh

      BEGIN     { split("SUNDAY;MONDAY;TUESDAY;WEDNESDAY;THURSDAY;FRIDAY;SATURDAY", week, ";") }

      FNR == NR { name2phone[$1] = gensub(/([0-9]{3})([0-9]{3})(.*)/, "(\\1) \\2-\\3", "g", $2 )
        next
      }

      { day2name[toupper($2)] = $1 }

           END       { fmtstr= "%-10s\t%s\t%s\n"

                         printf(fmtstr,"Day","Name","Phone")

                         print "____________________________________"

                     for(d=1;d< length(week); d++ )
                     {

                         cname = (week[d] in day2name ) ? day2name[ week[d] ] : "NOBODY"

                         printf( fmtstr, week[d], cname, name2phone[ cname])
                     }
      }

A: Some ideas with GNU awk:
$ awk '{match($0,/(...)(...)(.*)/,a);printf("(%s)%s-%s\n",a[1],a[2],a[3])}' <<<"333456789"
(333)456-789

$ awk '{match($0,/(...)(...)(.*)/,arr);printf( "(" arr[1] ")" arr[2] "-" arr[3])}' <<<"333456789"
(333)456-789

$ awk '{a=$0;printf("(%s)%s-%s\n",substr(a,1,3),substr(a,4,3), substr(a,7))}' <<<"333456789"
(333)456-789

To adapt it to your script try this one:
Replacing your last script line:
printf( fmtstr, week[d], cname, name2phone[ cname])

With bellow, should work ok:
ph=name2phone[ cname];
match(ph,/(...)(...)(.*)/,arr);
printf( fmtstr, week[d], cname, "(" arr[1] ")" arr[2] "-" arr[3])

A: {
  raw=$3; //or whichever column the phone# is in
  area=substr(raw,1,3);
  prefix=substr(raw,4,3);
  suffix=substr(raw,7);
  print $1, $2, "("area")"prefix"-"suffix
}

works for me

A: perl -F, -lane '

@ARGV and $Phone_of{$F[0]} = $F[1] =~ s/(...)(...)(.*)/($1)$2-$3/r;

@ARGV or $Person_of{uc $F[1]} = $F[0];

END {
   $fmt = join "\t", map { qq/%${_}s/ } qw/ -10 1 1 /;
   print sprintf $fmt, qw/ Day Name Phone /;
   print "_" x 37;
   for my $day ( map { uc($_ . day) } qw/ sun mon tues wednes thurs fri satur / ) {
      print sprintf $fmt, $day, $Person_of{$day} || "Nobody", $Phone_of{$Person_of{$day}};
   }
}

' project2.phone project2.day

We first fillup the hash %Phone_of with keys as names and values their phone numbers. Next, when @ARGV has gone zero, i.e., the last file (.day) is being processed, we populate the hash %Person_of with keys as uppercase day and value as person working on that day.
In the END{...} block, when both the files have been processed away, we first setup the format string and using that print the header. Finally, we loop over the days of the week (uppercased) and display the day, person working on that day (or nobody if nobody's working on that day), and the phone number of the person.
Result:
Day             Name    Phone
_____________________________________
SUNDAY          Tom     (248)496-2204
MONDAY          Nobody
TUESDAY         Barry   (313)123-4567
WEDNESDAY       Alden   (616)556-4458
THURSDAY        Dave    (734)838-9800
FRIDAY          Carl    (248)344-5576
SATURDAY        Marci   (313)449-1390

Caveats
No whitespace(s) in the input files (*.phone, *.day)


text:
Q: $V$ is finite dimensional iff $V'$ with the weak topology is normable Why is the following statement valid?  Note, $V$ is locally convex Hausdorff topological vector space over $\mathbb{C}$ and $V'$ is the space of all continuous linear maps from $V \to \mathbb{C}$.
$V$ is finite dimensional if and only if $V'$ with the weak topology is normable.
I believe that since $V$ is finite dimensional then $V'$ is finite dimensional.  Thus all topologies on $V'$ are the same and $V'$ is normable.  However, the other direction I am clueless as to the reasoning.

A: Clue: If $V'$ is infinite dimensional, then for every finite set $F\subset V''$ of functionals $\bigcap \{\ker: f\in F\}$ should be a non-zero subspace which, therefore can not be contained in a ball $\{f\in V':||f||<1\}$.


text:
Q: How do I set up a choice column in Windows Sharepoint Services 3 SP2 that contains the date/time and user identity that selected a particular choice? We are using WSS 3 SP2. I'd like to preface this by saying that while I have been programming for some time, I have not done any Sharepoint development before now, so I am very much a newbie in that respect.
Basically what we have is a Sharepoint wiki that contains support documentation about each of the various applications throughout our organization. Each application has a wiki page containing some of the more pertinent info (vendor support #, etc), and these wiki pages are created from a template.
Currently, there is one "choice" column on the template that lists all of our department work groups, and users can edit the individual wiki pages to check off their particular work group after they've verified that the relevant wiki page information is correct. Example:

[Checkbox] Help Desk
[Checkbox] Programming
[Checkbox] Networking

What I've been tasked with is adding functionality to the template column that does the following:

*

*list  the date that each checkbox was checked

*Indicate the user identity that checked the checkbox (logged on username is fine)

*display the percentage of checkboxes that have been checked

Example:

Application Verification: 66%
[Checkbox] Help Desk - verified by JohnDoe on 8/26/10
[Checkbox] Programming - Unverified
[Checkbox] Networking - verified by JaneDoe on 7/21/10

I have been playing around with web parts trying to get my feet wet, but I don't know enough about Sharepoint yet to understand if a new web part is the way to go or if I can extend the choice column to do this.
What is the best way to accomplish this with Sharepoint? Can someone point me in the proper direction?

A: The direction I would start in would be developing a custom field, that would store your info internally in some sort of custom structure (XML, comma-separated, whatever). Then in the render control you will need to serialize and deserialize this value into your representation. Take a look at the following tutorial to get you started on custom fields:
http://vspug.com/nicksevens/2007/08/31/create-custom-field-types-for-sharepoint/


text:
Q: bash shell output history file location Where does the bash shell store the actual terminal session? I want to read the output of commands I used before. All I can find googling is how to store the output of a command.
Since output is displayed on the screen, it has to be stored somewhere anyway. So my question is: where?

A: There are lots of questions related to this one, but they all start with the (right) assumption that the output isn't logged.

So my question is: where?

Nowhere: Bash's (and any other shell that I know of's) output isn't logged.

Since output is displayed on the screen, it has to be stored somewhere anyway.

It is, but most likely not in plain text and not even on the disk (although this really is up to the terminal emulator): most likely, and at least in most cases, in a memory segment allocated by the terminal emulator.
However for sure it isn't logged to a file, at least not by the shell, and I don't know of terminal emulators which log the output to a file by default.
Indeed this doesn't mean it's impossible to log the terminal output: first I'll mention something that I think not many are aware of, since I've never saw anyone mentioning this at least here on Ask Ubuntu: Konsole allows to save the scrollback to a file (perhaps there are other terminal emulators that provide such a functionality, Konsole is just the only one I know of), although this is limited by Konsole's scrollback size limit.
This is often not really useful though, and most likely you'll want to look into "proper" solutions to log a whole session's output to a file (How do I log all input and output in a terminal session? and Ron's answer).

A: Bash only stores history of the commands you ran (which you can retrieve by typing history). Unless you already have set the scroll-back to a very high number, there is no way to see the outputs that are older than the set value of scroll-back. Also setting this value to a very high number will make your scrolling sluggish since the lines are stored in the memory.
To store your future commands and their outputs, there are few options:
Using screen
Start a screen session by entering screen. Once you are inside screen, press Ctrl-a, then :, then enter log. All the I/O will be captured in screenlog files in the directory where you started the screen command.
Using script
You can start by typing script. A script session will start that will capture all the I/O to a file named typescript. You can exit the script session by Ctrl-d  and view the logs in the typescript file.
Using tee
tee is a handy tool. You can do something like this:
$ bash | tee log.txt

This will open a new bash shell inside the one you are already running. When you exit out of this, you can see the outputs in the file called log.txt
Other ways
As Dustin Kirkland suggested in this post, you can also use byobu. Although, I have never used, terminal screencasting tools such as Shelr also sounds like an option.

A: There is a command named as script , if not installed then apt-get install script would do it.
Then in terminal just type script.
and do what ever you want , after you are done just type exit and then there will be a file created at your current directory with all stdout and stdin information.
hope it helps you.

A: This has nothing to do with your shell (bash), it isn a feature of the terminal emulator you are using. It is stored in your terminal's "scrollback buffer". I haven't been able to find any clear explanations of where exactly this is stored, but personal experience has shown me that it is stored somewhere in /tmp.
As the answer of the question linked to above suggests, it is most likely stored in a nameless file. To see what I mean, open a new file with a text editor:
gedit newfile

Write a line of text to the file and save it. Now, while that file is still open, open a terminal and delete it:
rm newfile

Since you still have the file open in gedit, you can continue writing to it. You could even write several gigabytes of data into it, despite the fact that the file has been deleted. That's because deleting a file simply removes the link pointing to its inode. If its file descriptor is held open by another program, data can be written to it, despitre the fact that there is no longer an actual link (file) corresponding to the file descriptor on the file system.
All this is to say that your terminal's history is probably saved using a trick like that, somewhere in a deleted file in /tmp. What you probably actually want is to simply increase the scrollback buffer size of youre terminal emulator so you can just scroll up and see it. The details of how to do this depend ont he terminal emulator you are using. Most have a command line switch that lets yous et this and many also have a GUI way of setting it. For example, in gnome-terminal (the default on Ubuntu) it's Edit -> Preferences -> Profiles --- click on your profile --> Edit -> Scrolling -> Limit scrollback to NNN:

A: Terminal session is stored in .bash_history file. Enter this in your terminal echo $HISTFILE, this would give you the path of .bash_history file.


text:
Q: Synology - Cron job I'm trying to make cron jobs or task schduler working, but I can not figure out why my script is not taken in consideration.
I'm trying to simply archive a folder with:
tar -cvf /volume1/NetBackup/Backups/Monday.tgz /volume1/NetBackup/Backups/ns3268116.ovh.net/

Each time the script starts working but cannot achieve the work. Either with task scheduler or crontab, a file Monday.tgz is created in folder /volume1/NetBackup/Backups/, but this file is only 1024 bytes.

A: Synology Cron is really fussy.
Here are my own personal notes for Synology DS413j, DSM 5.2:

*

*Hand edit /etc/crontab as root, crontab -e isn't available

*Ensure you use tabs not spaces to separate the columns

*Your crontab changes may not survive a reboot if there are syntax problems

*The who column in crontab may not be reliable. Use root in the who column and /bin/su -c '<command>' <username> to run as another other user

*remember that it uses ash not bash so check for bashisms, e.g use >> /path/to/logfile 2>&1' not&>> /path/to/logfile`

*It doesn't support 'MAILTO='

*you need to restart crond synoservicectl --reload crond for the new crontab to take effect

A: You may try adding some diagnostics to it. For instance:

*

*Add MAILTO into the crontab file (on top of crontab -e) to receive cron errors by email:
MAILTO=username@domain.com

*Redirect output of your tar command to the file:
your command > ~/log.txt 2>&1

*Check cron log and look for anomalies. For instance (it may depend on your configuration):
/var/log/cron.log
You may also try searching through /var/log/messages at the time of your cron job.
Is volume1 a resource on remote host? If yes, it is worth checking this part of the system.

A: I agree about the really nagging nature of Crontab on Synology Linux OSs.
I would certainly suggest to create de desired job as a .sh shell script and call it via CRON task inserted by using the GUI, as suggested here.
As for today (March 2017) is the best method I have found, since working with crontab via CLI is nearly a pain.


text:
Q: Rails simple_fields_for I am working on a rails 3.0.11 application. for a many to many association I used simple_fields_for in a form.
simple_form_for @test do |f|
  f.input :example
  f.simple_fields_for :services do |builder|
    render "services_partial", :f => builder
  end
end

Now this is the main form and I used simple_fields_for in the form to render the partial of many to many association model called services
In the services partial
f.input :example_service
f.another_service

What I want to do is to assign the value of example_service attribute to a variable like
var = @test.services.example_service

but this method is not correct. Can anyone help me that how I can access this for each service. because there may be multiple services.

A: I do not quite understand what you're doing. But if you want the values of "example_service" of all services of given @test you can try this
some_var = @test.services.collect(&:example_service)

some_var is an array of "example_service"-values of all services


text:
Q: Distribute labeling function over a list in order to assign different labels in a PieChart I have a PieChart:
PieChart[{{1, 2, 3}, {4, 5, 6}}]

I want to label each sublist differently, but
  PieChart[{{1, 2, 3}, {4, 5, 6}}, ChartLabels -> {{"l1", "l2", "l3"}, {"l4", "l5", "l6"}}]

does not work, because the first part of the Labellist will be associated with the row label. So I thought the only solution to this will be to assign a Label to each entry separately by using Labeled
But then I got stuck with distributing the Labeled function over the values list. For example, given the list of values for the PieChart:
labList = {{1, 2, 3}, {4, 5, 6}}

I can apply Labeled to each element in this list:
labeledStuff = Map[Labeled[#, "Label"] &, labList, {2}]

But how to apply a different label to each element? That is, given the list with labels:
labels = {{"l1", "l2", "l3"}, {"l4", "l5", "l6"}}

apply each of these labels to each element of the value list, resulting in the following:
{{Labeled[1,"l1"],Labeled[2,"l2"],Labeled[3,"l3"]},{Labeled[4,"l4"],Labeled[5,"l5"],Labeled[6,"l6"]}}

A: data = {{1, 2, 3}, {4, 5, 6}};
labels = {{"l1", "l2", "l3"}, {"l4", "l5", "l6"}};

PieChart[Thread[Labeled @@ #] & /@ Transpose[{data, labels}]] (* or *)
PieChart[Thread /@ Thread[Labeled[data, labels]]]