text:
Q: as3 calling jQuery function I need flash to talk to jQuery.
Here is my Flash code:
if (ExternalInterface.available)
{
 ExternalInterface.call('function(){ MyFunction(); }');
ExternalInterface.call('function(){ alert("Praise Be Jesus Christ!"); }');
}

The "Alert" works great. My function does not.
Here is my jQuery:
<script type="text/javascript">

  $(document).ready(function()
  {
  $("#flashContentABOVE").click(MyFunction);

  function MyFunction()
  {
            $("#flashContentABOVE").css("z-index", 4 );

  }

  });
</script>

A: Put your <script> tag at the bottom of your html file (before the closing <body>), and take out the document.ready() function.

A: You should be able to call MyFunction directly from your swf.  I always call ExternalInterface like:
ExternalInterface.call("funcName","param1","param2");


text:
Q: cleveref refers to a theorem as a definition when theorems and definitions share a counter The following LaTeX document is saved in a file whose path is ~/test.tex.
\documentclass{article}

\usepackage{amsthm}
\newtheorem{definition}{Definition}
\newtheorem{theorem}[definition]{Theorem}

\usepackage{cleveref}

\begin{document}
\begin{definition}\label{d}
This is a definition.
\end{definition}

\begin{theorem}\label{t}
This is a theorem.
\end{theorem}

Here is a reference to~\cref{t}.
\end{document}

When the following commands are executed at the terminal:

> cd ~
> pdflatex test
> pdflatex test

a PDF file is generated at the path ~/test.pdf. When opened in a PDF viewer, the file displays as follows:

Notice that the reference to the theorem is displayed as a reference to a definition.
How can I get \cref to distinguish between the theorem and the definition, while maintaining a continuous, unified numbering schema for theorems definitions?

A: This works:
\documentclass{article}

\usepackage{thmtools}

\declaretheorem[name=Definition]{definition}
\declaretheorem[name=Theorem, numberlike=definition]{theorem}
\usepackage{cleveref}
\crefname{theorem}{Theorem}{Theorems}
\crefname{definition}{Definition}{Definitions}

\begin{document}

\begin{definition}\label{d}
This is a definition.
\end{definition}

\begin{theorem}\label{t}
This is a theorem.
\end{theorem}

Here is a reference to~\cref{t} based upon \cref{d}.

\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: JavaScript Maps -- create two values with "same" key I seem to recall reading somewhere that you could add two entries to a JavaScript map which have the same "key" (more like a label) but they were somehow made unique. These kinds of keys had a special name. I can't find any information anywhere on Google but I am certain I remember reading this. Does anyone know what I'm talking about?
The answer will be useful for me in writing my answer to another question on SO.
Edit: I am receiving votes for the question being too broad or unclear but within several minutes I have received the answer I'm looking for from 2 people, therefore I think the down vote and close requests are unmerited. If I could have been more specific I could have found the answer without coming here to ask.
Thanks

A: It sounds like you are probably talking about Symbols.
A Symbol is created with a string, but is a unique object that you can't recreate and have to keep stored. You can use these as the key to an object and have as many of them as you want:

const a = Symbol('my key');
const b = Symbol('my key');

const map = {};

map[a] = 1;
map[b] = 2;

console.log(map[a]);
console.log(map[b]);

Really, you aren't given them the same key (since each Symbol is a unique object), since that is impossible, but this lets you create something with the same value that can be used as a key.


text:
Q: Deserialize a JSON object with support for embedded associations Is there an easy way to deserialize a JSON string to a domain class with support of embedded association; belongsTo and hasMany
{
  name: "Customer",
  contact: {
    name: "Contact"
  }
}

class Customer {
  name
  Contact contact
}

class Contact {
  String name
  static belongsTo = [customer:Customer]
}

in my controller I would like to do the following
def save() {
   def customer = new Customer(request.JSON)
   customer.save();
}

Now i'm forced to do
def save() {
   def contact = new Contact(request.JSON.contact);
   def customer = new Customer(request.JSON);
   customer.contact = contact;
   customer.save();
}

A: Have you tried using JsonSlurper?
Example usage:
def slurper = new JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')

assert result.person.name == "Guillaume"
assert result.person.age == 33
assert result.person.pets.size() == 2
assert result.person.pets[0] == "dog"
assert result.person.pets[1] == "cat"

Ref: http://groovy.codehaus.org/gapi/groovy/json/JsonSlurper.html
you can try this
    Test test
    def result = new JsonSlurper().parseTest('yourString')
    test = result

Try this will work.


text:
Q: How to access contents of folder 'nul' windows? I created a folder with the name NUL, which is traditionally not possible without any fancy tricks.
This folder has unusual properties as trying to copy it, rename it or delete it causes problems because of underlying WINDOWS OS architecture limitations.
Now if you try to drag in a file called a.txt, it will absorb the file, but where did it go? piping files to NUL would delete the data, but. If I try to copy another file called a.txt, it will say NUL already contains a file with that name. So the windows file system still has some idea of filenames inside NUL.
I tried renaming NUL back to a normal folder, but couldn't get that to work. I tried whatever I could, but I think it's impossible to get back to the contents.
Does anyone have experience with NUL and other reserved folders and know why you can't perform certain operations on this folder and most importantly, how to get the files back thrown into NUL. Or are these files permanently lost?

A: I found a way, even though the folder properties and everything tell the user the folder is empty and your contents are lost. You can rename the folder with:

C:\> rename \\.\C:\..\NUL. deletefile.txt

Deleting/Renaming a file named NUL
Then as you wish you can delete this as any other textfile with:

C:\> del deletefile.txt


text:
Q: SlidingDrawer above other views how do i place a slidingdrawer above another view so i doesnt come out from the bottom of the screen, but from the top of another view ?
my code so far:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:orientation="vertical"
          android:background="@drawable/splash">
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:layout_gravity="bottom"
                  android:background="#000000">
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                   android:layout_width="fill_parent"
                   android:layout_height="fill_parent"
                   android:orientation="vertical"
                   android:background="@drawable/splash">
        <Button android:id="@id/content"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="I'm in here!"/>
     </LinearLayout>
     <SlidingDrawer android:id="@+id/drawer"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:handle="@+id/handle"
                    android:content="@+id/content">
        <ImageView android:id="@id/handle"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:src="@drawable/categories_bar_flipped"/>
        <Button android:id="@id/content"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:text="I'm in here!"/>
     </SlidingDrawer>
  </RelativeLayout>
  <EditText xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
</LinearLayout>

problem is that the EditText disappeares and the sliderhandle is dokked at bottom of screen instead of at top of the EditText

A: Use a framelayout which will stack views on top of each other based on the order of the childs. That should make the drawer appear on top.

A: Check some answers:

*

*Sliding Drawer From Top

*How to make an Android SlidingDrawer slide out from the left?

*http://code.google.com/p/aniqroid - Library to do that

It has code examples of how to do that.


text:
Q: How do I make and run my own file extension? I was checking out the files in a old game called Warcraft III and saw that they had files with their own extension, for example, file name.w3x.
How do you make your own file extension and run it?

A: In short: you make your own file extension by applying whatever letters you want to the end of the file name. You run it by telling your OS what program should be called when you double-click on it.

Full explanation:
A file extension is actually just the letters after the file, there is nothing magical about the extension. A lot of files I have made when I'm on my Linux machines I have forgotten to even put the file extension on.
That being said, in Windows the file extension is how Windows determines what the file is. If you change the file extension of a .mp3 for example to a .png Windows will think it is a picture when it tries to open it. What Windows does is it looks at the extension and sends the file to an appropriate program related to that file. so .mp3 gets sent to iTunes, .png gets sent to Paint, .html gets sent to Firefox/Chrome, and .docx gets sent to Word.
In terms of the creation of these files, they fall into two categories. There are plain text files (.html, .txt, .java, .py, .cpp, .config, .xml) and then there are binary data files (.exe, .mp3, .png) (well, and then there are mixes of binary and plain text like .docx, but they can be treated like binary files). When you are dealing with plain text files (it is plain text if Notepad can open it) it is very easy to do. Depending on your programming language you basically just open a file and read/write strings to the file. With binary files, it gets a little more complicated, but the principle remains the same, you are reading/writing bytes from a file.
To make a file of a particular type executable (by double-clicking on it) is probably the hardest step depending on your programming language. If it is C or C++, you simply point Windows to your .exe and Windows sends the file you wish to open as the second argument in args to your program's main method. In Java or Python, it is still doable, but you'll have to work out some sort of workaround to get Windows to open the run-time environment or interpreter and send the file argument to the program.

A: You will need to choose a programming language, then write a program which looks for files with the extension you have chosen. Those files must also be written in a way that the program looking for them can read, understand and execute the code within.

A: Assuming since you're talking about Warcraft III you're on Windows.  Also assuming you're not wanting to do this programatically (otherwise you would have asked on stackoverflow).
Save a file with your custom extension.  Open the file in Windows Explorer and it will ask you how to open it.  Choose "pick from list", select the program you want, and check "Always use the selected program to open this kind of file".  Voila, you can now "run" files with your custom extension.

A: The .w3x extension is a map extension. Warcraft 3 doesn't run this extension, it's just map data.
They have their own algorithm / markup language to create these files and how to read them.

A: Well, just save the file under some name and that extension. "Running" it is a little more difficult, and depends partially on the OS as well.


text:
Q: How to modify this LINQ statement to show bundles with count < 3 instead of CountWithinBundle < 3 I am creating bundles in my app and a bundle is defined as follows
Having a BundleId != null
Having a CountWithinBundle
A bundle is "full" when it has 3 members
I am trying to write a query to find "non full" bundles, below is where I am at but it gives me the second within a bundle every time since I am using the < 3
How can I modify this so that it gives me the last"non full" bundle Item, i,e an ItemInBasket where there are less than 3 entries with the same bundleId and Department so I can add a new item into the same bundle
var itemInBasket = basketToUpdate.ItemsInBasket.OrderByDescending(c => c.ThisItemsCountWithinBundle)
                                                                   .Where(s => !string.IsNullOrEmpty(s.BundleId))
                                                                   .Where(i => i.ThisItemsCountWithinBundle < 3)
                                                                   .Where(s => s.Item.Department == itemToAdd.Item.Department)
                                                                   .FirstOrDefault();

