text:
Q: Is it possible to override the nested class definition of an abstract parent, within an inheriting class? Context
I have an scenario in which I wish to define several Bar classes, each of which must define Request, Response and Error classes of their own. For this reason, I have written an abstract Foo class, within an intension to force an the implementation.
Request, Response and Error share a base class, PDU, and must implement their respective interfaces. Each Bar requires a sufficiently unique Request, Response and Error, that they must be independently defined.
Furthermore, the Request, Response and Error of each Bar shall not be instantiated outside of that Bar, so it seems correct (at least to me) that the class definitions should be nested.
Question
Is it possible to override a nested class definition within a child, inheriting from an abstract parent? Or at least to achieve the same through another approach?
Illegal Example
Below is an illegal code example of how I would of liked to write it:
public abstract class Foo
{
    public class Request: PDU, IRequest
    { }

    public class Response : PDU, IResponse
    { }

    public class Error : PDU, IException
    { }
}

public class Bar : Foo
{
    public override Request
    {
        // Definition of Request goes here
    }

    public override Response
    {
        // Definition of Response goes here
    }

    public override Error
    {
        // Definition of Error goes here
    }
}

A: It isn't possible to override a nested class, so your current approach won't work. However, I think this is what you are trying to achieve.
My advice would be to use interfaces and generics. So let's say you have your 3 interfaces:
public interface IRequest
{
    //snip
}
public interface IResponse
{
    //snip
}

public interface IException
{
    //snip
}

Now you can make your base class look like this:
public abstract class BaseThing<TRequest, TResponse, TError>
    where TRequest : IRequest
    where TResponse : IResponse
    where TError : IException
{
    // An example method
    public abstract TResponse GetThing(TRequest request);
}

Now you can make some concrete definitions of the above things:
public class FooRequest : IRequest
{
    //snip
}

public class FooResponse : IResponse
{
    //snip
}

public class FooError : IException
{
    //snip
}

public class FooThing : BaseThing<FooRequest, FooResponse, FooError>
{
    public override FooResponse GetThing(FooRequest request)
    {
        //snip
    }
}

A: Since the classes Request, Response and Exception are very specific to each Bar class, it does not look like the case for a 'class'. All you need is the interfaces IRequest, IResponse, IException.
Implement these interfaces in each 'Bar' class and provide class specific implementation for the methods in the interface. This way there is no issue for derived classes, regular inheritance principles will work.
What remains is the question of inheriting from PDU class - Does the PDU class contain any implementation? Or is it an abstract class? If it does not have any implementation, it can be converted into an interface which can be implemented by Bar classes.
If it contains implementation, each Bar class can create an instance of PDU class for use by the methods implementing IRequest/IResponse/IException.


text:
Q: XPS Printing of Visuals from different thread than the UI thread - is it possible? Why am I getting this strange exception when I'm trying to write to an XPS document?
XpsPackagingException:
Package already has a root DocumentSequence or FixedDocument.

My goal is to print a WPF Visual into an XPS file, but because the visual tree is so big, the printing process could be very slow, so I want to find out how can I print XPS files on a background thread, so my users won't get annoyed because of a frozen application.
Here is my code:
Dispatcher otherThreadDispatcher;
public MainWindow()
{
    InitializeComponent();
    Thread thread = new Thread(() =>
    {
       otherThreadDispatcher =  Dispatcher.CurrentDispatcher;
       printIt.Click += new RoutedEventHandler(printIt_Click);
       System.Windows.Threading.Dispatcher.Run();
    });
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
}

void printIt_Click(object sender, RoutedEventArgs e)
{
    otherThreadDispatcher.Invoke(new Action(() =>
    {
       using (XpsDocument myDoc = new XpsDocument("foo.xps", FileAccess.ReadWrite))
       {
           XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(myDoc);
           var collator = writer.CreateVisualsCollator();
           collator.BeginBatchWrite();
           collator.Write(someImageToPrint);
           collator.EndBatchWrite();
       }
    }));
}

A: Why not use asynchronous pattern like async and await or Tasks? That way you don't have to bother about threading much.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pass parameter and model to component view in PagedListPager i am traying to use PagedList in asp.net core
Function List in view component name : AdvListViewComponent.cs
public async Task<IViewComponentResult> InvokeAsync(int page = 1)
    {

        var adv = _db.advertisements.OrderByDescending(i => i.AdvId);
        return View(adv.ToList().ToPagedList(page , 6 ));
    }

in asp.net mvc i use this code To go to the next page ( My List function was Index in controller)
 @Html.PagedListPager(Model, page => Url.Action("Index", new { page }))

how  can i  pass paremeter page and Model to View Component InvokeAsync (AdvList)  AdvListViewComponent.cs  using lambda and PagedListPager
to go to the next page

A: The better way would be to use a complex model for the View. The complex model will carry all the necessary date from the action to the View. For example:
View Model:
public class MyViewModel {
   public MyViewModel(){
      advList = new List<Adv>();
   }

   public int pageIndex {get; set;}
   public int pageSize {get; set;}
   public int TotalCount {get; set;}
   public string OrderBy {get; set;}
   public List<Adv> advList {get; set;}
}

Action:
public async Task<IActionResult> InvokeAsync(MyViewModel model)
{
    var adv = _db.advertisements
        .skip(model.pageIndex * model.pageSize)
        .Take(model.pageSize)
        .OrderByDescending(i => i.AdvId);

    model.advList = adv.ToList().ToPagedList(model.pageIndex + 1 , model.pageSize)
    return View(model);
}

This allows you to only load the data for the current page and not all the data. Then in the View:
@Html.PagedListPager(Model.advList, page => Url.Action("Index",
    new { Model.pageIndex, sortOrder = Model.OrderBy }))

Now if you click the pager then in the action's parameter the pageIndex and OrderBy will be auto populated from the UI.
This way you can send-receive multiple parameters between view and controller.


text:
Q: How to properly style excel file with laravel? I'm trying to export data from database into excel file.this is the code i'm using to display my data into the newly created excel file:
$name = 'fiche signaletique '.date('d-m-Y H-i');

        Excel::create($name, function($excel) use($cards, $count) {

            $excel->sheet('Sheetname', function($sheet) use($cards, $count) {

                $i = 2;
                $rows = $count;
                $rows++;

                $sheet->setHeight(1, 25);
                $sheet->setAutoSize(true);
                $sheet->setBorder('A1:AI'.$rows, 'thin');

                $sheet->row(1, array(

                    'Client (Société)',
                    'Numéro Fiche',
                    'Forme juridique',
                    'Capital Social',
                    'Type'

                ))->cells('A1:AI1', function($cells) {

                    $cells->setBackground('#1E86CF');
                    $cells->setFont(array(
                        'family'     => 'Calibri',
                        'size'       => '12',
                        'bold'       =>  true
                    ));
                    $cells->setFontColor('#ffffff');

                });

                foreach ($cards as $key => $card) {
                    $sheet->row($i, array(

                        $card->clientsociete['company'],
                        $card->card_code,
                        $card->legal_form,
                        $card->share_capital,
                        $card->group

                    ))->cells('A'.$i, function($cells) {

                        $cells->setBackground('#D9D9D9');

                    });

                    $i++;
                }

            });

        })->download('xls');

The problem that i have is that the last column doesn't have any style(no font or background color).


text:
Q: Where will the reducer output save in Hadoop is it in Client node or in HDFS I am trying to set output path as per the client node,
public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();
    String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
    if (otherArgs.length != 2) {
        System.err.println("Usage: wordcount <in> <out>");
        System.exit(2);
    }
    Job job = new Job(conf, "word count");
    job.setJarByClass(WordCount.class);
    job.setMapperClass(TokenizerMapper.class);
    job.setCombinerClass(IntSumReducer.class);
    job.setReducerClass(IntSumReducer.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);
    FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
    FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));

    System.exit(job.waitForCompletion(true) ? 0 : 1);
}

But it's always referring to HDFS. eg. FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
How can I get the file on the client using map reduce? I know we can achieve this with the copyToLocal command. But I'm wondering if there is a way to pipe the reducer output straight away to the client Local File directory. How can this be done?

A: In a multinode hadoop cluster, the reduce tasks corresponding to a mapreduce job can execute in any of the nodes. So if you are adding a logic to write the output of reducer directly to local instead of hdfs, it may get saved in some of the nodemanager or tasktracker nodes. If you have only one node, you can implement the write to local logic in the reducer class. But this is not a good logic.
If you really need the output in the local directory of client machine, then performing copyToLocal to the client/edge node using api will be the best approach.


text:
Q: What the difference between a namespace and a module in F#? I've just started learning F# (with little prior experience with .NET) so forgive me for what is probably a very simple question: What the difference between a namespace and a module in F#?
Thanks
Dave
Edit: Thanks for the answer Brian. That's what I wanted to know.
Just a clarification: can you also open a namespace as well (similar to C# using statement)?

A: A namespace is a .Net thing, common in many industrial-strength languages, just a way to organize frameworks and avoid naming conflicts among different libraries.  Both you and I can define a type "Foo" and use them both in a project, provided they are in different namespaces (e.g. NS1.Foo and NS2.Foo).  Namespaces in .Net contain types.
A module is an F# thing, it is roughly analogous to a "static class"... it is an entity that can hold let-bound values and functions, as well as types (note that namespaces cannot directly contain values/functions, namespaces can only contain types, which themselves can contain values and functions).  Things inside a module can be referenced via "ModuleName.Thing", which is the same syntax as for namespaces, but modules in F# can also be 'opened' to allow for unqualified access, e.g.
open ModuleName
...
Thing  // rather than ModuleName.Thing

(EDIT: Namespaces can also similarly be opened, but the fact that modules can contain values and functions makes opening a module more 'interesting', in that you can wind up with values and functions, e.g. "cos", being names you can use directly, whereas in other .Net languages you'd typically always have to qualify it, e.g. "Math.cos").
If you type in code at 'the top level' in F#, this code implicitly goes in a module.


text:
Q: substitution of ConfigurationManager I'm working on an windows phone 7 project, I want to read the appsettings from config file such as app.config using ConfigurationManager class, but seems it is not implemented in windows phone 7 sdk, I have no idea now how to resolve this issue, anyone knows this?
I'm using vs 2010
OS windows 7
thanks

A: I once implemented a simple config class, that read configuration from a xml file added to the project. Take a look at https://github.com/igorkulman/Kulman.WP7/blob/master/Kulman.WP7/Config/AppConfig.cs.
This requires having app.config in the project and calling AppConfig.ParseAndLoadAppConfig() in App.xaml.cs constructor.


text:
Q: Material UI Webpack Build I did a little app using React, FullCalendar, JQuery, Material UI combined with Formsy-material-ui.
The app consists showing the fullcalendar with events.
This events are created doing click in a spot of the calendar and It renders a Form inside a Dialog with components like FormsySelect, FormsyDatepicker or FormsyTextfield.
When I do the build with webpack, generates a bundle with a weight of 588kb.
The Dialog form I load in another component by the way.
If I don't render my Dialog component the size of the bundle is 220kb.
Could Material UI be the responsible for this?.
Edit: I leave the imports that I made in the Dialog Component.
import React, { Component, PropTypes } from 'react';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Formsy from 'formsy-react';
import RaisedButton from 'material-ui/RaisedButton';
import MenuItem from 'material-ui/MenuItem';
import { FormsySelect, FormsyText, FormsyTime, FormsyDate, FormsyCheckbox } from 'formsy-material-ui/lib';
import Dialog from 'material-ui/Dialog';
import { mouseTrap } from 'react-mousetrap';

A: The proper way to go about solving this problem is to analyse you bundle first. Try running source-map-explorer against it:
$ sudo npm install -g source-map-explorer
$ source-map-explorer bundle.min.js
$ source-map-explorer bundle.min.js bundle.min.js.map

This will open up a visualization of how the space is used in your minified bundle.
Another good tool is webpack-bundle-analyzer.


text:
Q: Easy Java Boolean I need help with fixing my boolean, I am very new to programming and my professor's english is poor.
I need to add 5 to mpg if highway is true and subtract 2 when city is false.
import java.util.Scanner;

public class AdvancedTripCalc {
    public static void main(String[] args) {
        // New Trip Calc.
        String firstname;
        int mpg;
        int miles;
        double price;
        double totalcost;

        Scanner in = new Scanner(System.in);
        System.out.println("Please enter your First Name");
        firstname = in.nextLine();
        System.out.println("Please enter the MPG of your car");
        mpg = in.nextInt();
        boolean highway = true;
        boolean city = false;
        if (highway == true) {
            mpg = mpg + 5;
        }
        if (city == false) {
            mpg = mpg - 2;
        }
        System.out.println("Enter true if trip is on the highway false if the trip is       in the city");
        in.nextBoolean();
        System.out.println("Please enter the Miles to be traveled");
        miles = in.nextInt();
        System.out.println("Please enter the price per gallon of gas");
        price = in.nextDouble();

        totalcost = miles * price / mpg;
        System.out.println("Your name is " + firstname);
        System.out.println("Your MPG is " + mpg);
        System.out.println("Your miles to be traveled is " + miles);
        System.out.println("Your price per gallon of gas is " + price);
        System.out.println("Your total cost is " + totalcost);
    }
}

A: Make one boolean variable, for example, boolean inCity;
Change in.nextBoolean(); to inCity = in.nextBoolean();
Then AFTER you have your input value you can check using the if statements. In your code, you check the if statement before you get the input.
So you would have this:
boolean inCity;
System.out.println("Are you in the city?(true/false): ");
inCity = in.nextBoolean(); //Store input in variable

if (inCity) { //If the condition is a boolean variable, you can type it like this(if (boolean) )
    mpg -= 2;//Same as mpg = mpg - 2;
} else { //if inCity is false:
    mpg += 5; //mpg = mpg + 5;
}

A: if (highway) {
    mpg = mpg + 5;
}

if (!city) {
    mpg = mpg - 2;
}

should be
if (highway) {
    mpg = mpg + 5;
} else { //not highway, so city
    mpg = mpg - 2;
}

Right now you check if its a highway. If it is true the code adds 5. Then you check if it is not a city. If it is false the code subtracts 2.
Also, you can only check the boolean after it has been submitted:
System.out.println("Enter true if trip is on the highway false if the trip is in the city");
boolean highway = in.nextBoolean();
if (highway) {
    mpg = mpg + 5;
} else { //not highway, so city
    mpg = mpg - 2;
}


text:
Q: SSIS Rows Being Reduced From Original Amount I can't seem to figure this out?
Out of the 28,804 rows I'm extracting from SQL Server to Insert into Excel Data Source I'm being limited to just 10,000 and I'm not sure why. On the Data Flow Task properties I've switched AutoAdjustBufferSize to True and False as I suspect this might be to do with buffer size; it didn't help.
If I limit the actual query to 10000 rows or less no problems but above that the package just hangs but doesn't necessarily fail
Thanks


text:
Q: How to handle case when API response returns a null body in Java? I am calling a File Server's REST API using POST method and sending it file content to be uploaded. The REST API should ideally save the file and send a response which contains fileName.
My code is something like this.
public String uploadFile() {
    UploadResponse response = restTemplate.postForObject(
            FILE_SERVER_URL/upload,
            new HttpEntity<>(fileContent, headers),
            UploadResponse.class);
    return response.getFileName();
}

In the above code, the compiler complains that UploadResponse response could be null, and I should handle that.
I plan to handle it with the below code.
public String uploadFile() {
    UploadResponse response = restTemplate.postForObject(
            FILE_SERVER_URL/upload,
            new HttpEntity<>(fileContent, headers),
            UploadResponse.class);
    if(response != null) {
            return response.getFileServiceId();
        }
        else {
            throw new RuntimeException("File upload failed");
        }
}

However, I am not sure if it is the right way to handle this. I don't feel this is a Runtime Exception. Please guide me as how should I handle the case that response could be null.

A: You can use Optional to avoid null checks in your code.
You can read this really insightful Q/A here - https://softwareengineering.stackexchange.com/questions/309134/why-is-using-an-optional-preferential-to-null-checking-the-variable


text:
Q: Unable to map Firebase db items edit: including codepen:
https://codepen.io/hugerobots/pen/YeMWbY?editors=1010
Following is a pretty simple exercise in mapping database items to output into a
 per child database item.
The error after rendering (everything works until I implement the map below).

Uncaught TypeError: Cannot read property 'map' of undefined

The example I'm following along with is a few years old, so there might be some changes to what I'm following, with caveats to updated instruction from the actual Firebase documentation.
https://css-tricks.com/firebase-react-part-2-user-authentication/
Where I'm getting turned around is probably the repetition of using items and item in reference to the actual items in the database and use of the term in the code below.
handleSubmit(e) {
    e.preventDefault();
    const itemsRef = firebase.database().ref('vendors');
    const item = {
        name: this.state.user.displayName || this.state.user.email,
        email: this.state.user.email,
        vendorName: this.state.user.vendorName,
        vendorType: this.state.user.vendorType
    }
    itemsRef.push(item);
    this.setState({
        username: '',
        email: '',
        vendorName: '',
        vendorType: ''
    });
}

componentDidMount() {
    // retrieve data
    const itemsRef = firebase.database().ref('vendors');
    itemsRef.on('value', (snapshot) => {
        let items = snapshot.val();
        let newState = [];
        for (let item in items) {
            newState.push({
                id: item,
                name: items[item].username,
                email: items[item].email,
                vendor: items[item].vendorName,
                vendtype: items[item].vendorType
            });
        }
        this.setState({
            items: newState
        });
    });
}

And the problem map:

{this.state.items.map((vendors) => {
    return (

{vendors.name}

Vendor Name: {vendors.vendorName}
            {vendors.name === this.state.user.username || vendors.user === this.state.user.email ?
                <button onClick={() => this.remoteItem(vendors.id)}>Remove Item</button> : null}

    )
})}

A: You can set an empty state items array in the constructor to avoid the undefinederror in render():
this.state = { items: [] }

This is just an idea, as ignore how your constructor looks like.

A: With React, at the time this component mounts and loads the jsx. this.state.items doesn't exist yet or is empty. You can use a conditional.
{this.state.items.length > 0 ?
{this.state.items.map((vendors) => {
    return (

{vendors.name}

Vendor Name: {vendors.vendorName}
            {vendors.name === this.state.user.username || vendors.user === this.state.user.email ?
                <button onClick={() => this.remoteItem(vendors.id)}>Remove Item</button> : null}

    )
})}
:
Asynccccc
 }

I think you may have some async issues. try this.
componentDidMount() {
// retrieve data
let items;
let newState = [];
const itemsRef = firebase.database().ref("vendors");
itemsRef
  .on("value", snapshot => {
    items = snapshot.val();
    for (let item in items) {
      newState.push({
        id: item,
        name: items[item].username,
        email: items[item].email,
        vendor: items[item].vendorName,
        vendtype: items[item].vendorType
      });
    }
  })
  .then(() => {
    this.setState(
      {
        items: newState
      },
      function() {
        console.log(
          "Maybe you were setting state before your for each finishes"
        );
      }
    );
  });

}

A: Try && (and) operator
 {this.state.items.length > 0 && this.renderItems()}

where
renderItems= () => {
   return this.state.items.map((vendors) => {
    return (

{vendors.name}

Vendor Name: {vendors.vendorName}
            {vendors.name === this.state.user.username || vendors.user === this.state.user.email ?
                <button onClick={() => this.remoteItem(vendors.id)}>Remove Item</button> : null}

    )
})
}


text:
Q: Задание поля класса Хочу сделать метод который принимал бы два значения: название поля и экземпляр класса, и задавал бы по ключу названия этот экземпляр.
То-есть примерно сделующее:
class GameObject{
  addComponent(name, component){
      this.name = component;
    }
  }

По-сути некий аналог addComponent в unity.
Как сделать так, чтобы интерпретатор воспринимал name не как поле, которое нужно задать, а как переменную (надеюсь, понятно объяснила:) )

A: Вот так
class GameObject {
  addComponent(name, component) {
      this[name] = component;
  }
}


text:
Q: Kibana - plot count of unique words from @message field I am working in an environment with many different log files and many differently formatted log lines (100+) within each.
I have used grok extensively to reveal all kinds of exciting trends in these but I was wondering if there is a simple generic plot that could give me some insight into the frequency of words in any logfile?
Is it possible in Kibana 4 beta 3 to plot a count of unique words from the @message field? (I'm not interested in any numbers, I work with bandwidths, frequencies which are constantly changing).
Consider the following logfile:
29/01/2015 17:45:00 INFO Loading Banana 3218763kbs Retrieved - null /absy
29/01/2015 17:45:01 DEBUG Apple Interrogation, Completed 25
29/01/2015 17:45:02 EXCEPTION! Fruit rotting in 34 days
29/01/2015 17:45:03 Critical word of the day is pineapple 123456789
Imagine 200 more variations of the above.
I would like to count each word returned by:
cat logfile |cut -d" " -f3- |tr -d [0-9]
i.e. remove the timestamp, delete the numbers and then count the frequency of each word.  A pie chart/count of common terms within a logfile I may never have seen before would be extremely useful:
BANANA 788
Help 692
Exception 678
Orange 53
Retrieved 287
I thought an aggregation of "significant terms" on the field "message" would help, but only if I can exclude any numbers, which it doesn't seem possible to do.
Thanks!

A: Answer was to use "Terms" instead of "Significant terms" with the include pattern [A-Za-z]{2,}* to include only words (not numbers) of 2 letters or more.
Cool!


text: Q: logcat messages from my device missed some lines Do we trust logcat message from devices? I found that logcat messages from my Sansung Galaxy S20 device missed some lines sometimes. Logcat worked fine on other Android devices I have. The missing lines from my device's logcat really gave me troubles and wrong information for my debugging. Note that I turned chatty off for my device, so it is not an Android chatty issue. Does anyone see the same issues for logcat?


text:
Q: How to enqueue the script without hardcoded in the theme files? I have been working on the Custom Gallery Layout style and was wondering how do I enqueue and make the following script working without hard coded in the file. Or is there a better way of adding it via inline script wp_add_inline_script().
I tried with wp_add_inline_script() but that didn't helped. May be I was doing something wrong.
How to add the localize or enqueue the code which is nested with  tags in the below code.
add_action('print_media_templates', function() {
// define your backbone template;
// the "tmpl-" prefix is required,
// and your input field should have a data-setting attribute
// matching the shortcode name

$gallery_types = apply_filters('print_media_templates_gallery_settings_types',
    array(
        'justified' => esc_html__( 'Justified','textdomain' ),
        'grid'      => esc_html__( 'Grid','textdomain' ),
        'slider'    => esc_html__( 'Slider','textdomain' ),
        'default_val'    => esc_html__( 'Default','textdomain' ),
    )
);
?>


text:
Q: Pull out the minumum value in the CSV file I am trying to pull out all the relevant info for the lines with the minimum value in a csv file with Python.
Below is my code to find out the relevant information.
The minimum value is 12 when I code it spaerately.
But when I put in the function and will process the minimum to find and record other data in the csv file.The value can not be updated. What I am missing to update the value of line[9]?
The CVS file contains a column of numbers and I need to find the minimum.
The separate coding works well to find the minimum of 12 and I did it as a test. But it does not work after I assign a function and use the same method to find the minimum.
As I need to use the minimum in other part of the code, it is better if I can put it in the function and make it work.
So I would like to know how should transfer the function also works in finding the minimum.
Thank you in advance.
#put finding minimum in to a function and will use the returned minimum
#to pull out other information
def findMin():
minMile = 100
if num<minMile:
    minMile=num
return minMile

def main():
    fileIn = open("epaVehicleData2008.csv", "r")
    fileIn.readline()
    for line in fileIn:
        line = line.split(",")
        num=int(line[9])
        findmin(line)
        minMile=int(line[9])
        print(minMile)

main()

#separate code for finding the minimum as a test
fileIn = open("epaVehicleData2008.csv", "r")
fileIn.readline()
minMile = 100
for line in fileIn:
    line = line.split(",")
    num = int(line[9])
    if num < minMile:
        minMile = num
print(minMile)

A: This can be done using Python's CSV library to help with reading each line and automatically splitting it in a list:
import csv

def findMin(filename):
    with open(filename, 'r', newline='') as f_input:
        csv_input = csv.reader(f_input)
        return min(csv_input, key=lambda x: int(x[9]))[9]

print('Min mile', findMin('epaVehicleData2008.csv'))

The built-in min() function can be used to determine the smallest row. It takes a key parameter which tells it which part of the input you want to compare with, in this case the 9th element.
Each time you call your findMin(), the value for minMile will always be 100. In your design, you would need to make the variable global, rather than local to your function. Perhaps a better approach would be to pass the function a filename and let it read and calculate the minimum in one go and return that value.
lambda is just a function written inline without needing a separate def. In this case, it takes x being a row, and returns the ninth value as an integer.


text:
Q: $z_n\to 0$, then $\frac{1}{n}(z_1+\cdots + z_n)\to 0$ if
$$z_n\to 0$$, then $$\frac{1}{n}(z_1+\cdots + z_n)\to 0$$
I'm sorry for asking this one, I've seen it in may places before but I cannot think of a way to solve it, and I don't know how to search it here. Also, I've seen the solution before for real numbers.

A: Let $\epsilon>0$ be given, and let $N\in\Bbb N$ be such that for all $n>N$ $z_n<\epsilon/2$. Then we have

$${1\over n}\sum_{i=1}^nz_i = {1\over n}(z_1+\ldots + z_N) + {1\over n} (z_{N+1}+\ldots + z_n).$$

Taking absolute values and using the triangle inequality we have
$${1\over n}\left|\sum_{i=1}^nz_i\right| \le {1\over n}\left|z_1+\ldots + z_N\right| + {\epsilon\over 2}.$$
Now if we also choose $n> \displaystyle{2\over\epsilon}N\displaystyle\max_{1\le i\le N}\{|z_i|\}$ we see that this gives us

$${1\over n}\left|\sum_{i=1}^nz_i\right| \le \epsilon$$

as desired.


text:
Q: Basic UI-Routing Example but an error occurs I try to learn AngularJS. At the moment I focus on ui-Routing.
My Code is very simple, but it doenst work and I don't know why.
Description of my problem:
http://de.tinypic.com?ref=kd22ow.jpg
The browser shows:
"Hello World ui-Routing!" (h1 in index.html)
If I try to enter index.html/home.
It says: Error File not found!
Here is my Code:
index.html

        <title>My Angular App!</title>

Hello World ui-Routing!

app.js:
angular.module('Test', ['ui-router'])

.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterprovider)
{
  $stateProvider

    .state('home', {
      url: '/home',
      templateUrl: '/home.html',
      controller: 'MainCtrl'
    });

    .state('test', {
      url: '/test',
      templateUrl: '/test.html',
      controller: 'TestCtrl'
    });

  $urlRouterProvider.otherwise('home');
}])

.controller('MainCtrl', ['$scope',
function($scope){
 $scope.test = "Hello Jan!";
});

.controller('TestCtrl', ['$scope',
function($scope){
 $scope.test = "Hello Redirect!";
});

test.html:

Hello Test!

home.html:

Hello Home!

Where is my problem?
Looking forward to your answers,
Jan

A: You need to include the ui-router script in your html page too it is a third party and not included in angular.


text:
Q: Can I get str_extract to take a piece of text in the middle of a file name? A different program I am using (Raven Pro) results in hundreds of .txt files that include nine variables with headers. I also need the file name that each line is being pulled from.
I am using stringr::str_extract(names in order to get a file name thrown into a dataframe with rbindlist. My problem is that I only want a portion of the file name included.
Here's an example of one of my file names -
BIOL10_20201206_180000.wav.Table01.txt

so if I do ("\\d+")) to try and get numbers it only picks up the 10 before the underscore, but the portion of the file name I need is 20201206_180000
Any help to get around this is appreciated :)
library(plyr)
myfiles <-  list.files(path=folder, pattern="*.txt", full.names = FALSE)
dat_tab <- sapply(myfiles, read.table, header= TRUE, sep = "\t", simplify = FALSE, USE.NAMES = TRUE)
names(dat_tab) <- stringr::str_extract(names(dat_tab), ("\\d+"))
binded1 = rbindlist(dat_tab, idcol = "files", fill = TRUE)

ended up with file name coming in as "10" from the file name "BIOL10_20201206_180000.wav.Table01.txt"

A: A couple other options:
x <- "BIOL10_20201206_180000.wav.Table01.txt"

#option 1
sub("^.*?(\\d+_\\d+).*$", "\\1", x)
#> [1] "20201206_180000"

#option 2
stringr::str_extract(x, "(?<=_)\\d+_\\d+")
#> [1] "20201206_180000"

A: You can specify the length:
library(stringr)
str_extract(x, "\\d{8}_\\d{6}")
# "20201206_180000"


text:
Q: filter data in BigQuery based on importance of data points sql I am merging two tables in BigQuery and filtering those on a couple of conditions. The code looks like this:
SELECT,
    d.id,
    d.duration,
    c.action,
    c.url
FROM
    (
        `table_action_url` c
        INNER JOIN `table_duration` d ON (d.id = c.id)
    )
WHERE c.url LIKE "https://www.mywebpage%"
AND d.duration = '15000'
AND c.action in ('First quartile', 'Midpoint', 'Third quartile', 'Complete')

The output is:
id      duration      action                    url
1         15000        Midpoint           https://www.mywebpage_fashion
1         15000        Complete           https://www.mywebpage_fashion
2         15000        First quartile     https://www.mywebpage_home
2         15000        Midpoint           https://www.mywebpage_home

I need to add a logic that would grab only one value from action. And the priorities are Complete, Third quartile etc. So the code needs to compare ids and urls and if the max values are Complete (for the same ids & urls), then grab that.
Desired output is:
id      duration      action                    url
1         15000        Complete           https://www.mywebpage_fashion
2         15000        Midpoint           https://www.mywebpage_home

A: You can use window functions and a CASE expression:
SELECT * EXCEPT(rn)
FROM (
    SELECT,
        d.id,
        d.duration,
        c.action,
        c.url,
        ROW_NUMBER() OVER(PARTITION BY d.id ORDER BY CASE c.action
            WHEN 'Complete' THEN 1
            WHEN 'Third quartile' THEN 2
            WHEN 'Midpoint' THEN 3
            WHEN 'First quartile' THEN 4
        END) rn
    FROM `table_action_url` c
    INNER JOIN `table_duration` d ON d.id = c.id
    WHERE
        c.url LIKE "https://www.mywebpage%"
        AND d.duration = '15000'
        AND c.action in ('First quartile', 'Midpoint', 'Third quartile', 'Complete')
) t
WHERE rn = 1

A: In BigQuery, you can do this using aggregation:
SELECT d.id, d.duration,
       ( ARRAY_AGG(c.action ORDER BY ao.ord DESC LIMIT 1) )[ORDINAL(1)] as action,
       ( ARRAY_AGG(c.url ORDER BY ao.ord DESC LIMIT 1) )[ORDINAL(1)] as url
FROM `table_action_url` c JOIN
     `table_duration` d
     ON d.id = c.id JOIN
     (SELECT 'Complete' as action, 1 as ord UNION ALL
      SELECT 'Third quartile' as action, 2 as ord UNION ALL
      SELECT 'Midpoint' as action, 3 as ord UNION ALL
      SELECT 'First quartile' as action, 4 as ord
     ) ao
     ON c.action = ao.action
WHERE c.url LIKE 'https://www.mywebpage%' AND
      d.duration = '15000'
GROUP BY d.id, d.duration;

A: The easiest and generic way I see here is just to wrap up your existing query with below code
#standardSQL
SELECT AS VALUE
  ARRAY_AGG(current_query_result
    ORDER BY CASE action
      WHEN 'Complete' THEN 1
      WHEN 'Third quartile' THEN 2
      WHEN 'Midpoint' THEN 3
      WHEN 'First quartile' THEN 4
    END
    LIMIT 1
  )[OFFSET(0)]
FROM (
  SELECT,
    d.id,
    d.duration,
    c.action,
    c.url
  FROM `table_action_url` c
  INNER JOIN `table_duration` d USING(id)
  WHERE c.url LIKE "https://www.mywebpage%"
  AND d.duration = '15000'
  AND c.action in ('First quartile', 'Midpoint', 'Third quartile', 'Complete')
) current_query_result
GROUP BY id, url

with output
Row id  duration    action      url
1   1   15000       Complete    https://www.mywebpage_fashion
2   2   15000       Midpoint    https://www.mywebpage_home

As you can see the way to order candidates and pick one is implemented via below fragment
ORDER BY CASE action
  WHEN 'Complete' THEN 1
  WHEN 'Third quartile' THEN 2
  WHEN 'Midpoint' THEN 3
  WHEN 'First quartile' THEN 4
END
LIMIT 1

There is another option to achieve the same with less verbose, easier to manage and probably more efficient (this is not proven - just my feeling) code
ORDER BY STRPOS('Complete, Third quartile, Midpoint, First quartile', action)
LIMIT 1


text:
Q: C# : Extract data from image using iTextSharp Hello I m trying to extract data from scanned document or pdf file which contains images whith some data . For PdF file i have succeeded to read data ,but fro images or pdf that contains pictures , i  failed .
I have converted the image file to pdf but there is no result .
This my small code :
 public bool ConvertImageToPdf(string ImageIn, string PDFOut)
        {

            try
            {
                iTextSharp.text.Document doc1 = new iTextSharp.text.Document();
                byte[] b = File.ReadAllBytes(ImageIn);
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(b);
                using (FileStream fs = new FileStream(PDFOut, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    using (Document doc = new Document(image))
                    {
                        using (PdfWriter writer = PdfWriter.GetInstance(doc, fs))
                        {

                            Paragraph paragraph = new Paragraph("");
                            doc.Open();

                            image.SetAbsolutePosition(0, 0);
                            writer.DirectContent.AddImage(image);
                            doc.Add(paragraph); // add paragraph to the document
                            doc.Add(image); //add an image to the created pdf document
                            doc.Close();
                            return true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return false;
            }

        }

And for extracting data , i use this code :
   for (int page = 1; page <= reader.NumberOfPages; page++)
                {
                    outFile.Write(ExtractTextFromPDFBytes(reader.GetPageContent(page)) + " ");
}

the ExtractTextFromPDFBytes(byte[] input) is similar on codeProject sample


text:
Q: get-content : Cannot find path 'PATH_TO_FILE_' because it does not exsist I am writing a PS Script to try and locate a folder on a remote server. Here is the code:
# Set file to be tested for, put everything after c:\
# "c:\Users\Default" is the example path
$filetofind = "EventLogs"
# Hostnames TXT Location
$hostnamestxt = "C:\Scripts\Powershell_Remote_File_Query\hosts.txt"
# Destination file for Online Machines
$onlinetxt = "C:\Scripts\Powershell_Remote_File_Query\Machines_with_file.txt"
# Destination file for Offline Machines
$offlinetxt = "C:\Scripts\Powershell_Remote_File_Query\Offline_Machines.txt"

##########################################################
# Begin Executing Script – Do Not Edit Below This Line
##########################################################
$computers = get-content "$hostnamestxt"

write-host "———————————————-"
write-host "Scanning hostnames from $hostnamestxt…"
write-host "———————————————-"

foreach($computer in $computers)
{
ping -n 1 $computer >$null
if($lastexitcode -eq 0)
{
if(test-path "\\$computer\c$\$filetofind")
{
echo "$computer" | Out-File -Append "$onlinetxt"
write-host "File FOUND on $computer"
}
else
{write-host "File NOT found on $computer"}
}
else
{
echo "$computer" | Out-File -Append "$offlinetxt"
write-host "$computer is OFFLINE/DID NOT RESPOND TO PING"
}
}
write-host "———————————————-"
write-host "Script has completed please check output."
write-host "Hosts with file output location – $onlinetxt"
write-host "Hosts that were unpingable output location – $offlinetxt"
write-host "———————————————-"

I get this error when running the script:
get-content : Cannot find path 'C:\Scripts\Powershell_Remote_File_Query\"€' because it does not exist.
At C:\Scripts\Powershell_Remote_File_Query\Powershell_Remote_File_Query_Script.ps1:24 char:18
+     $computers = get-content "$hostnamestxtâ€
+                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (C:\Scripts\Powe...ile_Query\"€:String) [Get-Content], ItemNotFoundEx
   ception
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand

Both the script itself and the txt file are in the same directory. Please forgive me I'm new to Powershell and not a programmer by any means.

A: Instead of doing this...
$hostnamestxt = "C:\Scripts\Powershell_Remote_File_Query\hosts.txt"
$computers = get-content "$hostnamestxt"

Try just doing this...
$computers = get-content "C:\Scripts\Powershell_Remote_File_Query\hosts.txt"

I understand what you are trying to do should result to the same thing, yet, let's just try to eliminate that extra thing, and give it a shot to see if you get a different result.
Also, if that file you are reading is on a remote host, then you should be using the UNC file share path, not your local C: drive. Just assuming a bit here.


text:
Q: Can someone tell me how to use basic set notation to say... A is a set of integers that are not divisible by 3 except the numbers 21, 24, 27, 30, 33, 36, and 39.
I'm working on some challenge problems that require set notation and I think I may have it but I could be wrong:
{A | A is in ℤ, 3∤ℤ, 21, 24, 27, 30, 33, 36, 39}
How does that look? Any help would be appreciated!

A: $$A=\{n\in\mathbb{Z}:(3\not|n)\vee(n\in\{21,24,27,30,33,36,39\})\}$$


text:
Q: Can I block my ID when making a FaceTime Call? Is there a way to initiate a FaceTime call but block my identity from the person I'm making the call to? Reason: my daughter has lost her privilege to use FaceTime, but I looked at her Apple account a few minutes ago and it said that her iPhone was using FaceTime at the moment. I want to find out if she is, in fact, breaking the rules. Thank you.

A: No, you can only set your Caller ID to one of the email addresses associated with your Apple ID, accessible through Settings → FaceTime.

A: If you mean that you would be connected to the call silently or that it would be recorded, you could try to find an app that does that… but remember, you have to get consent to record the calls or you can fined or imprisoned for invasion of privacy.
[description of invasion of privacy ]
(https://i.stack.imgur.com/VqFxY.jpg)


text:
Q: Will System.Random always generate predictable numbers for a given seed across platforms? I know that Object.GetHashCode can return different values for the same object (an identical string, for example) depending on the platform.  I thus can't rely on this for a cross-platform simple hash.
But can I rely on System.Random?  Will it produce the same results for a given seed regardless of whether or not I'm on Microsoft .NET / Mono / x86 / x64, etc.?

A: No, you can not rely on consistent values being generated across platforms or versions. From the .NET Framework docs for System.Random (the less-detailed .NET Core docs don't address this):

The implementation of the random number generator in the Random class isn't guaranteed to remain the same across major versions of the .NET Framework. As a result, you shouldn't assume that the same seed will result in the same pseudo-random sequence in different versions of the .NET Framework.

A: As Jeremy mentioned in his answer the documentation states that the number generator is not guaranteed consistent across .NET versions.
However, the documentation also tells you how to implement your algorithm too.

You can implement your own random number generator by inheriting from the Random class and supplying your random number generation algorithm. To supply your own algorithm, you must override the Sample method, which implements the random number generation algorithm. You should also override the Next(), Next(Int32, Int32), and NextBytes methods to ensure that they call your overridden Sample method. You don't have to override the Next(Int32) and NextDouble methods.

Using that we can make our own random class that uses a known fixed algorithm you can use. For example, we could go to the .Net source and implement the current random algorithm, this would allow us to use the ConsistantRandom class and know for sure the algorithom won't change on us.
The following example is derived from the .NET Core 1.1.0 source.
using System;

namespace ConsoleApplication1
{
    public class ConsistantRandom: Random
    {
        private const int MBIG = Int32.MaxValue;
        private const int MSEED = 161803398;
        private const int MZ = 0;

        private int inext;
        private int inextp;
        private int[] SeedArray = new int[56];

        public ConsistantRandom()
            : this(Environment.TickCount)
        {
        }

        public ConsistantRandom(int seed)
        {
            int ii;
            int mj, mk;

            int subtraction = (seed == Int32.MinValue) ? Int32.MaxValue : Math.Abs(seed);
            mj = MSEED - subtraction;
            SeedArray[55] = mj;
            mk = 1;
            for (int i = 1; i < 55; i++)
            {
                ii = (21 * i) % 55;
                SeedArray[ii] = mk;
                mk = mj - mk;
                if (mk < 0) mk += MBIG;
                mj = SeedArray[ii];
            }
            for (int k = 1; k < 5; k++)
            {
                for (int i = 1; i < 56; i++)
                {
                    SeedArray[i] -= SeedArray[1 + (i + 30) % 55];
                    if (SeedArray[i] < 0) SeedArray[i] += MBIG;
                }
            }
            inext = 0;
            inextp = 21;
        }
        protected override double Sample()
        {
            return (InternalSample() * (1.0 / MBIG));
        }

        private int InternalSample()
        {
            int retVal;
            int locINext = inext;
            int locINextp = inextp;

            if (++locINext >= 56) locINext = 1;
            if (++locINextp >= 56) locINextp = 1;

            retVal = SeedArray[locINext] - SeedArray[locINextp];

            if (retVal == MBIG) retVal--;
            if (retVal < 0) retVal += MBIG;

            SeedArray[locINext] = retVal;

            inext = locINext;
            inextp = locINextp;

            return retVal;
        }

        public override int Next()
        {
            return InternalSample();
        }

        private double GetSampleForLargeRange()
        {
            int result = InternalSample();
            bool negative = (InternalSample() % 2 == 0) ? true : false;
            if (negative)
            {
                result = -result;
            }
            double d = result;
            d += (Int32.MaxValue - 1);
            d /= 2 * (uint)Int32.MaxValue - 1;
            return d;
        }

        public override int Next(int minValue, int maxValue)
        {
            if (minValue > maxValue)
            {
                throw new ArgumentOutOfRangeException("minValue");
            }

            long range = (long)maxValue - minValue;
            if (range <= (long)Int32.MaxValue)
            {
                return ((int)(Sample() * range) + minValue);
            }
            else
            {
                return (int)((long)(GetSampleForLargeRange() * range) + minValue);
            }
        }
        public override void NextBytes(byte[] buffer)
        {
            if (buffer == null) throw new ArgumentNullException("buffer");
            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = (byte)(InternalSample() % (Byte.MaxValue + 1));
            }
        }
    }

}

Because ConsistantRandom derives from Random you can use the class as a drop in replacement anywhere you had the type Random before, you just need to replace Random rnd = new Random(yourSeed); with Random rnd = new ConsistantRandom(yourSeed);.


text:
Q: Best practice for ASP.NET MVC webshop search-engine with SQL Server database We developing a webshop with a SQL Server database in the background and have an internal discussion about the best way to integrate/create a search engine.
At the moment we discuss following approaches:

*

*SQL Server full-text search

*

*PRO: Fast!

*CON: often bad results, because of language problems (german) or technical
abbreviation,...

*Lucene.Net

*

*PRO: Fast, good results..

*CON: Outdated (last release 3.0.3 - Oct 10, 2012) ???

*Web caching (HttpRuntine.Cache) / Linq searching (was only an idea to cache all search data via hangfire framework and make a classic linq search)


text:
Q: Decode h264 video stream to get image buffer I followed this post to decode my h264 video stream frames.
My data frames as bellow:

My code:
NSString * const naluTypesStrings[] =
{
    @"0: Unspecified (non-VCL)",
    @"1: Coded slice of a non-IDR picture (VCL)",    // P frame
    @"2: Coded slice data partition A (VCL)",
    @"3: Coded slice data partition B (VCL)",
    @"4: Coded slice data partition C (VCL)",
    @"5: Coded slice of an IDR picture (VCL)",      // I frame
    @"6: Supplemental enhancement information (SEI) (non-VCL)",
    @"7: Sequence parameter set (non-VCL)",         // SPS parameter
    @"8: Picture parameter set (non-VCL)",          // PPS parameter
    @"9: Access unit delimiter (non-VCL)",
    @"10: End of sequence (non-VCL)",
    @"11: End of stream (non-VCL)",
    @"12: Filler data (non-VCL)",
    @"13: Sequence parameter set extension (non-VCL)",
    @"14: Prefix NAL unit (non-VCL)",
    @"15: Subset sequence parameter set (non-VCL)",
    @"16: Reserved (non-VCL)",
    @"17: Reserved (non-VCL)",
    @"18: Reserved (non-VCL)",
    @"19: Coded slice of an auxiliary coded picture without partitioning (non-VCL)",
    @"20: Coded slice extension (non-VCL)",
    @"21: Coded slice extension for depth view components (non-VCL)",
    @"22: Reserved (non-VCL)",
    @"23: Reserved (non-VCL)",
    @"24: STAP-A Single-time aggregation packet (non-VCL)",
    @"25: STAP-B Single-time aggregation packet (non-VCL)",
    @"26: MTAP16 Multi-time aggregation packet (non-VCL)",
    @"27: MTAP24 Multi-time aggregation packet (non-VCL)",
    @"28: FU-A Fragmentation unit (non-VCL)",
    @"29: FU-B Fragmentation unit (non-VCL)",
    @"30: Unspecified (non-VCL)",
    @"31: Unspecified (non-VCL)",
};

-(void) receivedRawVideoFrame:(uint8_t *)frame withSize:(uint32_t)frameSize isIFrame:(int)isIFrame
{
    // First NAUL is AUD so i skiped 6 frame
    frame = &frame[6];
    frameSize -= 6;
    OSStatus status;

    uint8_t *data = NULL;
    uint8_t *pps = NULL;
    uint8_t *sps = NULL;

    // I know what my H.264 data source's NALUs look like so I know start code index is always 0.
    // if you don't know where it starts, you can use a for loop similar to how i find the 2nd and 3rd start codes
    int startCodeIndex = 0;
    int secondStartCodeIndex = 0;
    int thirdStartCodeIndex = 0;
    int fourthStartCodeIndex = 0;
    long blockLength = 0;

    CMSampleBufferRef sampleBuffer = NULL;
    CMBlockBufferRef blockBuffer = NULL;

    int nalu_type = (frame[startCodeIndex + 4] & 0x1F);
    NSLog(@"~~~~~~~ Received NALU Type \"%@\" ~~~~~~~~", naluTypesStrings[nalu_type]);

    // if we havent already set up our format description with our SPS PPS parameters, we
    // can't process any frames except type 7 that has our parameters
    if (nalu_type != 7 && _formatDesc == NULL)
    {
        NSLog(@"Video error: Frame is not an I Frame and format description is null");
        return;
    }

    // NALU type 7 is the SPS parameter NALU
    if (nalu_type == 7)
    {
        // find where the second PPS start code begins, (the 0x00 00 00 01 code)
        // from which we also get the length of the first SPS code
        for (int i = startCodeIndex + 4; i < frameSize; i++)
        {
            if (frame[i] == 0x00 && frame[i+1] == 0x00 && frame[i+2] == 0x00 && frame[i+3] == 0x01)
            {
                secondStartCodeIndex = i;
                _spsSize = secondStartCodeIndex;   // includes the header in the size
                break;
            }
        }

        // find what the second NALU type is
        nalu_type = (frame[secondStartCodeIndex + 4] & 0x1F);
        NSLog(@"~~~~~~~ Received NALU Type \"%@\" ~~~~~~~~", naluTypesStrings[nalu_type]);
    }

    // type 8 is the PPS parameter NALU
    if(nalu_type == 8)
    {
        // find where the NALU after this one starts so we know how long the PPS parameter is
        for (int i = secondStartCodeIndex + 4; i < frameSize; i++)
        {
            if (frame[i] == 0x00 && frame[i+1] == 0x00 && frame[i+2] == 0x01)
            {
                thirdStartCodeIndex = i;
                _ppsSize = thirdStartCodeIndex - _spsSize;
                break;
            }
        }
//        _ppsSize = frameSize - -_spsSize;

        // allocate enough data to fit the SPS and PPS parameters into our data objects.
        // VTD doesn't want you to include the start code header (4 bytes long) so we add the - 4 here
        sps =  malloc(_spsSize - 4);
        pps = malloc(_ppsSize - 4);

        // copy in the actual sps and pps values, again ignoring the 4 byte header
        memcpy (sps, &frame[4], _spsSize-4);
        memcpy (pps, &frame[_spsSize+4], _ppsSize-4);

        // now we set our H264 parameters
        uint8_t*  parameterSetPointers[2] = {sps, pps};
        size_t parameterSetSizes[2] = {(_spsSize-4), (_ppsSize-4)};

        status = CMVideoFormatDescriptionCreateFromH264ParameterSets(kCFAllocatorDefault, 2,
                                                                     (const uint8_t *const*)parameterSetPointers,
                                                                     parameterSetSizes, 4,
                                                                     &_formatDesc);

        NSLog(@"\t\t Creation of CMVideoFormatDescription: %@", (status == noErr) ? @"successful!" : @"failed...");
        if(status != noErr) NSLog(@"\t\t Format Description ERROR type: %d", (int)status);

        // See if decomp session can convert from previous format description
        // to the new one, if not we need to remake the decomp session.
        // This snippet was not necessary for my applications but it could be for yours
//        BOOL needNewDecompSession = (VTDecompressionSessionCanAcceptFormatDescription(_decompressionSession, _formatDesc) == NO);
//        if(needNewDecompSession)
//        {
//            [self createDecompSession];
//        }

        // now lets handle the IDR frame that (should) come after the parameter sets
        // I say "should" because that's how I expect my H264 stream to work, YMMV
        nalu_type = (frame[thirdStartCodeIndex + 3] & 0x1F);
        NSLog(@"~~~~~~~ Received NALU Type \"%@\" ~~~~~~~~", naluTypesStrings[nalu_type]);
    }

    // create our VTDecompressionSession.  This isnt neccessary if you choose to use AVSampleBufferDisplayLayer
    if((status == noErr) && (_decompressionSession == NULL))
    {
        [self createDecompSession];
    }

    if(nalu_type == 6)
    {
        for (int i = thirdStartCodeIndex + 3; i < frameSize; i++)
        {
            if (frame[i] == 0x00 && frame[i+1] == 0x00 && frame[i+2] == 0x01)
            {
                fourthStartCodeIndex = i;
                _seiSize = fourthStartCodeIndex - (_spsSize + _ppsSize);
                break;
            }
        }

        // do stuff here
        // [...]
        nalu_type = (frame[fourthStartCodeIndex + 3] & 0x1F);
    }

    // type 5 is an IDR frame NALU.  The SPS and PPS NALUs should always be followed by an IDR (or IFrame) NALU, as far as I know
    if(nalu_type == 5)
    {
        // find the offset, or where the SPS and PPS NALUs end and the IDR frame NALU begins
        int offset = fourthStartCodeIndex;
        int fifthStartCodeIndex = 0;

        for (int i = fourthStartCodeIndex + 3; i < frameSize; i++)
        {
            if (frame[i] == 0x00 && frame[i+1] == 0x00 && frame[i+2] == 0x01)
            {
                fifthStartCodeIndex = i;
                break;
            }
        }

        blockLength = fifthStartCodeIndex - offset;
        data = malloc(blockLength);
        data = memcpy(data, &frame[offset], blockLength);

        // replace the start code header on this NALU with its size.
        // AVCC format requires that you do this.
        // htonl converts the unsigned int from host to network byte order
        uint32_t dataLength32 = htonl (blockLength - 3);
        memcpy (data, &dataLength32, sizeof (uint32_t));

        // create a block buffer from the IDR NALU
        status = CMBlockBufferCreateWithMemoryBlock(NULL, data,  // memoryBlock to hold buffered data
                                                    blockLength,  // block length of the mem block in bytes.
                                                    kCFAllocatorNull, NULL,
                                                    0, // offsetToData
                                                    blockLength,   // dataLength of relevant bytes, starting at offsetToData
                                                    0, &blockBuffer);

        NSLog(@"\t\t BlockBufferCreation: \t %@", (status == kCMBlockBufferNoErr) ? @"successful!" : @"failed...");

        blockLength = frameSize - fifthStartCodeIndex;
        data = malloc(blockLength);
        data = memcpy(data, &frame[offset], blockLength);
        // replace the start code header on this NALU with its size.
        // AVCC format requires that you do this.
        // htonl converts the unsigned int from host to network byte order
        uint32_t dataLength32_1 = htonl (blockLength - 3);
        memcpy (data, &dataLength32_1, sizeof (uint32_t));

        status = CMBlockBufferAppendMemoryBlock(blockBuffer,
                                       data,
                                       blockLength,
                                       kCFAllocatorNull,
                                       NULL,
                                       0,
                                       blockLength,
                                       0);
        NSLog(@"\t\t BlockBufferAppend: \t %@", (status == kCMBlockBufferNoErr) ? @"successful!" : @"failed...");

    }

    // NALU type 1 is non-IDR (or PFrame) picture
    if (nalu_type == 1)
    {
        // non-IDR frames do not have an offset due to SPS and PSS, so the approach
        // is similar to the IDR frames just without the offset
        blockLength = frameSize;
        data = malloc(blockLength);
        data = memcpy(data, &frame[0], blockLength);

        // again, replace the start header with the size of the NALU
        uint32_t dataLength32 = htonl (blockLength - 4);
        memcpy (data, &dataLength32, sizeof (uint32_t));

        status = CMBlockBufferCreateWithMemoryBlock(NULL, data,  // memoryBlock to hold data. If NULL, block will be alloc when needed
                                                    blockLength,  // overall length of the mem block in bytes
                                                    kCFAllocatorNull, NULL,
                                                    0,     // offsetToData
                                                    blockLength,  // dataLength of relevant data bytes, starting at offsetToData
                                                    0, &blockBuffer);

        NSLog(@"\t\t BlockBufferCreation: \t %@", (status == kCMBlockBufferNoErr) ? @"successful!" : @"failed...");
    }

    // now create our sample buffer from the block buffer,
    if(status == noErr)
    {
        // here I'm not bothering with any timing specifics since in my case we displayed all frames immediately
        const size_t sampleSize = blockLength;
        sampleBuffer = NULL;
        status = CMSampleBufferCreate(kCFAllocatorDefault,
                                      blockBuffer, true, NULL, NULL,
                                      _formatDesc, 1, 0, NULL, 1,
                                      &sampleSize, &sampleBuffer);

        NSLog(@"\t\t SampleBufferCreate: \t %@", (status == noErr) ? @"successful!" : @"failed...");
    }

    if(status == noErr)
    {
        // set some values of the sample buffer's attachments
        CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, YES);
        CFMutableDictionaryRef dict = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(attachments, 0);
        CFDictionarySetValue(dict, kCMSampleAttachmentKey_DisplayImmediately, kCFBooleanTrue);

        // either send the samplebuffer to a VTDecompressionSession or to an AVSampleBufferDisplayLayer
        [self render:sampleBuffer];
    }

    // free memory to avoid a memory leak, do the same for sps, pps and blockbuffer
    if (NULL != data)
    {
        free (data);
        data = NULL;
    }
}

-(void) createDecompSession
{
    // make sure to destroy the old VTD session
    _decompressionSession = NULL;
    VTDecompressionOutputCallbackRecord callBackRecord;
    callBackRecord.decompressionOutputCallback = decompressionSessionDecodeFrameCallback;

    // this is necessary if you need to make calls to Objective C "self" from within in the callback method.
    callBackRecord.decompressionOutputRefCon = (__bridge void *)self;

    // you can set some desired attributes for the destination pixel buffer.  I didn't use this but you may
    // if you need to set some attributes, be sure to uncomment the dictionary in VTDecompressionSessionCreate
    NSDictionary *destinationImageBufferAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                                      [NSNumber numberWithBool:YES],
                                                      (id)kCVPixelBufferOpenGLESCompatibilityKey,
                                                      nil];

    OSStatus status =  VTDecompressionSessionCreate(NULL, _formatDesc, NULL,
                                                     (__bridge CFDictionaryRef)(destinationImageBufferAttributes),
                                                    &callBackRecord, &_decompressionSession);
    NSLog(@"Video Decompression Session Create: \t %@", (status == noErr) ? @"successful!" : @"failed...");
    if(status != noErr) NSLog(@"\t\t VTD ERROR type: %d", (int)status);
}

void decompressionSessionDecodeFrameCallback(void *decompressionOutputRefCon,
                                             void *sourceFrameRefCon,
                                             OSStatus status,
                                             VTDecodeInfoFlags infoFlags,
                                             CVImageBufferRef imageBuffer,
                                             CMTime presentationTimeStamp,
                                             CMTime presentationDuration)
{
    //    THISCLASSNAME *streamManager = (__bridge THISCLASSNAME *)decompressionOutputRefCon;

    if (status != noErr)
    {
        NSError *error = [NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil];
        NSLog(@"Decompressed error: %@", error);
    }
    else
    {
        NSLog(@"Decompressed sucessfully");

        // do something with your resulting CVImageBufferRef that is your decompressed frame
        //        [streamManager displayDecodedFrame:imageBuffer];
    }
}

- (void) render:(CMSampleBufferRef)sampleBuffer
{
    VTDecodeFrameFlags flags = kVTDecodeFrame_1xRealTimePlayback;
    VTDecodeInfoFlags flagOut;
    NSDate* currentTime = [NSDate date];
    VTDecompressionSessionDecodeFrame(_decompressionSession, sampleBuffer, flags,
                                      (void*)CFBridgingRetain(currentTime), &flagOut);

    CFRelease(sampleBuffer);

    // if you're using AVSampleBufferDisplayLayer, you only need to use this line of code
    // [videoLayer enqueueSampleBuffer:sampleBuffer];
}

@end

Output:
[2110:825268] ~~~~~~~ Received NALU Type "7: Sequence parameter set (non-VCL)" ~~~~~~~~

[2110:825268] ~~~~~~~ Received NALU Type "8: Picture parameter set (non-VCL)" ~~~~~~~~

[2110:825268]   Creation of CMVideoFormatDescription: successful!

[2110:825268] ~~~~~~~ Received NALU Type "6: Supplemental enhancement information (SEI) (non-VCL)" ~~~~~~~~

[2110:825268]   BlockBufferCreation:    successful!

[2110:825268]   BlockBufferAppend:  successful!

[2110:825268]   SampleBufferCreate:     successful!

[2110:825277] Decompressed error: Error Domain=NSOSStatusErrorDomain Code=-12909 "(null)"

Please point me out what i missed.


text:
Q: Google Script onEdit(e) function and row range I have stumbled upon two problems after asking for help on this community and getting a quick and on point answer by a member of this community ( Tedinoz ).
So getting to the problems, I'm trying to make a spreadsheet where rows are based on the number in a column called quantity (basically quantity-1) if a checkbox is marked.
First problem: How do I write my code in order for my function to go dynamically to all rows inserted in the spreadsheet? I get an error when I try to set var row = sheet.getDataRange();
Second problem: When using the function onEdit(e) is there a workaround so that the function doesn't add infinite rows when the checkbox is marked? I'm searching for something that adds rows based on quantity when the checkbox is True or subtracts the rows when the checkbox is False (if they where initially added for that row).
Also is there an way to copy the text of column C or a range of text (through columns when inserting rows)?

Below is what I have so far:
function onEdit(e) {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheetname = "Test";
  var sheet = ss.getSheetByName(sheetname);
  var row = sheet.getDataRange;

  // get value of Column H
  var colHValue = sheet.getRange(row,8).getValue()

  if (colHValue = true){
    //Logger.log("DEBUG: Col H = True. do something")

    // get value of Column D
    var Value = sheet.getRange(row,4).getValue();

    // get the quantity and convert from a string to a number
    var qty = Value;
    var qtynum = +qty;
    // var newtype = typeof qtynum; // DEBUG
    //Logger.log("DEBUG: the quantity is "+qtynum+", new type = "+newtype)

    // This inserts rows after
    sheet.insertRowsAfter(row, qtynum-1);
  }
  else{
    //Logger.log("DEBUG: col H <> True. do nothing");
  }
}

A: function onEdit(e) {
  var sh=e.range.getSheet();
  if(sh.getName()!="Test")return;
  var colHValue=sh.getRange(e.range.rowStart,8).getValue()
  if (colHValue==true){
    sh.insertRowsAfter(e.range.rowStart, Number(sh.getRange(e.range.rowStart,4).getValue())-1);
  }
}

A:
function autoDup() {
      var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var data = sheet.getDataRange().getValues();
     var newData = [];
     for(var n in data){
       newData.push(data[n]);
    if(!Number(data[n][3])){continue};// if column 3 is not a number then do nothing
      for(var c=1 ; c < Number(data[n][3]) ; c++){ // start from 1 instead of 0 because we have already 1 copy
      newData.push(data[n]);//store values
    }
  }
  sheet.getRange(1,1,newData.length,newData[0].length).setValues(newData).sort({column: 1, ascending: false});// write new data to sheet, overwriting old data
}


text:
Q: Can't delete Windows folder that contains a subfolder named "..." which contains a subfolder named "..." etc I'm stumped.
I have a folder called c:/data/ToDelete.  It used to contain files as well as a single subfolder called ..., which contained the same files as well as single subfolder named ... and this went on ad nauseum.
I moved the contents of the ToDelete folder elsewhere, but the subfolder/subfolder structure remains, and I can't get rid of it.
This is what it looks like in Explorer
This PC > Data > ToDelete > ... > ... > ... > ... > etc
clicking on the above reveals the path: C:\Data\ToDelete\
I was able to rename the first folder (from c:/data/temp/ to c:/data/ToDelete/) but whenever I try to rename the subfolder I get the "This folder is already open" (probably because it is just referring back to it's parent folder).
Things I've tried (none worked)

*

*the basics: Delete key, Shift Delete, drag to recycle bin, send to recycle bin

*command prompt delete, including trying the ASCII code for . just in case.

*I tried zipping it with 7zip

*I did a chkdsk and got no errors

*I tried removing with Revo Uninstaller Pro (the Delete folder option).

*I tried renaming the subfolders with this powershell script that I found online thinking I could then delete them but got an error:

    Get-ChildItem -Recurse | where {$_.attributes -eq "Directory"} | Where-Object {$_.Name -match '...'} | Rename-Item -NewName { $_.Name -replace '...' , 'ToDelete' }

The funny thing is I found the folder in my backup directory as well, so somehow the entire thing can get copied (which means I have to remove it in multiple places now).

A: You need to do two things to enable PowerShell to process files or folders literally named ...:

*

*Use -LiteralPath instead of -Path parameter where possible, to prevent PowerShell from parsing the path.

*Prepend \\?\ to the full path to tell the underlying Windows APIs to disable all string parsing and to send the string that follows it straight to the file system.

Example:
# For demonstration, create two nested sub folders literally named '...'
New-Item -ItemType Directory -Path '\\?\c:\data\ToDelete\...\...'

# Rename all '...' sub folders to 'ToDelete'
Get-ChildItem -LiteralPath '\\?\c:\data\ToDelete' -Directory -Recurse -Filter '...' |
    Sort-Object { $_.Fullname.Length } -Desc |
    Rename-Item -NewName ToDelete

*

*Before renaming the folders, we must sort by path length (descending) to make sure that deepest nested folders will be renamed first. Otherwise paths enumerated by Get-ChildItem would be incorrect after renaming the first folder.

For what you have tried:

*

*Note that -match '...' doesn't find folders named literally like "...". The -match operator's RHS operand is a regular expression pattern and as such would match the first sequence of any three characters in the string. The same can be said about -replace '...'. To literally match "...", use -eq '...' or escape the dots like this when used in RegEx pattern: \.\.\.


text:
Q: How to add a text in every line with an existing texts using regex in Notepad++? Is it possible to add a text or HTML tags after each line with an existing text in Notepad++?
For example, this text:

[COMPANY]

                    Alexander Hamilton (Alexander Hamilton)
                    We are waiting in the wings for you (waiting in the wings for you)
                    You could never back down
                    You never learned to take your time!
                    Oh, Alexander Hamilton (Alexander Hamilton)
                    When America sings for you
                    Will they know what you overcame?
                    Will they know you rewrote the game?
                    The world will never be the same, oh

[BURR, MEN, & COMPANY]

                    The ship is in the harbor now
                    See if you can spot him
                    Just you wait
                    Another immigrant
                    Comin' up from the bottom
                    Just you wait
                    His enemies destroyed his rep
                    America forgot him

The goal is to make the text above be like this: (adding the break tags)

[COMPANY]

                    Alexander Hamilton (Alexander Hamilton)

                    We are waiting in the wings for you (waiting in the wings for you)

                    You could never back down

                    You never learned to take your time!

                    Oh, Alexander Hamilton (Alexander Hamilton)

                    When America sings for you

                    Will they know what you overcame?

                    Will they know you rewrote the game?

                    The world will never be the same, oh

[BURR, MEN, & COMPANY]

                    The ship is in the harbor now

                    See if you can spot him

                    Just you wait

                    Another immigrant

                    Comin' up from the bottom

                    Just you wait

                    His enemies destroyed his rep

                    America forgot him

I was using

 earlier, but noticed a horizontal scroll has appeared after text wrapping and cannot make it disappear, therefore, I'm discarding it and will opt to use
 tags.
The problem I have is there's no "common denominator" for each line that I can use to add the
 tags. Therefore, I'm hoping there could be a regex trick to do this, like detecting an empty space after each line?
It doesn't have to be done in one go, I'm just hoping there is a quicker way to this.
A side question: Is there a a way to add an id or class to each line of these plain texts without adding  or
 tags?
Lots of thanks in advance!

A: Use
$(?<=.)(?<!>)

Replace with
.
See proof. $(?<=.)(?<!>) will match any end-of-line position that has a character other than line break characters before it and no > character afer.


text:
Q: Integral in math messes up copy-and-paste of text For a document like
\documentclass{article}

\usepackage[T1]{fontenc}

\input glyphtounicode.tex
\input glyphtounicode-cmr.tex
\pdfgentounicode=1

\pagestyle{empty} % for quick CTRL+A
\begin{document}
  Some text and then $x$.

  Some text and then $\int_0^1 x$.
\end{document}

Trying to copy-paste yields
Some text and then x.
Some text and then ∫ 1
0
x.

Now, I guess the interval isn't really properly expressible in plain text (unless it can be done through some funky Unicode composition), but I would not expect the result to be that bad – maybe ∫0 1 x? Is there something I can do for better results?

A: Run it with lualatex:
\documentclass{article}
\usepackage{unicode-math}
\setmathfont{XITS Math}
\pagestyle{empty}
\begin{document}
    Some text and then $x$.

    Some text and then $∫_0^1 x$.
\end{document}


text:
Q: How parse a list of dictionary and out the values in Ansible? I've the following json output. It is a list of dictionary. I just want to parse it and output its value.
I've tried the following play but without success...
"output1": {
    "changed": false,
    "msg": "All items completed",
    "results": [
        {
            "item": [
                {
                    "Device_Name": "SW1"
                },
                {
                    "Interface": "GigabitEthernet1/0/7"
                }
                    ]
         }
    ]
}

    - name: Display output1...2
      debug:
        msg: "{{ item.1.Device_Name }};{{ item.1.Interface }}"
      with_subelements:
        - "{{ output1.results }}"
        - item

The error was ""msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'int_name'\n\n"

A: Try below - I have not tested it though.
    - name: Display output1...2
      debug:
        msg: "{{ item|first }} : {{ item[item|first] }}"
      with_items:
        - "{{ output1.results[0].item }}"

A: Quick and dirty
The tasks below give quickly what is requested
- set_fact:
    Device_Name: "{{ output1.results[0]['item']|
                     map(attribute='Device_Name')|
                     select('defined')|
                     list|first }}"
    Interface: "{{   output1.results[0]['item']|
                     map(attribute='Interface')|
                     select('defined')|
                     list|first }}"

Details
This is a typical example of bad data structure. The task below
- debug:
    msg: "{{ output1.results|
             map('dict2items')|list|flatten|
             json_query('[?key==`item`].value')|flatten }}"

gives item, which is a list and must be iterated again,
"msg": [
        {
            "Device_Name": "SW1"
        },
        {
            "Interface": "GigabitEthernet1/0/7"
        }
]

instead of a dictionary, which could be easily referenced.
"msg": [
        {
            "Device_Name": "SW1",
            "Interface": "GigabitEthernet1/0/7"
        }
]

As a result of such filtering the tasks below
- set_fact:
    Device_Name: "{{ output1.results|
                     map('dict2items')|list|flatten|
                     json_query('[?key==`item`].value')|flatten|
                     map('dict2items')|list|
                     json_query('[*][?key==`Device_Name`].value')|flatten }}"