the class model looks like this
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace slapi.Models
{
    class BasketModel
    {
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }
        public string UserId { get; set; }
        public string Brand { get; set; }
        public int BasketLevel { get; set; }
        //Start New Basket props
        public int MaxBasketLevel { get; set; } = 6;
        public Nullable<decimal> BasketLevelProgress { get; set; }
        public decimal BasketLevelDiscount { get; set; }
        public decimal WhitePriceStoreSummary { get; set; }
        public Nullable<decimal> RedPriceStoreSummary { get; set; }
        public Nullable<decimal> CheckoutDiscount { get; set; }
        public Nullable<decimal> CheckoutDiscountPercent { get; set; }
        public string Currency { get; set; } = "SEK";
        public List<XForYStatusInformation> XForYInformations { get; set; }
        //End New Basket props
        public string ConsumerName { get; set; }
        public string StoreId { get; set; }
        public bool IsRedeemed { get; set; } = false;
        public bool IsDeleted { get; set; } = false;
        public List<ItemInBasket> ItemsInBasket { get; set; }
        public string CreatedDate { get; set; }
        public string CreatedDateUtc { get; set; }
        public string CreatedBy { get; set; }
        public string UpdatedDate { get; set; }
        public string UpdatedDateUtc { get; set; }
        public string UpdatedBy { get; set; }
        public Nullable<int> CountHistory { get; set; } = 0;
    }

    class ItemInBasket
    {
        public StorelensItemModel_V2 Item { get; set; }
        public Nullable<int> ItemRowPosition { get; set; }
        public bool UsedForWeightCalculation { get; set; }
        public bool IsPaused { get; set; }
        public string BundleId { get; set; }
        public int ThisItemsCountWithinBundle { get; set; } = 0;
        public int BundleNeededQty { get; set; } = 3;

    }

    class XForYStatusInformation
    {
        public string Sticker { get; set; }
        public string Text { get; set; }
        public string BundleId { get; set; }
        public string Department { get; set; }
    }
}

A: The problem is that you're querying individual items, so you lose their mutual relationships (i.e. belonging to the same basket). The basketToUpdate has all required information, basically something like this:
basketToUpdate
    .Select(b => new
    {
        Bundles = b.ItemsInBasket
                   .GroupBy(i => i.BundleId)
                   .Select(g => new
                   {
                        BundleId = g.Key,
                        ItemCount = g.Count(),
                        LastItem = g.OrderByDescending(c => c.ThisItemsCountWithinBundle)
                                    .FirstOrDefault()
                   })
    })
    .Where(x => x.Bundles.Any(b => ItemCount < 3))

This gives you baskets with non-full bundles in which you can filter the bundles with ItemCount < 3.
I don't know the function of this s.Item.Department == itemToAdd.Item.Department predicate, so I didn't try to fit it in.


text:
Q: Convert php array of objects to javascript array if i have an associative array in php.
Say, in the same view, i have $params array:
$parameters = array(
   'parameter1'=>'value1',
   'parameter2'=>'value2
);

Is there any way or php function or even javascript function to convert the php array to javascript array? in such a way that if we have the converted array, jsParameters, you'd be able to access it's fields and values like :
console.log(jsParameters.parameter1);
console.log(jsParameters.parameter2);

that will output, 'value1' and 'value2'. Is there a way? many Thanks!

A: Use json_encode:
console.log(<?php echo json_encode($parameters); ?>);

A: Use json_encode:
echo json_encode($parameters);

A: You should be able to call json_encode on the array, and echo that back to your application.
Check out the docs here


text:
Q: iphone UIview animation resize in like disappear in water and comes back floating I don't want to fade in and fade out like most common solution for the uiview animation. I would like to have the uiview resize to small until it disappear and comes back the same way. Another way to say it is having a camera pointing closely at the table with all the object in it (UIView) and camera backs up and the more it backs up the smaller the table gets. Which is why i titled which is mainly my app the whole uiview sinks into the water and floats back up. Hopefully i'll find a tutorial or someone's suggestion for the solution. everything resize/shrinks in the middle/center of the screen.
UPDATE***
i would like it to shrink in random position of the screen and appear from random position of the screen also.
Also my subview from other class is viewdidload in mainView
(View = [[View alloc] initWithFrame:CGRectMake(0, 40, 300, 300)];)

A: Try this, where view is the view you are messing with:
CGRect originalFrame = view.frame;

[UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationCurveEaseInOut animations:^{
    CGRect frame = view.frame;
    frame.origin = view.center;
    frame.size = CGSizeMake( 0, 0 );
    view.frame = frame;
} completion:^(BOOL finished) {
    // Do something with the view

    [UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationCurveEaseInOut animations:^{
        view.frame = originalFrame;
    } completion:^(BOOL finished) {
        return;
    }];

    return;
}];

A: You can have that effect by shrinking the frame to size (0,0) over the center of some point on the screen
// assume float cx,cy are defined as center coordinates of your animation (ie where your image shrinks and grows from)
// assume CGRect animFrame is defined as the starting coordinates of your animationView
// assume you have outlet to animationView

// to shrink
        [UIView beginAnimations:@"WaterAnim" context:nil];
        [UIView setAnimationDuration:0.33];

        animationView.frame = CGRectMake(cx,cy, 0,0);

        [UIView commitAnimations];
// to grow
        [UIView beginAnimations:@"WaterAnim" context:nil];
        [UIView setAnimationDuration:0.33];
        animationView.frame = animationFrame;
        [UIView commitAnimations];


text:
Q: Phonegap Build - Media.play audio files in iOS 6 (iPhone 5) only playing on headphones I'm using the Phonegap Media api and things are not going too well. Even my most simple attempts fail, such as:
new Media(src).play();
The funny thing is however that audio works perfectly when the headphones are plugged in, but I can get no sound from the phone speakers.
I'm using phonegap build with phonegap 2.1.0 and testing on iOS 6.0.1 on an iPhone 5.
After a quite exhaustive search (I even tried Bing) I switched to html5 audio but the latency really sucks.
Any suggestions? I've read a few things about setting up an audio session? But could not find this in the PG build API docs and the examples appear to be using phonegap on xcode not PGBuild.
Thanks in advance.


text:
Q: Bokeh plot update in notebook but not in static HTML This is the first time to ask a question here . I'm totally new to HTML , CSS , JavaScipt , Django , Python and Bokeh . I'm poor in English . And I'll appreciate for your help .
I'm meeting a problem when I want to realize a simple function . There is 2 plots here . When I click the circle of the first plot , the circles not associated with in the second spot will be hidden . It's work in notebook . But when I add it into an HTML page . The second plot won't Change . I use Django+python to realize this function . And I use HTML component tag to add plots into an web page.
I'm sorry that I'm not allow to put a picture here, but there are links.
Here is the gif when it works in notebook .
work in notebook
And this is the gif when it's not work in static HTML .
not work in HTML
Here is the HTML code .

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>test</title>
    <link
    href="https://cdn.bokeh.org/bokeh/release/bokeh-0.13.0.min.css"
    rel="stylesheet" type="text/css">
<link
    href="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.13.0.min.css"
    rel="stylesheet" type="text/css">
<link
    href="https://cdn.bokeh.org/bokeh/release/bokeh-tables-0.13.0.min.css"
    rel="stylesheet" type="text/css">

<script src="https://cdn.bokeh.org/bokeh/release/bokeh-0.13.0.min.js"></script>
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.13.0.min.js"></script>
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-0.13.0.min.js"></script>

</head>
<body>
{{ script2 |safe }}
{{ div2 |safe }}
{{ script3 |safe }}
{{ div3 |safe }}
</body>
</html>

And here is the python code .

from PIL.ImageQt import rgb
from bokeh.embed import components
from bokeh.layouts import column, widgetbox, layout
from bokeh.models import Range1d, Title, Label, PrintfTickFormatter, NumeralTickFormatter, Axis, ColumnDataSource, \
    ColorBar, LinearAxis, TapTool, CDSView, BooleanFilter, CustomJS, Slider, layouts, Select
from bokeh.plotting import figure, Figure
from bokeh.models import HoverTool
from bokeh.layouts import column
# Create your views here.
from bokeh.resources import CDN
from bokeh.transform import linear_cmap
from django.shortcuts import render

def test(request):

    data1 = {'time': [1, 2, 3, 4, 5, 6, 7],
             'projectname': ["project1", "project2", "project3", "project4", "project5", "project6", "project7"],
             'id': ['byq-1', 'byq-2', 'byq-3', 'byq-4', 'byq-5', 'byq-6', 'byq-7'],
             'missingnumber0': [1, 2, 30, 22, 23, 5, 9],
             'missingnumber1': [3, 4, 30, 12, 20, 1, 20],
             'missingnumber': [4, 6, 60, 34, 43, 6, 29],
             'holi': [0.10, -0.20, 0.30, -0.11, -0.32, 0.44, 0.05],
             'lilo': [0.23, -0.21, 0.02, 0.03, 0.66, 0.31, 0.22],
             'holo': [0.33, -0.41, 0.32, -0.08, 0.34, 0.75, 0.27],
             }
    data2 = data1
    source1 = ColumnDataSource(data1)
    source2 = ColumnDataSource(data2)

    plot1 = figure(plot_width=850, plot_height=170, toolbar_location=None, active_drag=None, title="total")
    plot1.circle(x='missingnumber', y='holo', size=10, line_color='Blue', fill_color='DeepSkyBlue', alpha=0.5,
                 source=source1)

    plot2 = figure(plot_width=850, plot_height=170, toolbar_location=None, active_drag=None, title="test")
    plot2.circle(x='missingnumber', y='holo', size=10, line_color='Blue', fill_color='DeepSkyBlue', alpha=0.5,
                 source=source2)

    def callback1(plot2=plot2, source2=source2, window=None):

        inds = cb_data.source.selected['1d'].indices
        d1 = cb_data.source.attributes.data
        d2 = source2.data
        d2['time'] = []
        d2['projectname'] = []
        d2['id'] = []
        d2['missingnumber0'] = []
        d2['missingnumber1'] = []
        d2['missingnumber'] = []
        d2['holi'] = []
        d2['lilo'] = []
        d2['holo'] = []

        d2['time'].push(d1['time'][inds[0]])
        d2['projectname'].push(d1['projectname'][inds[0]])
        d2['id'].push(d1['id'][inds[0]])
        d2['missingnumber0'].push(d1['missingnumber0'][inds[0]])
        d2['missingnumber1'].push(d1['missingnumber1'][inds[0]])
        d2['missingnumber'].push(d1['missingnumber'][inds[0]])
        d2['holi'].push(d1['holi'][inds[0]])
        d2['lilo'].push(d1['lilo'][inds[0]])
        d2['holo'].push(d1['holo'][inds[0]])
        source2.change.emit()

    taptool1 = TapTool(callback=CustomJS.from_py_func(callback1))
    plot1.add_tools(taptool1)

    script2, div2 = components(plot1)
    script3, div3 = components(plot2)

    return render(request, 'test.html',
                  {'script2': script2, 'div2': div2, 'script3': script3, 'div3': div3})

I think the problem is that even though I change the source of the second plot , web browser does't send redraw command to this area . But I don't know how to fix this problem .


text:
Q: Is there anyway to use firebase storage for flutter desktop? I am trying to build a cross platform app. I have used firebase for database. Anyway to use firebase storage for flutter desktop ?(Windows)

A: There is currently no support for running Flutter apps that use Firebase Realtime Database for Windows. Only macOS is supported according to the table on firebase.flutter.dev.
Also see:

*

*Flutterfire cli not showing windows and linux as an option for platform to support


text:
Q: Stitching Panoramic Images Today I came up with an interesting project from Germany: Throwable PanoramicBall Camera  36 images are captured in a small ball, then they are showed panoramically. The author declares to use OpenCV
Can you give me some idea about creating a model for cameras at fixed position/orientation and stitching images with OpenCV?

A: Look into Image rectification:
http://en.wikipedia.org/wiki/Image_rectification
This book also has some good explanations and code examples on how to do it in OpenCV in the later chapters:
http://www.amazon.com/OpenCV-Computer-Application-Programming-Cookbook/dp/1849513244/ref=sr_1_1?ie=UTF8&qid=1319209140&sr=8-1

A: The author was probably using the new samples available in OpenCV.
Here are links to the samples currently available in OpenCV...

*

*stitching_detailed

*stitching
You may want to start with these samples if you're trying to do image stitching in OpenCV.


text:
Q: how to use if statements on a pair of muons I am using c++ to run a script below. I have three number of muons having values 0,1,2. I am making pair of these and then fill histograms. But the if statements are not working properly. when i use mu3==0, it means the h1 fills only mu1 and mu2 pair with values 1,2. But all the histograms are filling same.
j=0;
for(unsigned int mu1=0; mu1 <nMu; ++mu1){
  jj=0;
  for(unsigned int mu2=0; mu2 <nMu; ++mu2) {
    if( (mu2 > mu1) &&  (VetoMu_charge[mu1]*VetoMu_charge[mu2]) < 0. ) {
      tmp1.SetPxPyPzE(VetoMu_px[mu1], VetoMu_py[mu1], VetoMu_pz[mu1],       VetoMu_en[mu1]);
      tmp2.SetPxPyPzE(VetoMu_px[mu2], VetoMu_py[mu2], VetoMu_pz[mu2],  VetoMu_en[mu2]);
      for(unsigned int mu3=0; mu3 < nMu; mu3++)  {
        if(mu3==0){
          h1->Fill((tmp1 + tmp2).M());
        }
        else if(mu3==1){
          h2->Fill((tmp1 + tmp2).M());
        }
        else if(mu3==2){
          h3->Fill((tmp1 + tmp2).M());
        }
      }
     }
    }
  }


text:
Q: Can I use a python decorator to preprocess input and postprocess output based on an input type? I have functions that can take either a List or a str. The return type should match the input type. E.g., if given a str the function should return a str.
This is a toy example to illustrate the point:
def swap_first_and_last(a: Union[List, str]) -> Union[List, str]:
    # Not in-place.
    STR = isinstance(a, str)
    a = list(a)

    a[0], a[-1] = a[-1], a[0]

    return "".join(a) if STR else a

This is an actual example:
def next_permutation(a: Union[List, str]) -> Union[List, str]:
    """
    Not in-place.
    Returns `None` if there is no next permutation
    (i.e. if `a` is the last permutation).
    The type of the output is the same as the type of the input
    (i.e. str input -> str output).
    """
    STR = isinstance(a, str)
    a = list(a)

    N = len(a)
    i = next((i for i in reversed(range(N-1)) if a[i] < a[i + 1]), None)
    if i is None:
        return None
    j = next(j for j in reversed(range(i+1, N)) if a[j] >= a[i])

    a[i], a[j] = a[j], a[i]
    a[i + 1:] = reversed(a[i + 1:])

    return "".join(a) if STR else a

As you can see, only a few lines are dedicated to handling str input vs List input, namely:
    # preprocess
    STR = isinstance(a, str)
    a = list(a)

    # main logic
    ...

    # postprocess
    return "".join(a) if STR else a

Can I use a decorator to do this slight preprocessing and postprocessing?

A: Yes, you can use a decorator like this:
from typing import Union, List

def pre_and_post_processing(func):
    def inner(a: Union[List, str]) -> Union[List, str]:
        STR = isinstance(a, str)
        a = list(a)
        b = func(a)
        return "".join(b) if STR else b
    return inner

@pre_and_post_processing
def swap_first_and_last(a: List) -> List:
    a[0], a[-1] = a[-1], a[0]
    return a

print(swap_first_and_last("asd"))  # -> dsa
print(swap_first_and_last(["asd", "ds", "sds"]))  # -> ['sds', 'ds', 'asd']

Note that the swap_first_and_last function now get and return a List.

A: Following up on @larsks suggestion, here is a way to use singledispatch on the @joseville toy example:
Example:
from functools import singledispatch

@singledispatch
def swap_first_and_last(a: str) -> str:

    a = list(a)
    swap_first_and_last(a)
    return "".join(a)

@swap_first_and_last.register
def _(a: list) -> list:

    a[0], a[-1] = a[-1], a[0]
    return a

print(swap_first_and_last([1,2,3]))
print(swap_first_and_last("123"))

Output:
[3, 2, 1]
321