- set_fact:
    Interface: "{{ output1.results|
                   map('dict2items')|list|flatten|
                   json_query('[?key==`item`].value')|flatten|
                   map('dict2items')|list|
                   json_query('[*][?key==`Interface`].value')|flatten }}"
- debug:
    var: Device_Name
- debug:
    var: Interface

give
"Device_Name": [
    "SW1"
]

"Interface": [
    "GigabitEthernet1/0/7"
]


text:
Q: Eclipse referring old class files of Maven. Have to re-build the project everytime I make a single change I am using Maven projects in my Eclipse workspace.
But, somehow Eclipse is referring the old .class files while running the program.
Hence, I have to re-build the complete project everytime I make any change to any java program.
I have tried executing maven commands like eclipse:clean & eclipse:eclipse.
But, they did not help.
My eclipse is also set to project - build automatically.
Is there a way I can tell Eclipse to refer to the current built .class files and not the previously built maven .class files.
Note: I am using Eclipse Mars
Thanks in advance.

A: I am afraid. There is no way to doing it automatically. Even if you find a way to do so. There isn't any guarantee that eclipse will build with new war.
Either you go for manual mvn clean install or use intellij idea it is very much statble. No build issue. Every time on your single save it will build new war file.

A: Posting answer to my question:
Sometimes the .project file of Eclipse gets corrupted. Easy solution is :