text:
Q: Query in back-testing strategy in R- Indian trader perspective There is a documentation for backtesting in R in GitHub(https://timtrice.github.io/backtesting-strategies/).
I have a query in two lines of code mentioned in this document (https://timtrice.github.io/backtesting-strategies/using-quantstrat.html#settings-and-variables).
First line

Sys.setenv(TZ = "UTC")

Second line

currency('USD')

As you can see, the first line sets - system time to the US and the second line - sets the currency in which trading is occurring to the US. I am an Indian Trader and my job is to do back-testing with equity data for Indian companies. I use quantstrat and quantmod packages along with its dependencies. The data is downloaded from Yahoo Finance through R platform.

*

*What is the argument should an Indian trader pass to both these
functions(Sys.setenv and currency)???. The currency of Indian market
is INR(Indian Nation Rupees) and the time of India is GMT+5:30

I have tried to pass the argument "GMT+5:30" to Sys.setenv function and it turned back an error. But when i tried to pass GMT, there was no error. But Indian timing is GMT+5:30.

A: I found the answer. For determining the time zone, type OlsonNames() in R. You will get a comprehensive list of timezones. Among that, please choose the specific one according to your timezone. So for me(Indian trader), it would be Sys.getenv("Asia/Kolkata") For the currency, please set it as currency("INR") . I thank Ilya Kipnis - for helping in arriving at solution.


text:
Q: How do select certain column indexes (continuous and individual) in Pandas I come from an R background and am having trouble slicing certain sets of columns in pandas.
Let's say I am trying to get the columns with index 0, 3, 5 through 20, and 25th. I would think the way to access what I want is:
df.iloc[:, [0,3,5:20,25]]
but there is a syntax error with the : within the 5:20 line of code. Is there a way to generate a sequence of numbers from 5 through 20 without typing each number out?

A: You can use numpy.r_[...]:
df.iloc[:, np.r_[0,3,5:21,25]]

Notice that the slice is 5:21 since numpy uses Python's slicing convention (exclude the upperbound) while pandas includes both the lower and upperbound.

A: You could build the list first and then use .iloc[] with it.
my_list = [0, 3]
my_list.extend(range(5, 21))
my_list.extend([25])
df.iloc[my_list]


text:
Q: Are Video and Audio Codecs Legal in Ubuntu in the United States? In the United States I would like to know if it is legal to use propriety video and audio codecs in Ubuntu. Specifically I would like to know if I can play mp3 files on Ubuntu, and if I can install and use the libx264 library to do video editing and export mp4 files.
I went to Computex in Taiwan today and I went to the Ubuntu booth. A person there told me that Canonical  has paid for the right/license to use proprietary audio and video formats/codecs. Is this true? I asked the person if he could show me anything online that said this and he could not find anything. Is there any list of codecs/formats that can be used legally in the United States for the purpose of listening to audio, watching video and audio and video editing?
I want to use OpenShot to edit some video and export it to mp4 using libx264 but I want to do it legally.

A: Selling/distribution of MP3 codec binaries is illegal because they are bound by patents, mainly by the Fraunhofer Society.
For libre use, there are open source implementations of the standard ( iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=31537 ) and it is NOT illegal to distribute their source code. There is:

*

*LAME for encoding (http://lame.sourceforge.net/)

*MAD for decoding (http://www.underbit.com/products/mad)

*Mpadec for decoding (http://sourceforge.net/projects/mpadec/)

and probably even more.
For more information:

*

*en.wikipedia.org/wiki/MP3#Licensing_and_patent_issues

*en.wikipedia.org/wiki/List_of_open_source_codecs

Concerning Canonical, they can't provide codecs with their installation media, as this would be considered as reselling patented software, that's why they provide such functionality via their ubuntu store:

*

*http://ostatic.com/blog/canonical-opens-codec-sales-and-potential-can-of-worms

A: From my own understanding, for Ubuntu to fall under the open-source license, they can't have any propriety software contained, which is why it is installed afterwards.
So it is legal.

A: I'm not a legal advisor.  But even if Canonical has paid for the right/license to use proprietary audio and video formats/codecs,  You can edit your own stuff legally, and without any problems.  But if you are editing other person's work, to that is illegal in any country.  But what do I know, as I said I`m not a legal advisor.


text:
Q: Javascript Regex string ends with and only contains one occurrence I have a scenario where I need to identitify using javascript regex when a string ends with the string 47368 but not when there's multiple occurrences of 47368. For example I'd expect the following results
localhost:47368 => true
localhost:47368/abc => false
localhost:47368/abc/47368 => false

A: A common pattern for this use case ("match this and not that") is
 ^ (?! .* non-match) match

in your case:
^(?!.*47368.).*47368$

https://regex101.com/r/riDD2r/1


text:
Q: How to modify authentication plugin in mariadb starting with 10.4.1 to get mysql access for root user without password when migrating mysql to Mariadb At https://kofler.info/root-login-problem-mit-mariadb/ a method is described for modifying the plugin being used for authenticating a user
update mysql.user set plugin='' where user='root';

leading to
ERROR 1348 (HY000): Column 'plugin' is not updatable

https://mariadb.com/kb/en/library/mysqlglobal_priv-table/
explains that there is now a single column global_priv table instead and the original user table is now a view.
select * from mysql.global_priv where User='root';

is possible or
SELECT CONCAT(user, '@', host, ' => ', JSON_DETAILED(priv)) FROM mysql.global_priv where user='root';

for a more readable version.
Unfortunately the documentation says nothing about

*

*How to modify the column under this design decision?

*The motivation for the change?

It would be great to get these two questions answered - obviously #1 being the more pressing one.

A: see: https://mariadb.com/kb/en/library/authentication-plugin-unix-socket/
ALTER USER root@localhost identified via  unix_socket;
flush privileges;

also
mysql

now works for the root user without password.
The statement *"The unix_socket authentication plugin is also installed by default ..."
does have no effect if you migrate from Oracle's mysql to mariadb

A: ALTER USER 'root'@'localhost' IDENTIFIED WITH <auth_plugin> USING PASSWORD('RootPass');


text:
Q: createElement does not work what's wrong with my code..? the div with a anchor tag with a img does not popup in the section area when i call this function
function addLink(){

  if(localStorage.getItem('howManyLinks') >= 1){
    localStorage.setItem('howManyLinks', Number(localStorage.getItem('howManyLinks')) + 1);
  }
  else{
    localStorage.setItem('howManyLinks', '1');
  }

  var howManyLinks = localStorage.getItem('howManyLinks');

  var myNewLink = document.getElementById("link");
    localStorage.setItem('link'+howManyLinks, myNewLink.value);

  var myNewIcon = document.getElementById("icon");
    localStorage.setItem('icon'+howManyLinks, myNewIcon.value);

/* below here is where i have trubble */

  var div = document.createElement('div');
  var img = document.createElement('img');
  var a = document.createElement('a');

  img.setAttribute('src','icon'+howManyLinks);
  a.setAttribute('href','link'+howManyLinks);

  section.appendChild(div);
  div.appendChild(a);
  a.appendChild(img);
}

A: To concentrate on your trouble part: This works with Firefox 25.0 / Linux:
<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
    <section id="section">
    </section>
    <script type="text/javascript">
        var div = document.createElement('div');
        var img = document.createElement('img');
        var a = document.createElement('a');
        var section = document.getElementById("section");

        img.setAttribute('src', 'dummyImg2.jpg');
        a.setAttribute('href', 'http://www.example.com');

        section.appendChild(div);
        div.appendChild(a);
        a.appendChild(img);
    </script>
</body>
</html>


text:
Q: Repeat word with delete and space in MySQL query Not sure if this is possible in MySQL, but I have a column that has business names like:
AT&T Store
O'Reilly's Auto Parts
Burger King
which I import into Sphinx Search with a MySQL query.  I have MariaDB, so there is a REGEXP_REPLACE(col, regexp, replace) function, but I'm having trouble figuring out the rest.
What I need is to repeat words with non-alphanumeric characters replaced with and without a space.  So the above examples would become:
ATT AT T Store
OReillys O Reilly s Auto Parts
Burger King
Is this possible in a MySQL query?  Thanks!

A: This can be done all at once, but maybe not by SQL primitive regex.
I don't know REGEXP_REPLACE, nor modern day SQL.
Typically its done by three regex.
Pseudo code:
$column_val = "O'Reilly's Auto Parts";
$new_column_val = Replace_Globally(
                     $column_val,
                     '\b\w+[[:punct:]](?:[[:punct:]]*\w)+\b',
                     function( $match ) {
                            $val = $match.value;
                            $text1 = Replace_Globally( $val, '[[:punct:]]+', "" );
                            $text2 = Replace_Globally( $val, '[[:punct:]]+', " " );
                            return $text1 + " " + $text2;
                      }
                  );

So, this might not look like something sql can do, so you might have to get creative.

A: REGEXP_REPLACE is in MariaDB only, MySQL doesn't have it.
select regexp_replace(regexp_replace(
"AT&T Store
O'Reilly's Auto Parts
Burger King",
'([[:alnum:]]+)[[:punct:]]+([[:alnum:]]+)[[:punct:]]+([[:alnum:]]+)',
'\\1\\2\\3 \\1 \\2 \\3'),
'([[:alnum:]]+)[[:punct:]]+([[:alnum:]]+)',
'\\1\\2 \\1 \\2')


text:
Q: How to set divider location for JSplitPane on start-up I have JPanel which contains JSplitPane. The JPanel is injected during a runtime into a JFrame using the method invokeAndWait. Then the invokeLater is called to update divider location in SplitPane.
The problem is, when the divider update is invoked, JPanel width is still 0.
When I add sleep or a breakpoint anywhere in the code (except the invokeLater), the code works fine.
    final JPanel viewPanel = new JPanel();
    viewPanel.setLayout(new BorderLayout());

    final JPanel header = getPresenterHeader(getPageTitle(), getPageInstructions());
    viewPanel.add(header, BorderLayout.NORTH);
    viewPanel.add(getSplitPane(), BorderLayout.CENTER);

    toolbar = createActionsToolBar();
    toolbar.addAction(new ExitPresenterAction(this));
    viewPanel.add(toolbar, BorderLayout.SOUTH);
    addContent(viewPanel);

    SwingUtilities.invokeLater(new Runnable()
    {
        @Override
        public void run()
        {
            splitPane.setDividerLocation(0.5);
        }
    });

A: I'm not sure whether it helps for you, but we have a method which mostly helps in this situation:
public static JSplitPane setDividerLocation(final JSplitPane splitter, final double proportion) {
    if (splitter.isShowing()) {
        if ((splitter.getWidth() > 0) && (splitter.getHeight() > 0)) {
            splitter.setDividerLocation(proportion);
        } else {
            splitter.addComponentListener(new ComponentAdapter() {
                @Override
                public void componentResized(ComponentEvent ce) {
                    splitter.removeComponentListener(this);
                    setDividerLocation(splitter, proportion);
                }
            });
        }
    } else {
        splitter.addHierarchyListener(new HierarchyListener() {
            @Override
            public void hierarchyChanged(HierarchyEvent e) {
                if (((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0) && splitter.isShowing()) {
                    splitter.removeHierarchyListener(this);
                    setDividerLocation(splitter, proportion);
                }
            }
        });
    }
    return splitter;
}

Use it instead of invokeLater call
setDividerLocation(splitPane, 0.5);


text:
Q: Is there CMS or template that helps me create a form for a study? I'm working on a psychology project and a study that requires me to set up a website that presents the idea and has a custom form where a user provides his email and question, or whatever consult they have and it goes straight to my email where we can start interacting as a part of the study.

A: You can discuss something like Wordpress engine to create a simple site with a simple form to get some data from people.


text:
Q: PHP jQuery HTML form insert to MySQL then stay on same page I have a simple PHP intranet site where there is an HTML form that takes 2 input fields. I want to take the user input from the HTML form, insert the values into MySQL database, but keep the user's browser on the same page. I have a separate PHP file that does the MySQL INSERT. I have been trying to do this with both pure PHP, and with the help of jQuery, but I can't get it to work! Any help would be greatly appreciated.
Here's my HTML form (which is in a PHP file):
<form name ="form" action="" method="POST">
  Claim Title:

  <input type="text" name="title" required>
  *

  Claim Body:

  <textarea name="claim" rows="5" cols="40"></textarea>

  <input type="submit" name ="submit" value="Submit"/>
</form>

The PHP file that does the db processing is called db-insert.php:
<?php

    require 'connect.php';
    $conn = Connect();

    // Claim form and sql insert variables
    $title          = $conn->real_escape_string($_POST['title']);
    $claim          = $conn->real_escape_string($_POST['claim']);
    $claimInsert    = "INSERT INTO claims(claim_title,claim_body,claim_type) VALUES('" . $title . "','" . $claim . "','T');";
    $success        = $conn->query($claimInsert);

    $conn->close();

?>

The connect.php file:
<?php

    function Connect(){

        // Connection variables
        $servername = "localhost";
        $username   = "user";
        $password   = "password";
        $dbname     = "db";

        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname) or die($conn->connect_error);

        return $conn;
        }
?>

Finally the .js file that I've written (I use the term 'written' loosely as I obtained it from another StackOverflow page on something similar) is:
$(document).ready(function(){
  $("button").click(function(){
    $.get("db-insert.php", function(data, status){
      alert("Data: " + data + "/nStatus: " + status);
    });
  });
});

I'm a bit of novice with jQuery/AJAX/related JavaScript and my PHP skills are growing but not amazing. I am using FireFox JavaScript debugger console and when I click the SUBMIT button for my form it isn't displaying anything, which makes me think it isn't processing the form data.
EDIT: I should have added this to underpin a comment made earlier in my post - I am in the early stages of dev work, please don't tell to parametrise and protect my SQL statements - I am aware of this :)

A: Something like this

$(document).ready(function(){

  $('form[name="form"]').submit( function(e){
    e.preventDefault();

    /*
    you can put the url in the form action as normal,
    its an old habit of mine, so if JavaScript is off on
    the clients browser the form still works.
    */
    var url = $(this).attr('action');
    var iData = {
      title: $('input[name="title"]').val(),
      claim: $('textarea[name="claim"]').val()
    };

    console.log(url);
    console.log(iData);

    /*
     Obviously you're going to need to un-comment this,
     Ajax doesn't really work well on SO website

     $.post(url, iData, function(data){
      //do something on return
    });
    */

    //yea it's old school
    return false;
  });
});

<form name ="form" action="db-insert.php" method="POST">
  Claim Title:

  <input type="text" name="title" value="" required>
  *

  Claim Body:

  <textarea name="claim" rows="5" cols="40"></textarea>

  <input type="submit" name ="submit" value="Submit"/>
</form>

A: Use $.post() to send your data to PHP, and preventDefault() to prevent the page from reloading.

$.post() - Load data from the server using a HTTP POST request.
preventDefault() - The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.

$(document).ready(function(){

    $("form").on('submit', function(e){
        e.preventDefault();
        var data = {title: $('#title').val(), claim: $('#claim').val()};
        console.log(data);
        // $.post("db-insert.php", data, function(data, status){
        //     alert("Data: " + data + "/nStatus: " + status);
        //     });
    });
});

<form name ="form" action="" method="POST">
    Claim Title:

    <input id="title" type="text" name="title" required>
    *

    Claim Body:

    <textarea id="claim" name="claim" rows="5" cols="40"></textarea>

    <input id="sub" type="submit" name ="submit" value="Submit"/>
</form>

Then in your db-insert.php
    <?php
    $title = $_POST['title'];
    $claim = $_POST['claim'];

    // rest of the code here

A: If your main goal is to do this without changing or refreshing the page, you can use Ajax and jQuery like this:
    $(document).on('click', '#submit-my-form', function(){
    var title = $("#title").val();
    var claim = $("#claim").val();

      jQuery.ajax({
      type: "POST",
      url: "http://your-site-url/db-insert.php",
      dataType: 'json',
      data: {title: title, claim: claim},
        success: function(res) {
          if (res)
          {
            alert('Hurray! Successfully done');
          }
        },
        error: function(xhr) {
          if (xhr)
          {
            alert('There was an error');
           }
        }
      });
    });

You can also add code to receive the insert status and process it in the return section of the Ajax code. Modify your html code by adding id tags to the inputs like this:
    <input type="text" name="title" id="title" required>

    <textarea name="claim" id="claim" rows="5" cols="40"></textarea>

    <input type="submit" name ="submit" id="submit-my-form" value="Submit"/>

That should do it.

A: hope can help u
$("document").ready(function()
{
    $("[name='submit']").click(function ()
    {
        sendS();
    });

});

function sendS()
{
    $.ajax(
    {
        type:"POST",
        dataType:"json",
        url:"php.php",
        data:{title:$("[name='title']"),claim:$("[name='claim']")},

        success: function(data)
        {
            //display or do somethg
            alert(data);
        },
        error: function ()
        {
            alert("Error!");
        }
    });
}

<?php
$data1=$_POST["title"];
$data2=$_POST["claim"];

echo "Title : ".$data1."
 Claim : ".$data2;
?>


text:
Q: loop until user enters one of three required letters Currently I have this:
do {
  $MAB = Read-Host "Do you require a Mandatory and/or Advertised deployment? (M)andatory, (A)dvertised, (B)oth"
} while ($MAB -ne "M","A","B")

But it isn't working for me.
What I need it to do is request the user if they want an Advertised, Mandatory or Both, and depending on what they need they type in M for Mandatory, A for Advertised or B for Both.
At the moment, using what I have above if I put in any of the 3 letters it just asks again.
If I set it up like this though:
do {
  $MAB = Read-Host "Do you require a Mandatory and/or Advertised deployment? (M)andatory, (A)dvertised, (B)oth"
} while ($MAB -ne "M")

It works fine, although that doesn't help me for the A or B inputs.
Also if you could explain how I can throw an error saying "You must enter either A for Advertised, B for Both, or M for Mandatory, to proceed." If they put in anything other than a M, A, or B.

A: $title = "Deployment choices"
$message = "Do you require a Mandatory and/or Advertised deployment?"

$mandatory = New-Object System.Management.Automation.Host.ChoiceDescription "&Mandatory"
$advertised = New-Object System.Management.Automation.Host.ChoiceDescription "&Advertised"
$both = New-Object System.Management.Automation.Host.ChoiceDescription "&Both"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($mandatory, $advertised, $both)

#do
#{
    $result = $host.ui.PromptForChoice($title, $message, $options, 0)

    switch ($result)
    {
        0 {"You selected Mandatory."}
        1 {"You selected Advertised."}
        2 {"You selected Both." }
    }
#}
#until ($result -in 0..2)

A: I think this is fairly neat:
do {
  $MAB = Read-Host "Do you require a Mandatory and/or Advertised deployment? (M)andatory, (A)dvertised, (B)oth"
} until ($("M","A","B").Contains($MAB))

A: OK so I found it out - I have been looking all day for this and it was quite hard to find the answer for multiples.
It's not actually a do..while, it's a do..until:
do {
  $MAB = Read-Host "Do you require a Mandatory and/or Advertised deployment? (M)andatory, (A)dvertised, (B)oth"
} until (($MAB -eq "M") -or ($MAB -eq "A") -or ($MAB -eq "B"))

I hope this helps someone else out there.

A: Another option is the choice command:
choice /c mab /m 'Do you require a Mandatory and/or Advertised deployment'
switch ($LASTEXITCODE) {
  1 { 'You selected Mandatory.' }
  2 { 'You selected Advertised.' }
  3 { 'You selected Both.' }
}


text:
Q: Realizing symmetric groups by diffeomorphisms Let $M$ be a (closed, smooth) manifold of dimension $d$. For $n$ a positive integer, fix $n$ points $x_1, \dots, x_n \in M$. The group of diffeomorphisms of $M$ that permutes the points $x_i$ surjects to the symmetric group $\Sigma_n$, at least for $d \geq 2$:
$$\Phi\colon \text{Diff}(M,\{x_1, \dots, x_n\}) \to \Sigma_n$$
Is it always true that $\Phi$ does not have a section for $n$ big enough?
How big do we have to choose $n$ for $M = S^d$? (The naive guess would be $d+3$.)

A: I'm going to reverse the roles of $n$ and $d$ (since otherwise I will screw things up in this answer).  If $M^n$ is a connected $n$-dimensional smooth manifold, then there is no section of the map $Diff(M^n,\{x_1,\ldots,x_d\}) \rightarrow \Sigma_d$ if $d \geq n+3$ (nb: you forgot in your question to assume that $M^n$ is connected).  Indeed, assume that $\Sigma_d$ acts by diffeomorphisms on $M^n$ such that the action restricts to the permutation action on $\{x_1,\ldots,x_d\}$.  The group $\Sigma_{d-1} \subset \Sigma_d$ then fixes $x_d$, so we get a linear action of $\Sigma_{d-1}$ on the tangent space $T_{x_d} M^n = \mathbb{R}^n$.  Every element of $\Sigma_{d-1}$ must act nontrivially on this tangent space; indeed, by averaging we can find a Riemannian metric on $M^n$ that is preserved by the action of $\Sigma_d$, and an isometry of a connected Riemannian manifold that fixes a point and all tangent vectors at that point must be the identity.  But the smallest dimensional vector space on which $S_{d-1}$ acts faithfully is $(d-2)$-dimensional.  We thus deduce that $n \geq d-2$, so $d \leq n+2$, as desired.


text:
Q: How to get List of Tuple from Code Behind to Javascript I have created a list of different items say list of tuple in code behind. I want to access the same list in my javascript. I tried the same but what I am getting in result in like: (value, value), (value, value), (value, value)...
I want a result like JSON format : [{value, value}, {value, value}...].
Code Snippet I wrote is:
List<Tuple<int, int>> comboPD = new List<Tuple<int, int>>();
            while (dataReader.Read())
            {
                int pId = (int)dataReader["FieldName"];
                int dId = (int)dataReader["FieldName"];
                comboPD.Add(Tuple.Create(f1, f2));
            }
            hdnPDValue.Value = String.Join(",", comboPD);

I accessed the same from java script through a hidden runat field. Like:
var arr = [];
arr = $(".json-ProgDivIds").val();

Please, let me know how to get that List to javascript in mentioned format.
Thanks.


text:
Q: How to debug further this dropped record in apache beam? I am seeing intermittent dropped records(only for error messages though not for success ones).  We have a test case that intermittenly fails/passes because of a lost record.  We are using "org.apache.beam.sdk.testing.TestPipeline.java" in the test case.  This is the relevant setup code where I have tracked the dropped record too ....
    PCollectionTuple processed = records
        .apply("Process RosterRecord", ParDo.of(new ProcessRosterRecordFn(factory))
            .withOutputTags(TupleTags.OUTPUT_INTEGER, TupleTagList.of(TupleTags.FAILURE))
        );
    errors = errors.and(processed.get(TupleTags.FAILURE));

    PCollection<OrderlyBeamDto<Integer>> validCounts = processed.get(TupleTags.OUTPUT_INTEGER);

    PCollection<OrderlyBeamDto<Integer>> errorCounts = errors
        .apply("Flatten Roster File Error Count", Flatten.pCollections())
        .apply("Publish Errors", ParDo.of(new ErrorPublisherFn(factory)));

The relevant code in ProcessRosterRecordFn.java is this
        if(dto.hasValidationErrors()) {

            RosterIngestError error = new RosterIngestError(record.getRowNumber(), record.toTitleValue());

            error.getValidationErrors().addAll(dto.getValidationErrors());
            error.getOldValidationErrors().addAll(dto.getOldValidationErrors());

            log.info("Tagging record row number="+record.getRowNumber());
            c.output(TupleTags.FAILURE, new OrderlyBeamDto<>(error));

            return;

        }

I see this log for the lost record of Tagging record row for 2 rows that fail.  After that however, inside the first line of ErrorPublisherFn.java, we log immediately after receiving each message.  We only receive 1 of the 2 rows SOMETIMES.  When we receive both, the test passes.  The test is very flaky in this regard.
Apache Beam is really annoying in it's naming of threads(they are all the same name), so I added a logback thread hashcode to get more insight and I don't see any and the ErrorPublisherFn could publish #4 on any thread anyways.
Ok, so now the big question: How to insert more things to figure out why this is being dropped INTERMITTENTLY?
Do I have to debug apache beam itself?  Can I insert other functions or make changes to figure out why this error is 'sometimes' lost on some test runs and not others?
EDIT: Thankfully, this set of tests are not testing errors upstream and this line "errors = errors.and(processed.get(TupleTags.FAILURE));" can be removed which forces me to remove ".apply("Flatten Roster File Error Count", Flatten.pCollections())" and in removing those 2 lines, the issue goes away for 10 test runs in a row(ie. can't completely say it is gone with this flaky stuff going on).  Are we doing something wrong in the join and flattening?  I checked the Error structure and rowNumber is a part of equals and hashCode so there should be no duplicates and I am not sure why it would be intermittently failure if there are duplicate objects either.
What more can be done to debug here and figure out why this join is not working in the TestPipeline?
How to get insight into the flatten and join so I can debug why we are losing an event and why it is only 'sometimes' we lose the event?
Is this a windowing issue? even though our job started with a file to read in and we want to process that file.  We wanted a constant dataflow stream available as google kept running into limits but perhaps this was the wrong decision?


text:
Q: Why is $\int_{0}^{r}\left(\int_{\partial B(x,s)}u\ dS\right)ds=u(x)\int_{0}^{r}n\alpha(n)s^{n-1}ds$
$\int_{B(x,r)}u\ dy=\int_{0}^{r}\left(\int_{\partial B(x,s)}u\ dS\right)ds=u(x)\int_{0}^{r}n\alpha(n)s^{n-1}ds=\alpha(n)r^nu(x)$

This appears in the proof of a theorem in the book of Evans PDE. I don't get the second equality, so in general $\int_{\partial B(x,s)}u\ dS\neq u(x)n\alpha(n)s^{n-1}$, they're only equal if we integrate both sides, am I wrong ? where does $s^{n-1}$ come from ? Is it valid only for radial symmetric $u$ ?

A: In the proof of the theorem you are refering to it was proved that the function $\phi(r):=\frac{1}{n\alpha(n) r^{n-1}}\int_{\partial B(x,r)}u(y)dS(y)$ is constant equal to $u(x)$, i.e.
$$\phi(r)=u(x)$$
Therefore
$$\int_{B(x,r)}udy=\int_{0}^{r}\int_{\partial B(x,s)}u(y)dS(y)ds=\int_{0}^{r}n\alpha(n)s^{n-1}\phi(s)ds=\int_{0}^{r}n\alpha(n)s^{n-1}u(x)ds$$

A: Is $u$ a harmonic function? If this is the case, then $$\frac{1}{\sigma(\partial B(x,s))}\int_{\partial B(x,s)}u\,d\sigma=u(x),$$ from the mean value property, so the second inequality follows.


text:
Q: How to fix "URL rewrite vulnerability" in Laravel version 5.2.45 I am getting the below security warning in the scan report with a laravel project built in version  5.2.45.

URL rewrite vulnerability

Below is the description.

It was identified that this application supports the legacy headers X-Original-URL and/or X-Rewrite-URL.Support for these headers lets users override the path in the request URL via the X-Original-URL or X-Rewrite-URL HTTP request header and allows a user to access one URL but have web application return a different one which can bypass restrictions on higher level caches and web servers. Many web frameworks such as Symfony 2.7.0 to 2.7.48, 2.8.0 to 2.8.43, 3.3.0 to 3.3.17, 3.4.0 to 3.4.13, 4.0.0 to 4.0.13 and 4.1.0 to 4.1.2 , zend-diactoros up to 1.8.4, zend-http up to 2.8.1, zend-feed up to 2.10.3 are affected by this security issue.

Any suggestions on how to fix this will be much appreciated.

A: Maybe "composer update" after setting the new value in composer.json?
  "laravel/framework": "5.3.*",

As documented here: https://laravel.com/docs/5.3/upgrade

A: Got the Fix. Added below code to the root htaccess file.
<IfModule mod_headers.c>
  RequestHeader unset X-Original-URL
  RequestHeader unset X-Rewrite-URL
</IfModule>


text:
Q: How does one properly use the nautilus & command in a graphical SSH into debian 6.0.4? Last login: Wed Mar 21 20:10:33 2012 from astrolab17.astro.washington.edu
1 td% nautilus &
[1] 9847
2 td% Initializing nautilus-gdu extension

And then I quit nautilus.
The thing is, though, that putting the & operator at the end of nautilus, I'm supposed to be able to enter new commands after I close (or 'X' out of) the nautilus window. This happens with most other programs like Matlab. Except that this doesn't happen with Debian.
The distribution involved is Debian 6.0.4.

A: ... & disown
Some programs require that you use & disown.  Some programs will still put output to your terminal, which is hard to deal with, but you can try directing the output to /dev/null.
For example:
nautilus > /dev/null & disown

This will also prevent nautilus from closing if you close the terminal window.
... ; bash
Is the terminal closing immediately when you launch nautilus?
nautilus > /dev/null & disown ; bash

CTRL+C
Are you sure you cannot run additional programs?  Try hitting CTRL+C to refresh your prompt.


text:
Q: Display message to user that a file cannot be loaded to program c# I am new to working with System.IO.
I have an application that grabs a Json file from the web and only grabs partial data to display on the Windows Application Form's controls.
The form allows the user to save the data as a new file and load a file if ONLY it contains the "indicator" I added in when the file was saved that tells the program it was saved by my program.
Everything works.
Whenever a file that doesn't contain that indicator is loaded to the program, it doesn't show nothing which is what I want it to do, but I also want a Messagebox.Show() to pop up and let the user know why the values are empty and why nothing happened.
if(openFile.ShowDialog() == DialogResult.OK)
{
    string dataLine = string.Empty;
    using (StreamReader read = new StreamReader(File.OpenRead(openFile.FileName)))
    {

        dataLine = read.ReadToEnd();
        string[] beginningOfData = dataLine.Split(',');
        string temporary = string.Empty;
        foreach (string line in beginningOfData)
        {
             //Indicator
             if(line.Contains("Indicator")
             {
                temporary = line.substring(9);
                //Goes through the rest of the file
                //Converts data to control value and adds it
             }
             else
             {
                //Where I tried to display the message box
             }
        }
    }

}

This what I've tried, but it wasn't working as I wanted it too
else
{
    MessageBox.Show("Can't load data.");
}

It would still show the MessageBox even if it read that the indicator was there and displayed the data inside the corresponding controls. Also whenever I tried to close the MessageBox it would just show it again.
So I decided to this instead:
else if(!line.contains("Indicator"))
{
    MessageBox.Show("Can't load data.");
    break;
}

and in this way too:
else
{
    if(!line.contains("Indicator"))
    {
        MessageBox.Show("Can't load data.");
        break;
    }
}

I also tried making it more specific by doing
if(line.contains("Indicator") == false)
{
   //Code here
}

But it would still display it even if the file was created by the program.
The break; did stop the message box from re-appearing again, but I only want the MessageBox to show when it's the incorrect text file (not containing the indicator) and allow me to close the MessageBox to try again.

A: You can wrap the foreach into an if statement which will use some LINQ code to determine if all lines contain "indicator":
if (beginningOfData.All(line => line.ToLower().Contains("indicator")))
{
    string temporary = string.Empty;
    foreach (string line in beginningOfData)
    {
        temporary = line.Substring(9);
        //Goes through the rest of the file
        //Converts data to control value and adds it
    }
}
else
{
    System.Windows.Forms.MessageBox.Show("Can't load data.");
}

A: Contains is case-sensitive.  Try this for your evaluation:
line.IndexOf("Indicator", StringComparison.InvariantCultureIgnoreCase) >= 0

A: I did this instead and it worked for my application
if(openFile.ShowDialog() == DialogResult.OK)
{
    string dataLine = string.Empty;
    using (StreamReader read = new StreamReader(File.OpenRead(openFile.FileName)))
    {
        //Changed happened here

        dataLine = read.ReadToEnd();
        string[] beginningOfData = dataLine.Split(',');
        string temporary = string.Empty;

        if(beginningOfData.Contains("Indicator"))
        {
           temporary = dataLine.Substring(9);
           foreach(string realData in beginningOfData)
           {
             //Goes through file
           }
        }
        else
        {
          MessageBox.Show("Can't load data");
        }
    }
}


text:
Q: How to use LIKE in MySQLi? I have a code it's working with MysQl but does not work in MySQLi:
function CheckBlocked($table, $thisip, $service) {
    $sql="SELECT * FROM $table WHERE code = '$service' AND b_contents LIKE '%.$thisip.%'";
    $query=mysqli_query($dbconnect,$sql);
    $num=mysqli_num_rows($query);
    if ($num > 0) {
        return true;
    } else {
        return false;
    }
}

How to used in MySQLi ?

A: try this code :
 $sql="SELECT * FROM $table WHERE code = '$service' AND b_contents LIKE '%".$thisip."%' ";


text:
Q: jQuery RemoveAttr and IE8 - Only effective after another component has focus I use the following code to hide 1-4 rows of a table when a checkbox is selected:
    for(i = 1; i < 4; i++){
      $(tbProf.rows[i]).attr('style','display:none');

      // same problem with
      // $(tbProf.rows[i]).hide();
    }

and reverse when its unticked:
    for(i = 1; i < 4; i++){
      $(tbProf.rows[i]).removeAttr('style');

      // same problem with
      // $(tbProf.rows[i]).show();

    }

It works perfectly fine in Chrome/Firefox:
In IE7/8 however the rows only hide/show after i click somewhere(anywhere) in the form after which the style is applied! Can anyone suggest a workaround for IE8? [ i have to support IE8 :(  ]

A: I understood the problem, but what you need to do? Show and hide these rows?
Why not use show() and hide() functions?
Edit 1:
So, try using:
$(tbProf.rows[i]).hide();

and
$(tbProf.rows[i]).show();

Edit 2:
A better example here (using the :lt selector). May be usefull for you.


text:
Q: Generate source code for class definition given a System.Type? Is there a way in .NET to create the source code class definition given a System.Type?
public class MyType
{
   public string Name { get; set; }
   public int Age { get; set; }
}

string myTypeSourceCode = GetSourceCode( typeof(MyType) );

Basically I'm looking for what GetSourceCode() is.
I realize there would be limitations: If there are property getters/setters or private members the source is not included, but I don't need that. Assume the type is a Data Transfer Object, so just the public properties/fields need to be exposed.
What I'm using this for is auto-generated code examples for a web API.

A: If you just want to generate pseudo-interface code like you have shown, you can iterate over the public fields & properties like this:
string GetSourceCode(Type t)
{
    var sb = new StringBuilder();
    sb.AppendFormat("public class {0}\n{{\n", t.Name);

    foreach (var field in t.GetFields())
    {
        sb.AppendFormat("    public {0} {1};\n",
            field.FieldType.Name,
            field.Name);
    }

    foreach (var prop in t.GetProperties())
    {
        sb.AppendFormat("    public {0} {1} {{{2}{3}}}\n",
            prop.PropertyType.Name,
            prop.Name,
            prop.CanRead ? " get;" : "",
            prop.CanWrite ? " set; " : " ");
    }

    sb.AppendLine("}");
    return sb.ToString();
}

For the type:
public class MyType
{
    public int test;
    public string Name { get; set; }
    public int Age { get; set; }
    public int ReadOnly { get { return 1; } }
    public int SetOnly { set {} }
}

The output is:
public class MyType
{
   public Int32 test;
   public String Name { get; set; }
   public Int32 Age { get; set; }
   public Int32 ReadOnly { get; }
   public Int32 SetOnly { set; }
}

A: Try a .Net decompiler
Here are some links to .net decompiler
http://www.telerik.com/products/decompiler.aspx
http://www.jetbrains.com/decompiler/
http://www.devextras.com/decompiler/
http://wiki.sharpdevelop.net/ilspy.ashx
or maybe you'll be able to find an old version of .Net Reflector when it was free...


text:
Q: How can i find out what C# version I'm programming with in Visual Studio Community? I want to make sure I'm using C# 7.0 or higher. Does anyone know an easy way of checking this? I use Visual Studio Community on a MacBook and cannot seem to find an easy way of checking or setting language preferences.
Thanks

A: you dhuld edit the project file and add:
<PropertyGroup>
   <LangVersion>7.0</LangVersion>
</PropertyGroup>

see here

A: Normally you use the latest installed version (depending on the .Net framework) in Visual Studio.
If you want to change it, go to the advanced build setting (project -> properties -> build)
In the advanced build settings you also see all installed versions of C# (also the latest), therefore you can also check it there.


text:
Q: Using If condition to do "something" once every 10 clock cycles. what if "something" takes more than 1 clock cycle? I am working on some VHDL code that will be used (on an FPGA) to read in a 16 bit digital signal, do some processing, and then write out the 16 bit processed signal. Currently it is setup so it should read the input every 10 clock cycles, do some processing on the next clock cycle (it currently does nothing, just outputs the input) and then just increment the counter for the remaining 8 clock cycles.
What happens if the processing takes longer than one clock cycle to complete (Which it will), will it continue until it finishes and stop the counter incrementing until it does? Or will the counter keep incrementing in parallel while it processes the signal?
I will set it up such that the process completes before the 8 clock cycles are up (in time to be written to the output).
The pseudocode looks something like this:
Do (on rising clock edge):
if (n = 10) then
  n <= 1;
  Output <= ProcessedSignal;
  InputSignal <= Input;
elsif (n = 1) then
  n <= n + 1
  Output <= Output;
  -- do some signal processing here (e.g. a filter)
  ProcessedSignal <= InputSignal;
else
  n <= n + 1;
  Output <= Output;
  ProcessedSignal <= ProcessedSignal;
end if;

A: It all depends on how you write the code; any kind of behavior is possible. Your pseudocode is nearly valid VHDL and will do what you want if I understand you correctly. Here is a suggestion for real code: (without architecture/signal declarations, also missing reset)
process (clock)
begin
  if rising_edge(clock) then
    n <= n + 1; -- default assignment

    if (n = 10) then
      n <= 1; -- overrides default assignment
      Output <= ProcessedSignal;
      InputSignal <= Input;
    elsif (n = 1) then
      -- do some signal processing here (e.g. a filter)
      ProcessedSignal <= InputSignal;
    elsif (n = 2) then
      -- do more processing
    end if;
  end if;
end process;

Note that there is no need to write a signal to itself in a clocked process, unless you want to make it explicit that the signal keeps its old value.


text:
Q: Binding a ListView and formatting data based on value I have a ListView with an ItemTemplate item as below:
<asp:Label runat="server" ID="lblChangeOrders"><%#Eval("sum")%></asp:Label>

What I need is if the sum is negative I need to set font color as RED and remove the minus sign.

A: I would use the DataBinding method on the contorl itself.
Example:
<asp:Label runat="server" ID="lblChangeOrders"
    OnDataBinding="lbChangeOrder_DataBinding"></asp:Label>

protected void lbChangeOrder_DataBinding(object sender, System.EventArgs e)
{
    Label lbl = (Label)(sender);
    double sum = (double)(Eval("Sum"));
    if (sum < 0)
    {
        sum *= -1;
        lbl.ForeColor = "Red";
    }
    lbl.Text = sum.ToString();
}

I prefer to do all these type of tweeks at the control level so you can swap out the control and you know everything that is tied to it.  If you do it at the ItemDataBound level, it is not as localized to the control itself.  Very rarely do I ever use the ItemDataBound event.

A: My first thought would be to use the ItemDataBound event and do a check of sum.  If it is negative then assign a CSS Class that will color that element red.


text:
Q: Хранение авторизации Vkontakte в android приложении Необходима авторизация через Вконтакте в приложении. Как лучше всего хранить полученный токен авторизации в приложении и как подставлять его автоматически если он еще не устарел? SharedPreference и SQLite небезопасны. Есть возможность хранить во внешней MySQL базе.

A: SharedPreference с MODE_PRIVATE http://developer.android.com/reference/android/content/Context.html#MODE_PRIVATE будет доступно только для текущего приложения
Если это кажется недостаточно безопасным можно использовать реализацию с шифрованием https://github.com/scottyab/secure-preferences


text:
Q: What's the best way of structuring hiearchy of views in ASP.NET MVC? I'm currently converting a ASP.NET webforms solution to MVC.
In webforms we besides the site.master we have master pages where we keep the common code and head imports for each section. So a normal page inheritance goes like so:
Site.master -> section.Master -> page.aspx

In MVC I'm unclear as to where to place the code common to a section. Is splitting the section content into partial views the only solution? So it becomes?
Layout.cshtml -> page.cshtml -> any-number-of-partial-views

To give an example, if I need a single CSS file to be shared across all 10 section pages, I can put it in a partial view and render it on each page but doesn't feel incredibly efficient. Or maybe I just need to get my head around to this new way of working.

A: You can use sections in MVC as well.
In your _Layout.cshtml you might have something like this:
 @RenderSection("testSection",required:false)

And in your child view you can specify what HTML should be rendered in this section or you can leave it all together because required has been set to false:
@section testSection{

Test

}

A: Partial view is your big friend if you would like to reuse the code several places.
You can put partial view inside Views > ControllerNameAsFolderName > view pages (put here) to use only in same controller views or even inside Shared folder to use globally.
section is another option, this is like UserControl (in web forms). create section reference @RenderSection("sectionName", required:false) on Layout page and use it on view pages like
@section sectionName{

content goes here

}

Assume you want to put something (like meta infos) inside  from view pages, in this case you can create a section in _Layout.cshtml page and then use that section on view pages.
This way you can place your code at certain location in DOM structure from any page. section has a great feature that allow you to mark it as required:false/true.


text:
Q: How to clear Picasso cache memory in android I have an issue with image i am trying to get images from server in list but if i update image from app it goes to server successfully but when i fetch new data  i got old image i have cleared Picasso cache memory still old image is display
here is my code. is there any other solution for clear the cache of Picasso
public class WorkerListAdapter extends RecyclerView.Adapter<WorkerListAdapter.MyViewHolder> {
    private static final int REQUEST_PHONE_CALL = 1;
    private List<ItemWorkerList> itemWorkerListList;
    private Context context;

    public class MyViewHolder extends RecyclerView.ViewHolder {

        public TextView tv_worker_name, tv_worker_type;
        public CircleImageView iv_worker_image;
        public ImageView iv_worker_images;
        ImageView iv_edit_provider;
        public LinearLayout ll_doc;
        public ProgressBar pb_worker;

        public MyViewHolder(View view) {
            super(view);
            this.setIsRecyclable(true);

            tv_worker_name = (TextView) view.findViewById(R.id.tv_worker_name);
            tv_worker_type = (TextView) view.findViewById(R.id.tv_worker_type);
            iv_edit_provider = (ImageView) view.findViewById(R.id.iv_edit_provider);
            iv_worker_image = (CircleImageView) view.findViewById(R.id.iv_worker_image);

            iv_edit_provider = (ImageView) view.findViewById(R.id.iv_edit_provider);
            pb_worker = (ProgressBar) view.findViewById(R.id.pb_worker);

        }
    }

    public WorkerListAdapter(Context context, ArrayList<ItemWorkerList> itemWorkerListList) {
        this.context = context;
        this.itemWorkerListList = itemWorkerListList;

    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())

                .inflate(R.layout.item_worker_list, parent, false);
        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        final ItemWorkerList itemWorkerList = itemWorkerListList.get(position);
        holder.tv_worker_name.setText(itemWorkerList.getName());
        holder.tv_worker_type.setText(itemWorkerList.getCategory());

        Picasso.get().invalidate(itemWorkerList.getImage());
        Picasso.get().invalidate(itemWorkerList.getDocument());
        if (!TextUtils.isEmpty(itemWorkerList.getImage())) {

            Picasso.get().load(itemWorkerList.getImage()).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(holder.iv_worker_image, new Callback() {
                @Override
                public void onSuccess() {
                    holder.pb_worker.setVisibility(View.GONE);
                }

                @Override
                public void onError(Exception e) {

                    holder.pb_worker.setVisibility(View.GONE);
                    Picasso.get().load(R.drawable.dummy).into(holder.iv_worker_image);
                }
            });
}

A: you can do this -
Picasso.with(context).load(your_url).networkPolicy(NetworkPolicy.NO_CACHE)
        .memoryPolicy(MemoryPolicy.NO_CACHE)
        .into(your_image_view);

A: public class Clear {

public static void clearCache (Picasso p) {
    p.cache.clear();
}}

Use like this.
Clear.clearCache(Picasso.with(context));

The class Clear must be in the package :
Because the cache is not accessible from outside that package. Like in this answer: https://stackoverflow.com/a/23544650/4585226


text:
Q: Passing data from one function to another I'm trying to edit data from a table .
Fiddle
the important part of codes are :
Edit
$scope.editUser = function(param){

        if(param == 'new' ){
            $scope.fName = '';
            $scope.lName = '';
            $scope.edit = true;
        }else{
            $scope.edit = false;
            $scope.fName = $scope.users[param-1].fName;
            $scope.lName = $scope.users[param-1].lName;
            //console.log($scope.users[param-1].lName);
        }

    };

ng-click on Save button
$scope.add = function(){
    $scope.users.push({
        fName:$scope.users.fName,
        lName:$scope.users.lName
    });
    $scope.users.fName = "";
    $scope.users.lName = "";
    console.log($scope.users.lName);
};

how can i pass data from edit function to add function for saving ?
many thanks

A: In your edit function call add function like this
$scope.add()

If you need to pass any parameters
$scope.add(params)

A: call add function as $scope.add(param1,param2,..);
define add function as $scope.add=function(param1,param2..){};
But, I see all the variables in your code are scope variables , if you want to modify only those then you can directly use them in add function instead of passing them as parameters.

A: You have (almost) the right ViewModel, and you don't need to pass anything between these functions - they are not calling each other.
You have $scope.users and you have $scope.fName and $scope.lName. That is fine - you just need to "remember" which user was being edited.
I would just slightly change this to:
$scope.users = [...]; // whatever you have
$scope.userBeingEditedCopy = null;
var userBeingEditedMaster = null;

Then, when "edit" is clicked, pass it the actual user object to be edited:
$scope.editUser = function(user){
   userBeingEditedMaster = user;
   $scope.userBeingEditedCopy = angular.copy(userBeingEditedMaster);
}

When you want to save changes, you already have all the data:
$scope.saveChanges = function(){
   angular.copy($scope.userBeingEditedCopy, userBeingEditedMaster);
   // optionally, remove the user from being edited
   userBeingEditedMaster = $scope.userBeingEditedCopy = null;
}

In the View it is easy to wire these up:

   <button ng-click="editUser(user)">Edit</button>
   {{user.fName}} {{user.lName}}

Edit User:

first name: <input ng-model="userBeingEditedCopy.fName">

last name: <input ng-model="userBeingEditedCopy.lName">

<button ng-click="saveChanges()">Save Changes</button>


text:
Q: Require guidance on implementing Excel services in SharePoint 2013 for existing Excel sheets and logic We have excel reports with programming built in to connect to db and extract info.
The sheet has 1000 rows. Every 5 rows belong to 1 client.. So there are total 200 clients (1000 rows). The excel sheet has functionality that allows user to filter the data based on client name.
This sheet is now going to be uploaded to SharePoint. Can the filter functionality be invoked via SharePoint 2013? Say based on some drop-down on the SharePoint page OR based on the logged in user's (AD) Company name. Please guide on the approach to follow...
We have set up Excel Services on our SharePoint site as a first step to this by following this MSDN article...
More reference articles:-
http://blogs.technet.com/b/microsoft_in_education/archive/2013/05/16/parameterizing-an-excel-spreadsheet.aspx
http://office.microsoft.com/en-in/sharepoint-server-help/connect-filter-web-parts-to-excel-web-access-HA010105470.aspx
http://blogs.office.com/2008/01/16/personalized-data-in-excel-services/?Redirected=true

A: I got the answer to this question in this link. It is for SharePoint 2010, but can be used in SharePoint 2013 as well (with very minor changes).
To create named range and to define a parameter in Excel 2013: http://office.microsoft.com/en-in/sharepoint-server-help/share-workbooks-using-excel-services-HA102772301.aspx#_Toc364261323


text:
Q: How to play sound from library in AS3? In Flash 10/AS3, I added some sound and it seems to be working alright, but I think I'm doing it wrong. I imported the sound into the library, but I believe that it's reloading it from the folder with the swf/sound. I'm loading them like so:
var request1:URLRequest = new URLRequest("CLICK8C.mp3");
clickSound = new Sound();
clickSound.addEventListener(Event.COMPLETE, completeHandler);
clickSound.load(request1);

Is there a way to get it to just load it from the library?

A: The top answer has managed to get some of the code incorrect.
Here is a more simplistic version.
var mysound:Sound = new (mySound);
mysound.play();

}
Just change your internal sound file class name to mySound.

A: You need to make the sound in the library available to actionscript.  After that, you can implement the sound object like any other class.
To make a library object available for actionscript, left click the item in the library and select 'Linkage'.  Check the box next to 'Export for ActionScript'.  You'll need to then give the object a class name and since you are dealing with a sound, make sure the base class is a Sound object.
Let's say you named your sound class "MySound", you can now access this object via actionscript like this (incorporating your code from the question):
var mysound:MySound = new MySound();
mysound.addEventListener(Event.COMPLETE, completeHandler);
mysound.play();

note:  if you want to further control the sound (stop, rew, etc), you'll need to create a SoundChannel object.  (see documentation below)
Adobe Sound Object Documentation


text:
Q: go-ethereum - geth - puppeth - ethstat remote server : docker: command not found I'm trying to setup a private ethereum test network using Puppeth (as Péter Szilágyi demoed in Ethereum devcon three 2017). I'm running it on a macbook pro (macOS Sierra).
When I try to setup the ethstat network component I get an "docker configured incorrectly: bash: docker: command not found" error. I have docker running and I can use it fine in the terminal e.g. docker ps.
Here are the steps I took:
What would you like to do? (default = stats)
 1. Show network stats
 2. Manage existing genesis
 3. Track new remote server
 4. Deploy network components
> 4

What would you like to deploy? (recommended order)
 1. Ethstats  - Network monitoring tool
 2. Bootnode  - Entry point of the network
 3. Sealer    - Full node minting new blocks
 4. Wallet    - Browser wallet for quick sends (todo)
 5. Faucet    - Crypto faucet to give away funds
 6. Dashboard - Website listing above web-services
> 1

Which server do you want to interact with?
 1. Connect another server
> 1

Please enter remote server's address:
> localhost
DEBUG[11-15|22:46:49] Attempting to establish SSH connection   server=localhost
WARN [11-15|22:46:49] Bad SSH key, falling back to passwords   path=/Users/xxx/.ssh/id_rsa      err="ssh: cannot decode encrypted private keys"
The authenticity of host 'localhost:22 ([::1]:22)' can't be established.
SSH key fingerprint is xxx [MD5]
Are you sure you want to continue connecting (yes/no)? yes
What's the login password for xxx at localhost:22? (won't be echoed)
>
DEBUG[11-15|22:47:11] Verifying if docker is available         server=localhost
ERROR[11-15|22:47:11] Server not ready for puppeth             err="docker configured incorrectly: bash: docker: command not found\n"

Here are my questions:

*

*Is there any documentation / tutorial describing how to setup this remote server properly. Or just on puppeth in general?

*Can I not use localhost as "remote server address"

*Any ideas on why the docker command is not found (it is installed and running and I can use it ok in the terminal).

A: Here is what I did.

*

*For the docker you have to use the docker-compose binary. You can find it here.

*Furthermore, you have to be sure that an ssh server is running on your localhost and that keys have been generated.

*I didn't find any documentations for puppeth whatsoever.

A: I think I found the root cause to this problem. The SSH daemon is compiled with a default path. If you ssh to a machine with a specific command (other than a shell), you get that default path. This does not include /usr/local/bin for example, where docker lives in my case.
I found the solution here: https://serverfault.com/a/585075:

*

*edit /etc/ssh/sshd_config and make sure it contains PermitUserEnvironment yes (you need to edit this with sudo)

*create a file ~/.ssh/environment with the path that you want, in my case:

PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin

When you now run ssh localhost env you should see a PATH that matches whatever you put in ~/.ssh/environment.


text:
Q: Python how to read text paragraph by paragraph I'm a Python beginner and I'm trying to read the example.txt file paragraph by paragraph using the iterator and next methods. The problem is, I cannot figure out how to read line by line in the next method without using a for loop or line = next(it). Any help would be greatly appreciated. Here is what I have until now.
class ByParagraph:

    def __init__(self, text):
        self.text = text

    def __iter__(self):
        return self
        par = ""

    def __next__(self):
        par = ""
        if (I still need to decide how to stop the iterations):
            raise StopIteration

        if str(self.text).isspace():
            return par.strip()
        else:
            return ' '.join([par, str(self.text)])

with open("example.txt") as f:
    for par in ByParagraph(f):
        print('BEGIN PAR' + par + 'END PAR')

A: So you need to actually consume self.text because this is a file iterator (f), i.e. you need to call next(self.text). You need to call this multiple times to consume all the lines until you receive a blank like, so you need a loop. A for loop will call next(self.text) so this should work, e.g.:
def __next__(self):
    par = []
    for line in self.text:
        if line.isspace():
            break
        par.append(line.strip())
    else:
        if not par:
            raise StopIteration()
    return ' '.join(par)

The for loop will cleanly exit on StopIteration so will enter the else clause. You should raise StopIteration only if there is no par to avoid missing the last paragraph.


text:
Q: Xbox360 to Dell All-in-one through HDMI cable, no sound When I connect my XBox 360 to my Dell All-in-One desktop through HDMI hook-up and switch to the HDMI source on my monitor, I get picture with no sound. How can I get sound?

A: *

*First, you need to check if your monitor supports sound over HDMI(Not all support it believe me)

*Second, check if your Xbox audio settings are in the stereo mode

*Third, check your volume.

A: The key-phrase is this:

Dell All-in-One desktop

This monitor is not even a monitor.  It is a PC attached to a monitor.
The speakers may not be part of the monitor.  It may be PC speakers that happen to be mounted to the side of the monitor, but hooked up to the PC.
You'll have to look at the specification of your device and see whether it really supports audio via HDMI.

A: Try the following:
1.Make sure the sound isn't muted and the volume is turned up on your TV.
2.Make sure the console audio settings are correct for your combination of TV and cables.
3.Update your console software.


text:
Q: Whitespace at bottom of page in IE7 and Chrome only I'm seeing extra whitespace at the very bottom of this page but only in IE7 and Chrome (and, as would be expected, in IE8 in IE7 Mode and Compatibility Mode).  Here's what it looks like for me in IE7.  I've examined the code using Firebug and the IE Developers Toolbar and didn't find any abnormalities.  Anyone know what is causing this browser-specific whitespace?   Thanks.

A: The reason you're getting the whitespace is because you're using relative positioning for the logos in your footer. Use absolute positioning instead.
Relative positioning shifts elements relative to their original position, but their original position is still "taken" and subsequent elements act as if nothing has changed.
So the whitespace is caused by the original positions those logos took up. If you comment out position: relative on all of the elements inside the footer you will see what is causing that whitespace.
Of course, absolute positioning isn't the only way to fix it, but it's certainly the easiest. You could also float them, use display: inline-block, display: table-cell perhaps, or even still use relative positioning, as long as you take the above into account (e.g. play with negative margins).

A: You can try this in your CSS:
* { margin:0px; padding:0px; }

If that works, then some element's padding or margin is causing the issue.
BTW, I get whitespace on Firefox as well.

A: Try removing the 100% height from body and html in CSS.
I am not perfectly sure if this is the reason, but I've seen bugs in the box model along with 100% height on elements creating this kind of problems.
BTW, it is in line 57 of your screen.css file.

A: Not good practice, but overflow hidden will hide it.


text:
Q: tinymce editor content not styled correctly I am building a small webapp for my website and have included tinyMCE as visual editor.
My site uses a free template and the contentarea has the id #left_side, which almost all styles refer to, that are relevant in articles.
So the editor is kind of wysiwyg, but the styles are wrong, because my styles, that I provided as content_css, won't fit.
I assume that is, because the #left_side id is not anywhere in the iframe.
I have googled for quite some time now and found no way to get tinyMCE to add for example a div with this ID around the editor content, so the css will work.
I don't think that it's hard to accomplish, I currently have just no idea how... :-/
Any ideas?
EDIT:
The content CSS is added like this:
tinyMCE.init({
    // General options
    mode : "textareas",
    theme : "advanced",
    plugins : "autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave",

    // Theme options
    theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
    theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
    theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
    theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    theme_advanced_statusbar_location : "bottom",
    theme_advanced_resizing : true,

    // Example content CSS (should be your site CSS)
    content_css : "/cms/static/style/site.css",
    ....

A: Not sure about it, but maybe one of the following configuration options could do it.

*

*http://www.tinymce.com/wiki.php/Configuration:body_class

*http://www.tinymce.com/wiki.php/Configuration:custom_elements
Please see also my other comments in Skype.


text:
Q: How do I convert my private MIB files into .py format so that I can perform GET/SET actions on my device I am trying to write a script that will perform GET/SET commands on my device. While I have tried to do GET action on sysDescr (which is part of the standard MIB SNMPv2) I managed to get a response.
I have tried to use the mibdump.py script in several different ways, in order to convert my proprietary MIB files so that I could later on work with them:

*

*activate the mibdump.py on a specific MIB file (see the result) with .mib extension and without
 c:\Program Files\Python35\Scripts>python mibdump.py SL-XPDR.mib
    Source MIB repositories: file:///usr/share/snmp/mibs, h ttp://mibs.snmplabs.com/a
    sn1/@mib@
    Borrow missing/failed MIBs from: h ttp://mibs.snmplabs.com/pysnmp/notexts/@mib@
    Existing/compiled MIB locations: pysnmp.smi.mibs, pysnmp_mibs
    Compiled MIBs destination directory: C:\Users\alpha_2.PL\PySNMP   Configuration\mibs
    MIBs excluded from code generation: RFC-1212, RFC-1215, RFC1065-SMI, RFC1155-SMI
    , RFC1158-MIB, RFC1213-MIB, SNMP-FRAMEWORK-MIB, SNMP-TARGET-MIB,   SNMPv2-CONF, SN
    MPv2-SMI, SNMPv2-TC, SNMPv2-TM, TRANSPORT-ADDRESS-MIB
    MIBs to compile: SL-XPDR
    Destination format: pysnmp
    Parser grammar cache directory: not used
    Also compile all relevant MIBs: yes
    Rebuild MIBs regardless of age: no
    Do not create/update MIBs: no
    Byte-compile Python modules: yes (optimization level 0)
    Ignore compilation errors: no
    Generate OID->MIB index: no
    Generate texts in MIBs: no
    Try various filenames while searching for MIB module: yes
    Created/updated MIBs:
    Pre-compiled MIBs borrowed:
    Up to date MIBs:
    Missing source MIBs: SL-XPDR
    Ignored MIBs:
    Failed MIBs:

*I have tried again with specific MIB file location with no success

*I have even tried to compile the whole MIB folder without any success
c:\Program Files\Python35\Scripts>python mibdump.py C:\Program Files\Python35\Scripts\mibs
    Source MIB repositories: file:///usr/share/snmp/mibs, file://C:\, file://c:\Prog
    ram Files\Python35\Scripts\Files\Python35\Scripts, h ttp://mibs.snmplabs.com/asn1/@mib@
    Borrow missing/failed MIBs from: h ttp://mibs.snmplabs.com/pysnmp/notexts/@mib@
    Existing/compiled MIB locations: pysnmp.smi.mibs, pysnmp_mibs
    Compiled MIBs destination directory: C:\Users\alpha_2.PL\PySNMP Configuration\mibs
    MIBs excluded from code generation: RFC-1212, RFC-1215, RFC1065-SMI, RFC1155-SMI, RFC1158-MIB, RFC1213-MIB, SNMP-FRAMEWORK-MIB, SNMP-TARGET-MIB, SNMPv2-CONF, SNMPv2-SMI, SNMPv2-TC, SNMPv2-TM, TRANSPORT-ADDRESS-MIB
    MIBs to compile: Program, mibs
    Destination format: pysnmp
    Parser grammar cache directory: not used
    Also compile all relevant MIBs: yes
    Rebuild MIBs regardless of age: no
    Do not create/update MIBs: no
    Byte-compile Python modules: yes (optimization level 0)
    Ignore compilation errors: no
    Generate OID->MIB index: no
    Generate texts in MIBs: no
    Try various filenames while searching for MIB module: yes
    Created/updated MIBs:
    Pre-compiled MIBs borrowed:
    Up to date MIBs:
    Missing source MIBs: Program, mibs
    Ignored MIBs:
    Failed MIBs:

What is the right way to transform my proprietary MIB files into .py files ?

A: If you are running SNMP management application, you do not really need to compile MIBs explicitly -- pysnmp will do that for you behind the scenes by calling pysmi compiler and caching compiled MIB for future occasions. Here's an example script that does just that.
You problems with mibdump seems to be related to MIB search paths. Given you have your MIB file in currect working directory, this command should do it:
mibdump.py  --mib-source . --mib-source http://mibs.snmplabs.com/asn1/@mib@ SL-XPDR

The idea is that you tell mibdump to first check out your cwd, then try the on-line MIB repository (for other MIB files your MIB may depend on).
In your screen paste it looks like paths get corrupted by whitespaces. I'm not sure is it because of cut&paste or you need to quote them at your command-line.