*

*Delete the project from Eclipse.

*Close Eclipse.

*Go to your project's folder and delete ".settings, .project, .classpath, bin"

*Open Eclipse again, and import your project once again.

This way it always works.


text:
Q: Windows 7 laptop freezes for half a second every minute or so I have a Dell Inspiron 14z latop, with an i5-2450M CPU (running at 2.5Ghz), 8 Gb of memory, and a Kingston SVP200S3 solid-state drive (120 Gb). I'm running Windows 7 Ultimate, 64bit on it.
My problems started a few days ago, out of the blue. I first noticed it while watching Youtube videos - the video and sound would freeze for half a second to a second (audio still on, but corrupted), and this would happen every minute or so. I attributed it to an error with Adobe Flash player. The problem is, when I played a movie later on using VLC player, the same thing would happen.
Finally, I noticed that even if I have all programs closed, and just move the mouse in circles on the desktop, the same thing would happen - mouse freezes for half a second, then it works again.
I rand Dell SupportAssist stress tests on the CPU and RAM, and nothing comes out of it. I still haven't run the SSD test, as it might take a few hours.
Any suggestions as to what might be causing this? What other software could I use to diagnose the problem?
Thanks!

A: After using MooO System Monitor (and it took a little bit of paying attention what's happening), it turned out two services were the culprits: DellDataVault.exe and DellDataVaultWiz.exe, both of which I disabled using msconfig.
Unfortunately, I'm still not sure why they were causing the issues, not why they started causing them suddenly - I didn't install them myself recently.


text:
Q: Bean Spec and apache-commons-beanutils (capitalization of getter) We have a Bean with a field called:
private String aBcde = ... ;

the getter was written:
public String getABcde() {
    return aBcde;
}

but
http://javasourcecode.org/html/open-source/commons-beanutils/commons-beanutils-1.8.0/org/apache/commons/beanutils/PropertyUtilsBean.java.html
reports a "NoSuchMethodError"
Question: Is the name of the getter wrong, or is this a bug in BeanUtils?
Pls Note that this works fine:
public String getaBcde() {
  ...
}

A: According to http://blog.950buy.com/article/javabean-specification-on-a-few-you-should-know/ it seems my expectiation was wrong and
public String getaBcde() {
  ...
}

is correct.
Actually, the Bean Spec says:
"However to support the occasional use of all upper-case names, we check if the first two characters of the name are both upper case and if so leave it alone. So for example:

*

*"FooBah" becomes "fooBah"

*"Z" becomes "z"

*"URL" becomes "URL""

So in my case I had getter "getABcde" which maps to property "ABcde", cf. the URL example.


text:
Q: Automatically add links to strings of keywords In my article, I want to automatically add links to keywords.
My keywords array:
 $keywords = [
       0=>['id'=>1,'slug'=>'getName','url'=>'https://example.com/1'],
       1=>['id'=>2,'slug'=>'testName','url'=>'https://example.com/2'],
       2=>['id'=>3,'slug'=>'ign','url'=>'https://example.com/3'],
    ];

This is my code:
private function keywords_replace(string $string, array $key_array)
{
    $array_first = $key_array;
    $array_last = [];
    foreach ($array_first as $key=>$value)
    {
        $array_last[$key] = [$key, $value['slug'], '' . $value['slug'] . ''];
    }
    $count = count($array_last);
    for ($i=0; $i<$count;$i++)
    {
        for ($j=$count-1;$j>$i;$j--)
        {
            if (strlen($array_last[$j][1]) > strlen($array_last[$j-1][1]))
            {
                $tmp = $array_last[$j];
                $array_last[$j] = $array_last[$j-1];
                $array_last[$j-1] = $tmp;
            }
        }
    }
    $keys = $array_last;
    foreach ($keys as $key)
    {
        $string = str_ireplace($key[1],$key[0],$string);
    }
    foreach ($keys as $key)
    {
        $string = str_ireplace($key[0],$key[2],$string);
    }
    return $string;
}

result:
 $str = "
Just a test: getName  testName";
 echo $this->keywords_replace($str,$keywords);

like this:Just a test: getName testName
very import: If the string has no spaces, it will not match.Because I will use other languages, sentences will not have spaces like English. Like Wordpress key words auto link
I think my code is not perfect,Is there a better algorithm to implement this function? Thanks!

A: First you need to change structure of array to key/value using loop that result stored in $newKeywords. Then using preg_replace_callback() select every word in string and check that it exist in key of array. If exist, wrap it in anchor tag.
$newKeywords = [];
foreach ($keywords as $keyword)
    $newKeywords[$keyword['slug']] = $keyword['url'];

$newStr = preg_replace_callback("/(\w+)/", function($m) use($newKeywords){
    return isset($newKeywords[$m[0]]) ? "{$m[0]}" : $m[0];
}, $str);

Output:

Just a test: getName  testName

Check result in demo

A: You can use array_reduce and preg_replace to replace all occurrences of the slug words in your string with the corresponding url values:
$keywords = [
       0=>['id'=>1,'slug'=>'getName','url'=>'https://www.getname.com'],
       1=>['id'=>2,'slug'=>'testName','url'=>'https://www.testname.com'],
       2=>['id'=>3,'slug'=>'ign','url'=>'https://www.ign.com'],
    ];
$str = "
Just a test: getName  testName";
echo array_reduce($keywords, function ($c, $v) { return preg_replace('/\\b(' . $v['slug'] . ')\\b/', $v['url'], $c); }, $str);

Output:

Just a test: https://www.getname.com https://www.testname.com

Demo on 3v4l.org
Update
To change the text into links, you need to use this:
echo array_reduce($keywords,
                  function ($c, $v) {
                     return preg_replace('/\\b(' . $v['slug'] . ')\\b/',
                                         '$1', $c);
                  },
                  $str);

Output:

Just a test: getName testName

Updated demo
Update 2
Because some of the links that are being substituted include words that are also values of slug, it's necessary to do all the replacements at once using the array format of strtr. We build an array of patterns and replacements using array_column, array_combine and array_map, then pass that to strtr:
$reps = array_combine(array_column($keywords, 'slug'),
                      array_map(function ($k) { return '' . $k['slug'] . ''; }, $keywords
                      ));
$newstr = strtr($str, $reps);

New demo

A: My answer uses preg_replace as does Nick's above.
It relies on the patterns and replacements being equally sized arrays, with corresponding patterns and replacements.
Word boundaries need to be respected, which I doubt you can do with a simple string replacement.
<?php
$keywords = [
    0=>['id'=>1,'slug'=>'foo','url'=>'https://www.example.com/foo'],
    1=>['id'=>2,'slug'=>'bar','url'=>'https://www.example.com/bar'],
    2=>['id'=>3,'slug'=>'baz','url'=>'https://www.example.com/baz'],
];

foreach ($keywords as $item)
{
    $patterns[]     = '@\b(' . $item['slug'] . ')\b@i';
    $replacements[] = '$1';
}

$html = "
I once knew a barbed man named Foo, he often visited the bar.
";

print preg_replace($patterns, $replacements, $html);

Output:

I once knew a barbed man named Foo, he often visited the bar.

A: This is my answer: thanks for @Nick
$content = array_reduce($keywords , function ($c, $v) {
    return preg_replace('/(>[^<>]*?)(' . $v['slug'] . ')([^<>]*?<)/', '$1$2$3', $c);
}, $str);


text:
Q: Change the SuperUser Advertising Info link to point to a Super User page I recently followed the advertising info link from SuperUser (in the page footer), it takes you to the same page as for StackOverflow. This page states it is possible to sponsor specific tags, which is only possible on StackOverflow (established over an email exchange with the nice people at Inedo Media).
I suggest to avoid confusion it would make sense to have a separate page for each site, if only because following an advertising link from SuperUser (or ServerFault) shouldn't take you to a StackOverflow-branded page.

A: Good idea, we'll follow up on this!


text:
Q: Nine people in an elevator Assume there are nine people who enter a nine-floor building. Each person can exit on each floor with the same probability. What is the probability that the elevator stops on each floor if:

*

*the building has basement

*the building does not have basement

My aproach.
(A) Building has basement
In this case the setting seems to be simple. Let's denote with $f_i$ the floor chosen by $i^\text{th}$ person. Then we could consider all possible values of tuple $(f_1, f_2, ..., f_9)$ with $f_i \in \{1, ..., 9\}, i=\overline{1,9}$. There are $9^9$ possible values in total and $9!$ possible values where all $f_i$'s are different. Thus, the final probability is $$p=\frac{9!}{9^9}$$
(B) Building without basement
This case is much more difficult for me. Let's consider the same tuple $(f_1, f_2, ..., f_9)$ but with $f_i \in \{2, ..., 9\}, i=\overline{1,9}$. The number of possible values is $8^9$ now. Next, we need to count the number of possible values of the tuple such that it contains all numbers from $\{2, ..., 9\}$.
Eight of of nine people could pick 8 different floor in $8!$ ways while the last one could pick any of 8 floors. Thus the total number of interest is $8\cdot8!$. And final probability is $$p=\frac{8\cdot8!}{8^9}=\frac{8!}{8^8}$$ which contradicts intuitition since it is equal to the probability for the problem (A) but for 8 people. But adding extra person should have increased the probability.
Help much appreciated in validating part (A) and helping with solving part (B).

A: Case A and B are not clearly stated in the question. Assuming in a building with basement, all $9$ people enter at the basement and there are $9$ floors where they can exit, then your answer for case (A) is correct.
Case (B): If there is no basement, you seem to be  assuming everyone enters on the ground/first floor and there are $8$ floors where they can exit. In that case,
Exactly two people will exit on the same floor and one person each on remaining $7$ floors. So we choose the floor where we have two people exit and we choose two people who exit together and then remaining $7$ people exit on remaining $7$ floors in $7!$ ways. So the probability is,
$\displaystyle P = 8 \cdot {9 \choose 2} \cdot 7! \ / \ 8^9 = \frac{9!}{2! \cdot 8^8}$

A: Part (B) is analogous to an eight faced die thrown $9$ times, and the valid ways can be expressed as the product of two multinomial coefficients, viz $\binom{9}{2,1,1,1,1,1,1,1}\binom{8}{1,7} = \frac{9!}{2!}\frac{8!}{7!}$
You can now compute the probability


text:
Q: Getting started with Phonegap I don't understand why I'm not getting an alert.  There are no errors in the console, and I'm sure it is finding the PhoneGap.js file.
<!doctype html>
<html>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script src="/Matrix/PhoneGap/Inc/js/PhoneGap.js"></script>
<script>
function myDeviceReady() {
    alert('Ready!');
}

document.addEventListener("deviceready", myDeviceReady, false);
</script>
</body>
</html>

Edit: This is not working on my iPhone using either Safari or Google Chrome.

A: Try:
window.addEventListener( 'load', myDeviceReady );

Checking deviceready has many issues. I find it easier to poll for window.device (which only exists if Phonegap is initialized).

A: You can get it to run in a Ripple emulator (see this link) but make sure use cordova.js not phonegap.js.


text:
Q: Angularjs ui-router not reaching child controller I've got a config function:
function config($stateProvider,$locationProvider) {
$locationProvider.html5Mode(true);
$stateProvider
    .state('projectsWs.tasks', {
        url: "/tasks",
        views: {
            "mainView": {
                templateUrl: "/app/projects/templates/index.php"
            },
            "innerView": {
                templateUrl: "/app/projects/templates/tasks.php",
                controller: tasksCtrl,
                controllerAs:'tasks'
            }
        }
    })
    .state('projectsWs.tasks.detail', {
        url: "/:taskId",
        views: {
            "mainView@": {
                templateUrl: "/app/projects/templates/index.php"
            },
            "innerView@mainView": {
                templateUrl: "/app/projects/templates/tasks.php",
                controller: function($stateParams) {
                    console.log('innerViewCtrl', $stateParams);
                }
            }
        }
    });}

InnerView is inside mainView.
When I've got url like /projects-ws/tasks, tasksCtrl function works as expected. But when I've got url with an id, i.e. /projects-ws/tasks/32, I don't see any output, but I expect innerViewCtrl output, that's the problem I got. I think I've got a problem with absolute/relative views, but I've allready tried all combinations and it still don't work.
UPDATE:
So now I've got following state:
state('projectsWs.tasks.detail', {
        url: "/:taskId",
        views: {
            "mainView@": {
                templateUrl: "/app/projects/templates/index.php",
                controller: function($stateParams) {
                    console.log('mainViewctrl', $stateParams);
                }
            },
            "innerView": {
                templateUrl: "/app/projects/templates/tasks.php",
                controller: function($stateParams) {
                    console.log('innerViewctrl', $stateParams);
                }

            }
        }
    })

as Radim Köhler said. It outputs mainViewctrl Object {taskId: "32"}, but how can I reach $stateParams.taskId from innerView now?

A: Absolute naming with UI-Router works a bit differntly then you've used it
.state('projectsWs.tasks.detail', {
    url: "/:taskId",
    views: {
        "mainView@": {
            templateUrl: "/app/projects/templates/index.php"
        },
        // this won't work, because the part after @
        // must be state name
        "innerView@mainView": {

        // so we would need this to target root, index.html
        "innerView@": {

        // or this to target nested view inside of a parent
        "innerView": {

        // which is the same as this
        "innerView@projectsWs.tasks": {

Check the:
View Names - Relative vs. Absolute Names
small cite:

Behind the scenes, every view gets assigned an absolute name that follows a scheme of viewname@statename, where viewname is the name used in the view directive and state name is the state's absolute name, e.g. contact.item. You can also choose to write your view names in the absolute syntax.

I created a working example here, and the states are like this
$stateProvider
.state('projectsWs', {
  template: '

' +
   '

',
})
$stateProvider
.state('projectsWs.tasks', {
    url: "/tasks",
    views: {
        "mainView": {
            //templateUrl: "/app/projects/templates/index.php"
            template: "
main view tasks
",
        },
        "innerView": {
            //templateUrl: "/app/projects/templates/tasks.php",
            template: "
inner view tasks
",
        }
    }
})
.state('projectsWs.tasks.detail', {
    url: "/:taskId",
    views: {
        "mainView@projectsWs": {
            //templateUrl: "/app/projects/templates/index.php"
            template: "
main view task {{$stateParams | json }}
",
        },
        "innerView@projectsWs": {
            //templateUrl: "/app/projects/templates/tasks.php",
            template: "
inner view task {{$stateParams | json }}
",
        }
    }
});

What we can see is, that the grand parent projectsWs is injecting into index.html (root)
 some template, with two named anchors:
template: '

' +
          '

',

this are then used in list and detail states, with relative resp absolute names
Check it here in action


text:
Q: TestContext is null when running test from a Windows Form I have an issue related to running CodedUITests from a Windows Form. (it works in the CodedUITestProject with Test-Explorer).
This is my CodedUITest's structure :
 [CodedUITest]
    public class DBTest
    {
        #region Static Fields
        public static CSVReader csvReader;
        #endregion

        #region Fields
        public string logFileName;
        public string timer = String.Empty;
        public  TestRead testRead;
        public  UploadResults uploadResults;
        private DateTime testStart;
        #endregion

   [ClassInitialize]
    public static void MyTestInitialize(TestContext test)
    {

        csvReader = new CSVReader();
        csvReader.LoadTestValues("steam.csv");

    }

    [TestInitialize]
    public void testInit()
    {

        testStart = DateTime.Now;
    }

    [TestMethod(), TestCategory("Reflection"), TestCategory("DataDriven"), DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", @"|DataDirectory|\CSV's\steam.csv", "steam#csv", DataAccessMethod.Sequential), DeploymentItem(@"..\..\CSV's\steam.csv")]
    public void steamAccess()
    {
        testRead = new TestRead();
        SteamMap a = new SteamMap();

        testRead.Read(a, TestContext);

    }

    [TestCleanup]
    public void TestCleanup()
    {
        uploadResults = new UploadResults();
        //timer for each test ( in seconds )
        double diffSecs = (DateTime.Now - testStart).TotalSeconds;

        uploadResults.TestUpload(testRead.TestResults, csvReader.DataTable, diffSecs,TestContext);
    }

    public  TestContext TestContext
    {
        get
        {
            return testContextInstance;
        }
        set
        {
            testContextInstance = value;
        }
    }
    private   TestContext testContextInstance;
}

This runs perfectly from VS's Test Explorer, testContextInitialize variable gets initialized.
In the same Solution I've added a second project, a simple Windows Form application, added a reference to my DLL ( from References)  which runs the following code :
            Playback.Initialize();
            DBTest a = new DBTest();
            a.steamAccess();
            Playback.Cleanup();

NullReferenceException occurs, my testContex is null when I run my test from outside it's assembly.
I need some help in this matter, Thanks
Edit 1:
Test Class :
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows.Input;
using System.Windows.Forms;
using System.Drawing;
using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UITest.Extension;
using Keyboard = Microsoft.VisualStudio.TestTools.UITesting.Keyboard;
using System.Linq;
using System.Reflection;
using SimarpiDB.GLobal;
using SimarpiDB.UITestMaps.SteamMapClasses;
using SimarpiDB.Global;
using System.Data;
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("TestLauncher")]

namespace SimarpiDB
{

    [CodedUITest]
    public class.....

Edit 2:
Temporary workaround until I find the cause of this error :
From my Windows Form I launch a MSTest with few required parameters and most of the what-methods-to-run logic will come from my database. I already did this few months ago but I scraped it because it's an additional performance overhead to use a tool such as MsTest within a launcher such as mine.
For anyone interested, there's a file located within VS's installation directory, it's called VsDevCmd.bat, I load this .bat within a hidden-in-background cmd with few additional commands ( mstest, testcontainer, test). This works but as I said I have no other plausible ideas.
There may also be a lack of referenced libraries within my Form ? Maybe something, a .dll that initialized the testenvironment and the testContext variable.
I wrote this because there may be others seeking the same result.

A: To clarify on my comment: internal is default in C#, so declaring something as abstract is like declaring it as "internal abstract".
For InternalsVisibleTo, you must make the library project visible to the test project, not the other way around:
[assembly:InternalsVisibleTo("MyTestProject")]