Q: App crash while setting Box APi key I register by app on box.com and get API key and start using it in my xcode project,but app get crash while setting BoxAPI at line:
[Box setBoxAPIKey:@"insert_key_here"];.

The error:

-[NSURL initFileURLWithPath:]: nil string parameter

No idea how to solve this issue.

A: This is pretty simple. Follow these steps
1) Go to your target build setting
2) Click on Add Build Phase (at buttom right corner) and choose Add Run Script
3) In the Edit Text Box copy paste this script
#!/bin/bash

echo "Copy Box database schema into bundle"
cp -fr ./Box.framework/Resources/BoxCoreDataStore.momd "${BUILT_PRODUCTS_DIR}/${CONTENTS_FOLDER_PATH}/BoxCoreDataStore.momd"

After Doing this click on build and you are done.
Happy coding

A: If someone faces the same problem than here is the fix:
You need to add files in Box.framework/Resources/BoxCoreDataStore.momd folder to your application package.
Add "Copy Files" phase and specify Destination = Executables, Subpath = ./BoxCoreDataStore.momd then add all files from above mentioned folder.


Q: ros: how to track changes in agents movement I'm a noob in this matter so this question might be a bit dumb but I'm trying to launch a multi agent world file where each agent need to know wHo is closest to it.
What I have by now: multi agent system where each agent has a laser sensor and they all move randomly and change direction when they are close to an obstacle which can be another agent or a wall defined in the world file
I'm trying to find a way not just to realize when I hit an obstacle but also to know if it is a moving one and if so where is it moving and how fast.
Thanks guys for any suggestion


Q: How to make an auto-complete textbox in a winforms desktop application I have a list of words. The list contains about 100-200 text strings (it's names of metro stations actually).
I want to make an auto-complete textbox. For an example, user press 'N' letter, then an (ending of) appropriate option appear (only one option). The ending must be selected.
How to do that?
PS1: I guess, there is a textbox control with a Property something like this:
List<string> AppropriateOptions{/* ... */}

PS2: sorry for my english. If you didn't understand -> ask me and I will try to explain!

A: Use a ComboBox instead of a TextBox. The following example will autocomplete, matching any piece of the text, not just the starting letters.
This should be a complete form, just add your own data source, and data source column names. :-)
using System;
using System.Data;
using System.Windows.Forms;

public partial class frmTestAutocomplete : Form
{

    private DataTable maoCompleteList;
    private const string MC_DISPLAY_COL = "name";
    private const string MC_ID_COL = "id";

    public frmTestAutocomplete()
    {
        InitializeComponent();
    }

    private void frmTestAutocomplete_Load(object sender, EventArgs e)
    {

        maoCompleteList = GetDataTableFromDatabase();
        maoCompleteList.CaseSensitive = false; //turn off case sensitivity for searching

        testCombo.DisplayMember = MC_DISPLAY_COL;
        testCombo.ValueMember = MC_ID_COL;
        testCombo.DataSource = maoCompleteList;
        testCombo.SelectedIndexChanged += testCombo_SelectedIndexChanged;
        testCombo.KeyUp += testCombo_KeyUp;
    }

    private void testCombo_KeyUp(object sender, KeyEventArgs e)
    {
        //use keyUp event, as text changed traps too many other evengts.

        ComboBox oBox = (ComboBox)sender;
        string sBoxText = oBox.Text;

        DataRow[] oFilteredRows = maoCompleteList.Select(MC_DISPLAY_COL + " Like '%" + sBoxText + "%'");

        DataTable oFilteredDT = oFilteredRows.Length > 0
                                ? oFilteredRows.CopyToDataTable()
                                : maoCompleteList;

        //NOW THAT WE HAVE OUR FILTERED LIST, WE NEED TO RE-BIND IT WIHOUT CHANGING THE TEXT IN THE ComboBox.

        //1).UNREGISTER THE SELECTED EVENT BEFORE RE-BINDING, b/c IT TRIGGERS ON BIND.
        oBox.SelectedIndexChanged -= testCombo_SelectedIndexChanged; //don't select on typing.
        oBox.DataSource = oFilteredDT; //2).rebind to filtered list.
        oBox.SelectedIndexChanged += testCombo_SelectedIndexChanged;

        //3).show the user the new filtered list.
        oBox.DroppedDown = true; //this will overwrite the text in the ComboBox, so 4&5 put it back.

        //4).binding data source erases text, so now we need to put the user's text back,
        oBox.Text = sBoxText;
        oBox.SelectionStart = sBoxText.Length; //5). need to put the user's cursor back where it was.

    }

    private void testCombo_SelectedIndexChanged(object sender, EventArgs e)
    {

        ComboBox oBox = (ComboBox)sender;

        if (oBox.SelectedValue != null)
        {
            MessageBox.Show(string.Format(@"Item #{0} was selected.", oBox.SelectedValue));
        }
    }

}

//=====================================================================================================
//      code from frmTestAutocomplete.Designer.cs
//=====================================================================================================
partial class frmTestAutocomplete

{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private readonly System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.testCombo = new System.Windows.Forms.ComboBox();
        this.SuspendLayout();
        //
        // testCombo
        //
        this.testCombo.FormattingEnabled = true;
        this.testCombo.Location = new System.Drawing.Point(27, 51);
        this.testCombo.Name = "testCombo";
        this.testCombo.Size = new System.Drawing.Size(224, 21);
        this.testCombo.TabIndex = 0;
        //
        // frmTestAutocomplete
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(292, 273);
        this.Controls.Add(this.testCombo);
        this.Name = "frmTestAutocomplete";
        this.Text = "frmTestAutocomplete";
        this.Load += new System.EventHandler(this.frmTestAutocomplete_Load);
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.ComboBox testCombo;
}

A: Just in case @leniel's link goes down, here's some code that does the trick:
AutoCompleteStringCollection allowedTypes = new AutoCompleteStringCollection();
allowedTypes.AddRange(yourArrayOfSuggestions);
txtType.AutoCompleteCustomSource = allowedTypes;
txtType.AutoCompleteMode = AutoCompleteMode.Suggest;
txtType.AutoCompleteSource = AutoCompleteSource.CustomSource;

A: The answer link by Leniel was in vb.net, thanks Joel for your entry. Supplying my code to make it more explicit:
private void InitializeTextBox()
{

    AutoCompleteStringCollection allowedStatorTypes = new AutoCompleteStringCollection();
    var allstatortypes = StatorTypeDAL.LoadList<List<StatorType>>().OrderBy(x => x.Name).Select(x => x.Name).Distinct().ToList();

    if (allstatortypes != null && allstatortypes.Count > 0)
    {
        foreach (string item in allstatortypes)
        {
            allowedStatorTypes.Add(item);
        }
    }

    txtStatorTypes.AutoCompleteMode = AutoCompleteMode.Suggest;
    txtStatorTypes.AutoCompleteSource = AutoCompleteSource.CustomSource;
    txtStatorTypes.AutoCompleteCustomSource = allowedStatorTypes;
}

A: Use combo box, sets its datasource or give hard coded entries but set the following properties:
    AutoCompleteMode = Suggest;
    AutoCompleteSource = ListItems;

A: You want to set the TextBox.AutoCompleteSource to CustomSource and then add all of your strings to its AutoCompleteCustomSource property, which is a StringCollection. Then you should be good to go.

A: I want to add that the standard autocomplete for TextBox does only work from the beginning of your strings, so if you hit N only strings starting with N will be found. If you want to have something better, you have to use some different control or implement the behavior for yourself (i.e. react on TextChanged Event with some timer to delay execution, than filter your tokenlist searching with IndexOf(inputString) and then set your AutoCompleteSource to the filtered list.


Q: Developer Studio BPEL project doesn't recognize analytics extension Using wso2bps-3.5.1, wso2das-3.0.1 and Developer Studio 3.8.0
I'm following a guideline for Monitoring a BPEL Process with WSO2 DAS. I recieve this from inside Developer Studio and my .bpel file:
Error: Extension "http://wso2.org/bps/monitoring/publisher" is not supported by this implementation.
<bpel:extensions>
    <bpel:extension namespace="http://wso2.org/bps/monitoring/publisher" mustUnderstand="yes"/>
</bpel:extensions>

A: WSO2 Developer Studio uses Eclipse bpel plugin to add support for bpel creation for WSO2 BPS. This BAM publishing bpel extension activity that you are referring to, is a custom extension developed by WSO2 and default bpel editor is not aware of this extension. This is why it gives syntax errors when you add this extension activity from the source view.
However, you should be able to export and deploy the CAR file without any issues regardless of the syntax errors.
According to this, there's a possibility to add support for custom extension activities in bpel editor.
Hence, I have raised a jira in WSO2 BPS Tooling jira for this feature.
Thanks.


Q: Can I build easily a static binary to be used inside fakeroot and how? fakeroot seems to build some  libfakeroot.a (but inside  a .lib directory).
But I am not sure, that the static linker can indeed replace/rename symbols  as the dynamic linker can.

A: Fakeroot uses the dynamic linker in order to do its magic (specifically, LD_PRELOAD). Unfortunately, the dynamic linker is not involved in loading statically linked binaries (which is how the dynamic linker itself is invoked: /lib/ld-linux.so.2 is statically compiled).
As answered above, your only option, as far as I'm aware, is to use fakeroot-ng, which uses a completely different mechanism to inject into the process, and is, thus, able to work on statically linked libraries without a problem.
In fact, statically linked libraries was part of the reason I set out to write fakeroot-ng in the first place. At the time, there was no way to tell ldconfig to run on a subtree, and ldconfig is statically linked.
Shachar

A: seems the solution is to use  fakeroot-ng, which works for statically linked binaries.


Q: How can I restrict jQuery UI connected lists drag and drop to single direction I am using jQuery UI Connectedlist
Here drag and drop is working fine with both side from left to right and right to left.
How can I disable right to left ? It has to work only one way, from left to right.
I need also sorting to still work inside ul yellow items like in grey items.

$(function() {
    $( "#sortable1, #sortable2" ).sortable({
      connectWith: ".connectedSortable"
    }).disableSelection();
  });
#sortable1, #sortable2 {
    border: 1px solid #eee;
    width: 142px;
    min-height: 20px;
    list-style-type: none;
    margin: 0;
    padding: 5px 0 0 0;
    float: left;
    margin-right: 10px;
  }
  #sortable1 li, #sortable2 li {
    margin: 0 5px 5px 5px;
    padding: 5px;
    font-size: 1.2em;
    width: 120px;
  }

  <meta charset="utf-8">
  <title>jQuery UI Sortable - Connect lists</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

  <link rel="stylesheet" href="/resources/demos/style.css">

Item 1

Item 2

Item 3

Item 4

Item 5

Item 1

Item 2

Item 3

Item 4

Item 5

A: You could cancel the drag event in the right list sortable2 using receive event in sortable1 to prevent receiving any item from second list.
To drag grey lis back to the left side we will add helper class e.g s2 that will identify the sortable2 original items and cancel the drag only on them :
$("#sortable1").sortable({
     receive: function(ev, ui) {
          if(ui.item.hasClass("s2"))
               ui.sender.sortable("cancel");
     }
});

Hope this helps.

$(function() {
    $( "#sortable1, #sortable2" ).sortable({
         connectWith: ".connectedSortable"
    }).disableSelection();

    $("#sortable1").sortable({
        receive: function(ev, ui) {
           if(ui.item.hasClass("s2"))
               ui.sender.sortable("cancel");
        }
    });
});
#sortable1, #sortable2 {
    border: 1px solid #eee;
    width: 142px;
    min-height: 20px;
    list-style-type: none;
    margin: 0;
    padding: 5px 0 0 0;
    float: left;
    margin-right: 10px;
  }
  #sortable1 li, #sortable2 li {
    margin: 0 5px 5px 5px;
    padding: 5px;
    font-size: 1.2em;
    width: 120px;
  }

  <meta charset="utf-8">
  <title>jQuery UI Sortable - Connect lists</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

  <link rel="stylesheet" href="/resources/demos/style.css">

Item 1

Item 2

Item 3

Item 4

Item 5

Item 1

Item 2

Item 3

Item 4

Item 5

A: Currently your connectWith selector matches both the sortable, i.e it's a two way connection. If you only want one way connection from left to right, just connect the left sortable to right sortable using a more specific selector (#sortable2) than a common one:
$(function() {
  $("#sortable1").sortable({
      connectWith: "#sortable2"
  }).disableSelection();

  $("#sortable2").sortable({}).disableSelection();
});

The demo below has the shorter code that does the same thing:

$(function() {
  $(".connectedSortable").sortable({
    connectWith: "#sortable2"
   //----------^---------- #sortable2 connectWith #sortable2 has no effect
  }).disableSelection();
});
#sortable1,
#sortable2 {
  border: 1px solid #eee;
  width: 142px;
  min-height: 20px;
  list-style-type: none;
  margin: 0;
  padding: 5px 0 0 0;
  float: left;
  margin-right: 10px;
}
#sortable1 li,
#sortable2 li {
  margin: 0 5px 5px 5px;
  padding: 5px;
  font-size: 1.2em;
  width: 120px;
}

Item 1

Item 2

Item 3

Item 4

Item 5

Item 1

Item 2

Item 3

Item 4

Item 5

A: The options you are looking for are cancel and update (s2 inspired by the post above), it will disable the drag on matched elements.
$(function() {
    $( "#sortable1, #sortable2" ).sortable({
        connectWith: ".connectedSortable",
        cancel: ".ui-state-highlight, .s2",
        update: function( event, ui ) {ui.item.addClass("s2");}
    }).disableSelection();
});


Q: How to manage contiguous memory chunks in modern C++? I've been doing some low level C++ programming these days and it involes a lot of memory management issue. For example, I may need to maintain a chunk of contiguous memory:
char* ptr = static_cast<char*>(malloc(sizeof(char)*512*1024));
....
do_something(ptr); // pass to other functions
....
do_something(ptr+sizeof(int)*4); // random access may be needed
....
free(ptr);

However, many books say that we should avoid using any raw pointer in modern C++ programing and smart pointers are preferred. Thus, what's the best practice for contiguous memory chunk management in modern C++? Should I use something like std::unique_ptr or std::allocator？

A:
"many books say that we should avoid using any raw pointer in modern C++"

It is only owning raw pointers that should be avoided. In your case you need to std::free() the pointer so you own it. Therefore you should definitely put it in a std::unique_ptr but with a custom deleter to call std::free().
// some type aliases to make life shorter...
struct malloc_deleter{void operator()(void* vp) const { std::free(vp); }};
using  malloc_uptr = std::unique_ptr<char, malloc_deleter>;

auto ptr = malloc_uptr(static_cast<char*>(std::malloc(sizeof(char)*512*1024)));
....
do_something(ptr.get()); // pass to other functions
....
do_something(ptr.get()+sizeof(int)*4); // random access may be needed
....
// no need to free, gets done when ptr` goes out of scope.


Q: Python open() function without variable initialization. Is close() method needed? I trying to understand file operations in Python 2.7. Script bellow is writing contents of input_file into output_file.
from sys import argv
script, input_file, output_file = argv

open(output_file, 'w').write(open(input_file).read())

Should I call close() method on files opened in example? (and how to reference object that isn't referenced by variable?) Are opened file objects kept in memory even when not referenced by variable?
English is not my native language; please excuse errors.

A: A better approach would be to use context managers:
with open(inputfile, 'r') as inf:
    with open(outputfile, 'w') as outf:
        out.write(in.read())

close will then be called implicitly on leaving the with block even if an exception is encountered.
However, for that specific example, why not just copy the file?


Q: String Format with undefined number of characters c# So I'm working on formatting a string and I need to line it up in a table, but this string has an undetermined number of characters. Is there anyway to have the string be in the same spot for each column? so far I have:
ostring +=  "Notes\t\t"
+ "       :  "
+ employees[number].Notes
+ "\t\t"
+ employees[number].FirstNotes
+ "\t\t"
+ employees[number].SecondNotes;

I use a similar fashion on the other rows, but they have a pre-determined number of digits, this however doesn't so I can't use the string modifiers like I would like.
Any ideas on what I need to do?

A: You can use String.PadRight() to force the string to a specific size, rather than using tabs.

A: When you are using String.Format item format has following syntax:
{ index[,alignment][ :formatString] }

Thus you can specify alignment which indicates the total length of the field into which the argument is inserted and whether it is right-aligned (a positive integer) or left-aligned (a negative integer).
Also it's better to use StringBuilder to build strings:
var builder = new StringBuilder();
var employee = employees[number];
builder.AppendFormat("Notes {0,20} {1,10} {2,15}",
    employee.Notes, employee.FirstNotes, employee.SecondNotes);

A: You would first have to loop over every entry to find the largest one so you know hoe wide to make the columns, something like:
var notesWidth = employees.Max(Notes.Length);
var firstNotesWidth = employees.Max(FirstNotes.Length);
// etc...

Then you can pad the columns to the correct width:
var output = new StringBuilder();
foreach(var employee in employees)
{
    output.Append(employee.Notes.PadRight(notesWidth+1));
    output.Append(employee.FirstNotes.PadRight(firstNotesWidth+1));
    // etc...
}

And please don't do a lot of string "adding" ("1" + "2" + "3" + ...) in a loop. Use a StringBuilder instead. It is much more efficient.


Q: Python Module Not Found Error: First function found, but second is not I have a simple dir structure:
project/
  __init__.py
  main.py
  dir1/
    __init__.py
    foo.py
  dir2/
  dir3/

Inside of main.py:
from dir1.foo import function1, function2

function1 is imported, but function2 is not, and the following error is thrown.

No module named dir1.foo found.

I have no idea how this is possible.
Edit: I am able to use function1 in main(), but when function2 is called the error is thrown.


Q: How do you get Endeca to search on a particular target field rather than across all indexed fields? We have an Endeca index configured across multiple fields of email content - subject and body. But we only want searches to be performed on the subject lines. Endeca is returning matches within the bodies too. How do you limit the search to the subject?

A: You can search a specific field or fields by specifying it (them) with the Ntk parameter.
Or if you wish to search a specific group of fields frequently you can set up an interface (also specified with the Ntk parameter), that includes that group of fields.

A: This is how you can do it using presentation API.
final ENEQuery query = new ENEQuery();
final DimValIdList dimValIdList = new DimValIdList("0");
query.setNavDescriptors(dimValIdList);
final ERecSearchList searches = new ERecSearchList();
final StringBuilder builder = new StringBuilder();
for(final String productId : productIds){
    builder.append(productId);
    builder.append(" ");
}
final ERecSearch eRecSearch = new ERecSearch("product.id", builder.toString().trim(), "mode matchany");
searches.add(eRecSearch);
query.setNavERecSearches(searches);

Please see this post for a complete example.

A: Use Search Interfaces in Developer Studio.
Refer - http://docs.oracle.com/cd/E28912_01/DeveloperStudio.612/pdf/DevStudioHelp.pdf#page=209


Q: Build failure while trying to update to "org.jooq:jooq-codegen-maven:3.15.1" [ERROR] Failed to execute goal org.jooq:jooq-codegen-maven:3.15.1:generate (default) on project event-dao-jooq: Execution default of goal org.jooq:jooq-codegen-maven:3.15.1:generate failed: Unable to load the mojo 'generate' in the plugin 'org.jooq:jooq-codegen-maven:3.15.1' due to an API incompatibility: org.codehaus.plexus.component.repository.exception.ComponentLookupException: org/jooq/codegen/maven/Plugin has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0

A: jOOQ 3.15 requires Java 11 (class file version 55) and you are using Java 8 (class file version 52) in your build. You either need to upgrade to Java 11, downgrade to jOOQ 3.14, or purchase a license for jOOQ 3.15 as all of the commercial editions still support Java 8.


Q: CSS and HTML doesn't shows properly in iOS and MacOS Safari even Chrome I have the following issue:
I have this under construction state website, https://endertainment.com, it was build with PHP and MySQL from scratch, like any other I did. The issue is when you access the website from Mobile Safari or Safari the website doesn't show all the elements must show. When you access from Android (Any Browser) or Windows or even in Linux the website shows any element well. I already run test in BrowserStack and CrossBrowserTesting... in both shows the same result; the web didn't show properly. I already remove every flexbox property and use inline-block instead. For example, this other website (https://tuticketazo.com) is under construction state too and use the same structure of https://endertainment.com.
I already made tests changing the server folder the domain points; upload a simple html page from scratch, without PHP ; use without SSL... I think already test everything but in iOS Safari, Mac OS Safari and even in Chrome in MacOS shows the elements but not in the right way.

A: You should set line-height of your heading titles.
#MainTitles h1 { line-height: 50px }

#LangSelect a { line-height: 20px; }

But the problem is not inside these 2 rules. I didn't determinate full code of CSS, I just check small fixes for places which I saw broken

A: I found the problem and resolve the Issue.
OS X have a rendering issue with some fonts.
I start my research searching a common pattern, I has this issue with 3 websites:

*

*Adjusting the line-height didn't work properly.

*Change the ul from inline-block to flexbox, didn't work

*The issue is present in any browser in Mac OS (I test Chrome,
Firefox and Safari)

Continue researching an I found some documentation about the issue.
I found this article
OS X type rendering - text baseline is shifted upwards, effectively no-longer centered vertically within the line-height
I test in the 3 different websites have the issue and VOILA!
Everything works fine now.
I used in the 3 websites the same fonts (the common pattern):

*

*Gotham Book

*Gotham Black

I can confirm this two fonts evoke the rendering issue in Mac Os.
The problem is solved right now.


Q: How to get a UTF8 encoded string from a Base64 encoded string in Javascript? AEEAQgBDAGEAYgBj is Base64 for ABCabc however when I run this code:
let a = Buffer.from('AEEAQgBDAGEAYgBj', 'base64').toString('utf-8');
console.log(Buffer.from(a, 'utf8'));

the printed result in the console is <Buffer 00 41 00 42 00 43 00 61 00 62 00 63> which is UTF16 (LE).
I would assume that since I am creating a Buffer from a UTF8 encoded string the result would be <Buffer 41 42 43 61 62 63>.
So how can I get an actual UTF8 encoded string from Base64?

A: The problem is that your original data is Base64 encoded UTF16-BE. If you look at a after your first line, you'll see that it has those zero bytes that you see in the final buffer:
let a = Buffer.from("AEEAQgBDAGEAYgBj", "base64").toString("utf-8");
console.log(a.length);
// 12
console.log([...a].map(ch => ch.charCodeAt(0).toString(16).padStart(2, "0")).join(" "));
// 00 41 00 42 00 43 00 61 00 62 00 63

So the question becomes: How to read the UTF16-BE text you have in the buffer from Buffer.from("AEEAQgBDAGEAYgBj", "base64"). Node.js's Buffer doesn't support UTF16-BE directly (there is no "utf16be" encoding in its standard library), but you can get there via swap16 and then reading the buffer as UTF16-LE ("utf16le", which is in Node.js's standard library):
let a = Buffer.from("AEEAQgBDAGEAYgBj", "base64").swap16().toString("utf16le");
console.log(a.length);
// 6
console.log(a);
// ABCabc

Now a is a normal string. If you want a buffer containing its contents in UTF8, you can use Buffer.from(a).toString("utf8"):
let a = Buffer.from("AEEAQgBDAGEAYgBj", "base64").swap16().toString("utf16le");
console.log(a.length);
// 6
console.log(a);
// ABCabc
let b = Buffer.from(a); // (Default is `"utf8"` but you could supply that explicitly)
console.log(b);
// <Buffer 41 42 43 61 62 63>


Q: Check if PDFTOHTML is installed on server I'm trying to check before running a php script if pdftohtml is installed on server.
Is there a way to check if pdftohtml is installed on server (linux or mac) from within the code.
I'm looking for something similar to function_exists()

A:
Perhaps, the following will solve your case:
$isInstalled = (bool) shell_exec('which pdftohtml');

which returns nothing if the program isn't found. But it will only work if it's installed globally (without specifying an absolute path). And returns a full path if it's there


Q: Does every operation need to be a single Command?
What I want to know:
Does every single operation provided on the list in the background paragraph need to be a single command? What do the single commands do?

Background:
I need to write a program which gets started from the cmd and performs operations on a string you can enter as argument to the command line. You also need to pass the operations to be performed as CLA.
For example: myprogram.exe /es "This is the string" /ds /rs .
Es = Enter string, ds = display string, rs=  reverse string.
It is not necessary to implement Undo/Redo.

Possible Operations are:
• Enter string
• Display string
• Reverse string
• Upperace all letters
• Lowercase all letters
• Uppercase specific letters
• Lowercase specific letters
• Eliminate consecutive duplicates
• Rotate left
• Rotate right
• Run-length encoding
• Run-length decoding
• Drop every n'th character
• Split by string and take first
• Split by string and take last

What did I do / What is my approach:
I recognized after some research that the optimal way of implementing this example would be to use the Command Pattern and Chain Of Responsibility. I'm reading the book written by the Gang of Four : Design Patterns.
But I think I do not understand perfectly the concept. I know, that using Command Pattern there is a: Invoker, Receiver, Command, CommandInterface etc. I know that the Invoker (here my ProgramHandler.cs class) generates the single Commands, equips them with a receiver and an Action. And the single Command calls the receiver to execute the action. The receiver is a class called StringManipulator which holds all the methods to manipulate a string. My idea is also, that the parser parses the CLA and "tells" the ProgramHandler which Commands need to be created.
(Please have a look on my first design approach, picture at the end!)
But:

Additional Questions:
Isn't that quite a bit of an overhead of having an abstract class SimpleCommand which holds the receiver and action and afterwards the concrete commands inherit from SimpleCommand?
It feels a bit wrong, but on the other hand: Each command needs an action and a receiver, so giving each concrete command these fields separately would be against the "rules" of object oriented Programming.
How is this designed correctly?

Class Diagram
Class Diagram
Thank you for your time and help!
Best regards!


Q: How to click automatically on "Content" button This is element HTML:
<button class="search-vertical-filter__filter-item-button button-tertiary-medium-muted" data-ember-action="" data-ember-action-5975="5975"> Content </button>

Code:
driver.find_element_by_link_text('Content').click()

Even i also tried:
driver.find_element_by_class_name('search-vertical-filter__filter-item-button button-tertiary-medium-muted').click()

I want to click on "Content" button on LinkedIn automatically and I am using Selenium and Python for that.

A: As per the HTML provided to click on the button with text as Content you can use the following line of code :
driver.find_element_by_xpath("//button[@class='search-vertical-filter__filter-item-button button-tertiary-medium-muted' and normalize-space()='Content']").click()

A: Try to use the following code:
driver.find_element_by_css_selector(".search-vertical-filter__filter-item-button.button-tertiary-medium-muted").click()

Hope it helps you!


Q: Get body of request in ASP.NET Web Api I faced problem like this.
I have method in controller, that receive data in body of POST request.
Here is method.
 // POST: api/StartWorkingDays
    [ResponseType(typeof(StartWorkingDay))]
    public IHttpActionResult PostStartWorkingDay(StartWorkingDay startWorkingDay)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.StartWorkingDays.Add(startWorkingDay);
        db.SaveChanges();
        return Json(new { Result = "Success", Message = "Saved Successfully"});
        //return CreatedAtRoute("DefaultApi", new { id = startWorkingDay.Id }, startWorkingDay);
    }

How I can see body of request that I receive?
Thank's for help.

A:     [HttpPost]
    public HttpResponseMessage PostStartWorkingDay([FromBody] StartWorkingDay startWorkingDay)
    {
      //here above startWorkingDay is body your mobile developer will send
       //you and data can be viewed while debugging ,
       //tell mobile developer to set content-type header should be JSON.
       return Request.CreateResponse(HttpStatusCode.Created, "Success");
    }

Why your return type is Json ? you should use HttpResponse . I believe you are using Web api 2 . With Attribute routing and if you want to send response in json format then remove Xml formatter from WebApiConfig.cs file inside App_Start folder


Q: Google Cloud Endpoint do not receive a request coming from ORANGE money API I have an endpoint that receives get or post requests from postman or a browser. but when the ORANGE service sends me the request in post I receive nothing.
anxious to believe that the problem comes from the ORANGE service, I went to this site https://webhook.site which generates an end point and listens to the requests made on this one, and to my surprise this endpoint receives many requests from ORANGE.
I don't understand where the problem could come from.


Q: SQLException Error Says Existing Column Doesn't Exist When running a searchQuery, I get a SQLException error saying that one of my columns cannot be found. This is very confusing, as I reference that column earlier in the code, and the program can find the column just fine at that point. do I have something wrong in the syntax? Thank you!
public void createDB(){
    String createCharTableSQL = "CREATE TABLE CosplayCharacter (" +
                "CharacterID int NOT NULL primary key GENERATED ALWAYS " +
                "AS IDENTITY (START WITH 1, INCREMENT BY 1), " +
                "name varchar(60) not null," +
                "gender varchar(10)," +
                "genreID int, " +
                "universeID int, " +
                "mediaID int, " +
                "description varchar(60))";

      statement.executeUpdate(createCharTableSQL);
}

public void insertCharacter(){
  String fetchAllDataSQL = "SELECT * from CosplayCharacter";

    //Code can find the universeID column here
        resultSet = statement.executeQuery(fetchAllDataSQL);
        while (resultSet.next()) {
            String name = resultSet.getString("name");
            int universeCharID = resultSet.getInt("universeID");

            System.out.println("Character Name : " + name +
                    " UniverseID : " + universeCharID);
        }
}

//But returns error here
public void searchCharacter(String characterName){
    String fetchAllDataSQL = "SELECT * from CosplayCharacter where name = '" + characterName +"'";

        resultSet = statement.executeQuery(fetchAllDataSQL);
        while (resultSet.next()) {
            String gender = resultSet.getString("gender");
            int genreID = resultSet.getInt("genreID");
//Method to search a column in a joined table; no error
            String genreName = getGenreName(genreID);
            int universeID = resultSet.getInt("universeID");
   }
}

Stack Trace:
 java.sql.SQLException: Column 'universeID' not found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown
Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.ConnectionChild.newSQLException(Unknown Source)

A: ResultSet was used globally. ResultSet used in getGenreName method override the resultSet in the main searchCharacter method. Solution: set ResultSet variable individually in each method.


Q: How to return value from addEventListener and use it out When I want to access to variable det out of addEventListener I get  undefined.
ElementInfo = function(element) {
  var myVar;
  this.tagName = element.tagName;
  document.addEventListener('Mylistener', function(e) {
    myVar = e.detail.workspaceName;
  });
  this.injected = myVar;
}

How can I get the value of myVar out of addEventListener? I don't use JQuery.


Q: How to get all pom.xml present under maven repo Is there any way to get all the pom.xmls which are under http://repo.maven.apache.org/maven2
Thanks,
Vijay

A: As a best practice, you should not scan and parse poms neither in remote nor local repository. On maven central they already scanned and parsed for you.
Just download nexus-maven-repository-index.gz from index dir (you need that big file 700M length, other files named nexus-maven-repository-index.XXX.gz are incremental updates)
Then use Maven Indexer to unpack index, maven indexer is available as java library and CLI program
As a result of running Maven indexer you'll get ordinary Apache Lucene index, with abitility to update it incrementally.
Here is a documentation, which explains how to unpack index and query data from it.
Most probably, index contain all the data you need.

A: For people still having the same question, I have developed a much simpler way to extract maven index indexes that works for most Nexus-based Maven repositories: the Maven Index Exporter.
From there you could simply get a list of poms and download them, if that's what you aim for.
Note however that it's huge: roughly 20 million documents are indexed for Maven Central and the text export is 14GB. There are as of today approximately 6.5 million pom files on Maven Central.


Q: Set credentials on an Android Webview using secured HTTPS connection I would like to create an Android Webview that connects to a website via a secured HTTPS connection with the use of credentials.
First difficulty was to accept the certificate (private), it was solved with this very useful post.
Second difficulty is to use credentials, I found this post.
(first answer from dparnas) which seems to deal pretty well with it, but it talks about HTTP connection and not HTTPS. I ve tried it, but it doesnt work, I just reach the sign-in form page without any error message, just the normal blank form.
Here is my code:
import android.app.Activity;
import android.net.http.SslError;
import android.os.Bundle;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ConnectorWebView extends Activity {
  WebView mWebView;
  String mUsrName;
  String mPassC;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.connwebview);

    // Getting info from Intent extras
    // Get it if it s different from null
    Bundle extras = getIntent().getExtras();
    mUsrName = extras != null ? extras.getString("username") : null;
    mPassC = extras != null ? extras.getString("passcode") : null;

    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.setHttpAuthUsernamePassword("myhost.com", "myrealm", mUsrName, mPassC);

    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedHttpAuthRequest  (WebView view, HttpAuthHandler handler, String host, String realm){
          handler.proceed(mUsrName, mPassC);
        }

        public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
          handler.proceed() ;
        }
      });

    mWebView.loadUrl("https://myhost.com/secured_area");
  }
}

A: The WebView class doesn't provide as much flexibility in its connectivity as using the low level classes (such as HttpPost or the like) directly.
If you need to fully control the connection to the server -- or deal with complicated authorization scenarios such as this one -- use the low level classes, retrieve the data, then use WebView.loadData() to load and show the HTML.
Here is a good example of loading content using SSL and a BasicCredentialProvider.  The result of this could be loaded into the WebView as described above.

A: As it seems that WebView cannot natively handle Basic authentication when using HTTPS, I started toying with the idea of setting the Authorization header (containing the encoded username/password) manually.
Here's how I think this can be done:
import org.apache.commons.codec.binary.Base64;

// ...

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.connwebview);

  // Getting info from Intent extras
  // Get it if it s different from null
  Bundle extras = getIntent().getExtras();
  mUsrName = extras != null ? extras.getString("username") : null;
  mPassC = extras != null ? extras.getString("passcode") : null;

  mWebView = (WebView) findViewById(R.id.webview);
  mWebView.getSettings().setJavaScriptEnabled(true);
  // mWebView.setHttpAuthUsernamePassword("myhost.com",
  //                                   "myrealm",
  //                                   mUsrName,
  //                                   mPassC);

  mWebView.setWebViewClient(new WebViewClient() {
      @Override
      public void onReceivedHttpAuthRequest(WebView view,
                                            HttpAuthHandler handler,
                                            String host,
                                            String realm){
        handler.proceed(mUsrName, mPassC);
      }

      public void onReceivedSslError(WebView view,
                                     SslErrorHandler handler,
                                     SslError error) {
        handler.proceed() ;
      }
    });

  String up = mUserName +":" +mPassC;
  String authEncoded = new String(Base64.encodeBase64(up.getBytes()));
  String authHeader = "Basic " +authEncoded;
  Map<String, String> headers = new HashMap<String, String>();
  headers.put("Authorization", authHeader);
  mWebView.loadUrl("https://myhost.com/secured_area", headers);
}

This takes advantage of the WebView.loadUrl (String url, Map<String, String> additionalHttpHeaders) method and for this example I'm using the Base64Encoder from Apache Commons. The Base64Encoder part is quite trivial and if you didn't want to include external libraries in your application (for whatever reason), you could always write your own (reference).
Also note that the aforementioned WebView.loadUrl (String url, Map<String, String> additionalHttpHeaders) method is only available in API 8+. For reference, see also the Wikipedia article on Basic Authentication (which discusses the headers, etc).

A: Alternative Scenario:
If willing to write roundabout 10 lines of javascript using jQuery, this scenario is rather simple.
Inject your javascript code into the webview or in case you're controlling the html page you are displaying, include it there.
If you need to interface back from javascript, you can do that. For heavier command exchange, use the CordovaWebView-Interface which has a lower delay depending on api level.


Q: Draw on desktop (windows/ubuntu) using python I am doing a project in which I need to show lines on window. Also I want to move cursor along the line. I am looking forward to work in python.
How can I do this using python or other languages. Please help me

A: i only just found this out and here you go.
import win32gui

def DRAW_LINE(x1, y1, x2, y2):
    hwnd=win32gui.WindowFromPoint((x1,y1))
    hdc=win32gui.GetDC(hwnd)
    x1c,y1c=win32gui.ScreenToClient(hwnd,(x1,y1))
    x2c,y2c=win32gui.ScreenToClient(hwnd,(x2,y2))
    win32gui.MoveToEx(hdc,x1c,y1c)
    win32gui.LineTo(hdc,x2c,y2c)
    win32gui.ReleaseDC(hwnd,hdc)

x1 = 640
y1 = 400
x2 = 840
y2 = 600

DRAW_LINE(x1, y1, x2, y2)

as for moving your mouse underneath the lines i cant figure that out


Q: 'Group by' is not grouping by in the order that I need it to I want to 'group by' beers so that they are grouped together, with the respect aggregate rating and tasters (people who review the beers) listed in separate columns.
Here is my code:
create or replace view tasters_avg_ratings1
as
select a.taster as taster, a.beer as beer, round(avg(a.rating),1) as rating
from allratings a
group by beer, taster
;

Yet my output looks like this:
beers=# select * from tasters_avg_ratings1;
 taster |          beer          | rating
--------+------------------------+--------
 Peter  | XXXX                   |    5.0
 Sarah  | James Squire Pilsener  |    3.0
 Raghu  | Sierra Nevada Pale Ale |    3.0
 Hector | Fosters                |    3.0
 John   | Chimay Red             |    3.0
 John   | Sierra Nevada Pale Ale |    5.0
 Geoff  | James Squire Pilsener  |    4.0
 Ramez  | Sierra Nevada Pale Ale |    4.0
 John   | 80/-                   |    4.0
 John   | Rasputin               |    4.0
 Adam   | Old                    |    4.0
 John   | Crown Lager            |    2.0
 Jeff   | Sierra Nevada Pale Ale |    4.0
 Sarah  | Burragorang Bock       |    4.0
 Sarah  | Scharer's Lager        |    3.0
 Sarah  | New                    |    2.0
 Geoff  | Redback                |    4.0
 Adam   | Victoria Bitter        |    1.0
 Sarah  | Victoria Bitter        |    1.0
 Raghu  | Rasputin               |    3.0
 Ramez  | Bigfoot Barley Wine    |    3.0
 Hector | Sierra Nevada Pale Ale |    4.0
 Sarah  | Old                    |    3.0
 Jeff   | Burragorang Bock       |    3.0
 John   | Empire                 |    3.0
 Sarah  | James Squire Amber Ale |    3.0
 Rose   | Redback                |    5.0
 Geoff  | Empire                 |    3.0
 Adam   | New                    |    1.0
 Jeff   | Rasputin               |    1.0
 Raghu  | Old Tire               |    5.0
 John   | Victoria Bitter        |    1.0
(32 rows)

As you can see, the beers are NOT grouped together. Ideally for example, the 'Victoria Bitter' beers should be displayed as a group, not separated.
The desired result is achieved using 'order by'. For example:
create or replace view tasters_avg_ratings1
as
select a.taster as taster, a.beer as beer, round(avg(a.rating),1) as rating
from allratings a
group by beer, taster
order by a.beer
;

OUTPUT:
beers=# select * from tasters_avg_ratings1;
 taster |          beer          | rating
--------+------------------------+--------
 John   | 80/-                   |    4.0
 Ramez  | Bigfoot Barley Wine    |    3.0
 Jeff   | Burragorang Bock       |    3.0
 Sarah  | Burragorang Bock       |    4.0
 John   | Chimay Red             |    3.0
 John   | Crown Lager            |    2.0
 Geoff  | Empire                 |    3.0
 John   | Empire                 |    3.0
 Hector | Fosters                |    3.0
 Sarah  | James Squire Amber Ale |    3.0
 Geoff  | James Squire Pilsener  |    4.0
 Sarah  | James Squire Pilsener  |    3.0
 Adam   | New                    |    1.0
 Sarah  | New                    |    2.0
 Adam   | Old                    |    4.0
 Sarah  | Old                    |    3.0
 Raghu  | Old Tire               |    5.0
 Jeff   | Rasputin               |    1.0
 John   | Rasputin               |    4.0
 Raghu  | Rasputin               |    3.0
 Geoff  | Redback                |    4.0
 Rose   | Redback                |    5.0
 Sarah  | Scharer's Lager        |    3.0
 Hector | Sierra Nevada Pale Ale |    4.0
 Jeff   | Sierra Nevada Pale Ale |    4.0
 John   | Sierra Nevada Pale Ale |    5.0
 Raghu  | Sierra Nevada Pale Ale |    3.0
 Ramez  | Sierra Nevada Pale Ale |    4.0
 Adam   | Victoria Bitter        |    1.0
 John   | Victoria Bitter        |    1.0
 Sarah  | Victoria Bitter        |    1.0
 Peter  | XXXX                   |    5.0
(32 rows)

So while I know order by achieves my result, why doesn't 'group by' do the same thing? It is frustrating because I have seen numerous examples on the internet using 'group by' and succeeding especially in cases similar to mine with non-aggregate and aggregate columns. For example: https://learnsql.com/blog/error-with-group-by/ , at tip #3.
Any help would be appreciated, thanks!

A: GROUP BY is only being used to compute the aggregate value (average rating in this case). It doesn't have anything to do with the ordering of the results when they are displayed. As you have mentioned, you need to use ORDER BY to get the desired ordering.

A: Group By should be used to group rows that have the same value for the specified column,
Full explanation here https://stackoverflow.com/a/2421441.
In your case, you want to group beers with the respect to aggregate rating and tasters, so you need to GROUP  BY a.beers and order by the first and the third column.
Thus the view should be like this:
create or replace view tasters_avg_ratings1
as
select a.taster as taster, a.beer as beer, round(avg(a.rating),1) as rating
from allratings a
group by a.beer
order by 1,3;

1 and 3 are the ordinal positions of columns that appear in the select list.

A: The SQL standard defines that a SELECT statement without an ORDER BY may return the resulting rows in an arbitrary order. There is a good explanation of why it might look different at first.
GROUP BY is for grouping and aggregating related tuples together. A trivial implementation for grouping is of course sorting the data first and then working your way from top to bottom and aggregate related tuples. If your database chooses to use such an implementation chances are high you will receive an ordered result set. But there are other implementations possible and your database may change to using one of those at any time. And if it does you will receive the same rows but in a different order.
So in short, if you want your result set to be ordered use an ORDER BY.
Regarding the example you mentioned it is perhaps a bit misleading. The result is ordered by the columns it is also grouped by. This is a possible ordering and given the thoughts before probably quite a likely one. But since the query is without an ORDER BY this is just coincidence and not guaranteed.


Q: When is the screenshot taken for the app drawer? I have an app with a login page.  In the login page, I have a switch to allow the user to show the password they are entering in plain text to ensure they are entering it correctly.  However, when I pause the app and the app goes into the background, a screenshot is taken and the plain text password can be seen in the app drawer.
I tried adding a statement in the onPause() method of the activity to turn off the Hide/Show switch before pausing.  You can see the password revert back to a masked password before the app pauses, but the screenshot still shows the plain text password.
So I'm wondering when the screenshot for the app drawer is taken and whether I can get the password switched back to masked before that happens.
I know about the FLAG_SECURE window flags but that creates a black app drawer screenshot and I would prefer to give something more user-friendly to the user.
Thanx in advance.

A: Unfortunately, what you want is not supported. There is a method in Activity called onCreateThumbnail() that can be overridden to provide a custom thumbnail, but according to a post from Dianne Hackborn in 2009, this method is never actually called:
https://groups.google.com/d/msg/android-developers/J5uBtHzhG8E/bX43j_GAm4gJ
I've tried it relatively recently myself to no effect, so I have to assume that's still the case.


Q: Retaining a value obtained from file within the return value of a method Assuming I will need to access the values contained within a given file a small number of times, from different methods, can I include some sort of boolean value within a method to determine whether or not it is appropriate to call the file?
Lets say I have the file config.cfg. In that file, there are three values:
string/name>max|
bool/adult>yes|
int/age>20|

The method getUserName() returns the value of "max". It does this by calling the file:
using (StreamReader reader = new StreamReader(path))
{
    //get line beginning with string/name here
    return //string value containing name
}

Let's assume I need to use the value of name several times, as well as the values isAdult and clientAge. Rather than accessing the file over and over again, it could be much easier to save the requested value in some form of static variable. However, this variable still needs to be changed in value at least once, when the method is first called.
Can I do this inside the method getUserName()?
Furthermore, is this idea even possible within the bounds of OOP? Is it a similar concept to Prefetch?

A: Create a static class. Something like this:
 public static class ClientConfig{

    public static string Name{get;set;}
    public static bool IsAdult{get;set;}
    public static int Age{get;set;}

     public static void Load(){
     // load your values
    // ClientConfig.Name = name from file etc.
    }

    public static void Save(string newName, int age, bool value){
     // save your values to the config file
    }
    }

And call ClientConfig.Load() first time when your app starts, for example (or whenever you need to retrieve config data)

A: It really looks to me that you  need to access a field in a lazy way (i.e. only if needed, when needed). If so .NET has Lazy class for such cases which also provides thread safety out of the box:
public static Lazy<string> Name { get; } = new Lazy<string>(() => ReadNameFromFile());

Lazy will also ensure that you only create value once (i.e. call initiailization method) and on later calls it will simply return already retrieved value.


Q: Facebook JavaScript SDK help 1002 I am using the jQuery library for authenticating the user, using this script:


Q: whitelist allowed hosts, block everything else using the chrome.declarativeWebRequest, it is possible to execute actions if some conditions apply. The only available Condition is an Instance of declarativeWebRequest.RequestMatcher which is useful to test if the url has some features. I am searching for a way to test if an url does not have some features For instance:
chrome.declarativeWebRequest.onRequest.addRules([
  {
    conditions: [
      new chrome.declarativeWebRequest.RequestMatcher({
        url: { hostSuffix: 'google.com' } })
    ],
    actions: [
      new chrome.declarativeWebRequest.CancelRequest()
    ]
  }
]);

Will block all Requests to the host google.com. But I am interested in a rule that does the opposite, block everything but google.com.

A: According to documentation, you can use the rules' priorities to achieve your goal: create one rule to cancel all requests and another rule, with higher priority, to ignore the first rule if the host is google.com.


Q: How to list out all the api in an Django application? I have an Django application which is around 4 years old.
I want list out all the api in order to remove all inactive api's from the codebase.
Is there any way to figure out all the API?
The application is based on Djnago. We are using javascript for the frontend part.


Q: YAML issue when knitting to pdf I have a paper written in rnotebook, which I want to knit to pdf.
this is the beginning of it, including the YAML:
---
title: "Are shifts between points of view challenging for readers? An examination of readers' eye movements in response to Woolf's *To the Lighthouse* and *Mrs Dalloway*"
author: "Giulia Grisot, Kathy Conklin, Violeta Sotirova - The University of Nottingham"
date: '`r format(Sys.time(), "%d %B %Y")`'
output:
  html_notebook:
    fig_caption: yes
    force_captions: yes
    #highlight: pygments
    number_sections: false
    theme: readable
# csl: sage-harvard.csl
csl: apa.csl
bibliography: library.bib
link-citations: yes
nocite: |
  @Grisot2018

---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE, message=FALSE)
```

```{r, include=F}
library(tidyverse)
library(ggpubr)
```

# Abstract

The emergence of empirical approaches within stylistics has increased interest in how literary texts are processed by readers. Techniques of speech and thought representation represent an area ripe for empirical investigation in this respect, especially when these cause interpretative ambiguities.

I have installed tinytex, and I have got miktex installed and pandoc.
I have tried to just use the "knit to pdf" command in RStudio but it gives me this error and i don't know what to do
Error in yaml::yaml.load(..., eval.expr = TRUE) :
  Scanner error: while scanning for the next token at line 4, column 31 found character that cannot start any token at line 4, column 31
Calls: <Anonymous> ... parse_yaml_front_matter -> yaml_load -> <Anonymous>
Execution halted

A: I think this is down to the formatting in your yaml. When I knitted your code R Studio did some re-formatting of the title, but in the process replaced the ' with " in your date, causing the error. I don't have your .bib file so I can't test your exact code, but the following worked for me:
---
title: Are shifts between points of view challenging for readers? An examination of
  readers' eye movements in response to Woolf's *To the Lighthouse* and *Mrs Dalloway*
author: "Giulia Grisot, Kathy Conklin, Violeta Sotirova - The University of Nottingham"
date: '`r format(Sys.time(), "%d %B %Y")`'
output:
  pdf_document: default
  html_notebook:
    fig_caption: yes
    force_captions: yes
    number_sections: no
    theme: readable
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE, message=FALSE)
```

```{r, include=F}
library(tidyverse)
#library(ggpubr)
```

# Abstract


Q: Using string.prototype.replace with a regexp and a function The following returns 'entiy'. I want it to return 'entity'. How can I achieve this?
'entities '.replace(/\w(ies)(?:[\W|$|_])+/g, 'y');

A: You could change the \w to \B to verify that there is not a word boundary.

console.log('entities '.replace(/\Bies\b/g, 'y'));

A: Just capture the character before the "ies":
'entities '.replace(/(\w)(ies)(?:[\W|$|_])+/g, '$1y');

Now your question asked about using a function; you can do that too:
'entities '.replace(/(\w)(ies)(?:[\W|$|_])+/g, function(_, before, repl) {
  return before + "y";
});

I don't know what you want to do with the subsequent stuff after "ies"; you can either capture it and glue it back into the replacement, or else use positive look-ahead. Portions of the input text matched by look-ahead are not part of the match involved with the replacement operation. In other words, the look-ahead does succeed or fail based on the pattern, but the characters matched are not made part of the "to be replaced" grouping.


Q: How to serve static images in nodejs server using absolute path in Angular 10 img tag? I have been searching here and not finding a solution, so I am asking. How can I serve my static images located in the nodejs server:
public/img

Nodejs (before app.listen()):
app.use("/api", routesIndex);
app.use(express.static(__dirname + '/public/img'));

Angular 10 template:

The [src] resolves to the absolute correct path of:
http://localhost:5000/api/public/img/shark.jpg

But it shows 404 still. Any ideas?
Thanks

A: There is no need to add path of statically served directory. Just remove '/public/img/'

You can access the all file of your served directory directly. like:
http://localhost:5000/shark.jpg

A: Follow the below steps,
your image is at path Public/img/shark.jpg

in your app.js, this should be before any route is created
app.use(express.static(__dirname + '/public/img'));

create a route as below
app.get('/Image/:id', function (req, res) {
    // logic to find image based on id passed, we will assume it results in shark.jpg
    const filepath = `${__dirname}/public/img/shark.jpg`;
    res.sendFile(filepath);
});

Now consume this endpoint from your angular code
localhost:{PORT_NUMBER}/Image/{ID_FOR_SHARK_IMAGE}

A: I got it working by doing the following:
Nodejs added path:
const path = require("path");

app.use(express.static(path.join(__dirname, 'public/img')));

Then in Angular created a separate assetUrl that omits the "/api" part of the baseUrl:
[src]="quizService.assetUrl+'/'+quizService.questions[quizService.questionProgress].imageName+'.jpg'"

and now my images are served.


Q: Filter Data in Shiny by Clicking on Plot Data Point I Want to filter data by click on data points of plot in Shiny, like we have in powerbi.
i have developed a dashboard in powerbi i want to have a same effect in shiny,
like if i click the data point of plot in shiny dashboard the other plots should drill down in response to that point, i have build a complete dashboard in shiny but i need to add these function.
there can also be multiple data points drill down like if i want to know the february(datapoint) month sales of John(datapoint).

A: In the UI, you should add, click,doubleclick or hover:
 plotOutput("plot1", click = "plot_click")

And in the Server will be input$plot_click, X and Y coordinates
Here a Shiny explanation:
https://shiny.rstudio.com/articles/plot-interaction.html
And I wrote for you a simple example:
library(shiny)
library(ggplot2)
library(MASS)

ui<- shinyUI(
       fluidPage(
                plotOutput("grafica", hover="clickGrafica"),
                tableOutput("miverbatini")
        )
)
server<- shinyServer(function(input,output) {

        output$grafica <- renderPlot({

                ggplot(mpg,aes(x=cty, y=hwy)) +
                        geom_point()
        })

        output$miverbatini <- renderTable({
                nearPoints(mpg,input$clickGrafica, threshold = 10)  # near points 20
        })
})
shinyApp(ui, server)


Q: Why Radio button selects multiple options when label values are different Having a reusable Radio button component, when the options are using the same value for name it works fine:
  const drinks = [
    {
      label: "Coffee",
      name: "a"
    },
    {
      label: "Tea",
      name: "a"
    },
    {
      label: "Water",
      name: "a",
      disabled: true
    }
  ];

But when they are different values, it doesn't work fine, it lets the user select multiple options:
  const drinks = [
    {
      label: "Coffee",
      name: "1"
    },
    {
      label: "Tea",
      name: "2"
    },
    {
      label: "Water",
      name: "3",
      disabled: true
    }
  ];

Here is a working sandbox of it as it's complicated to create a working example here: https://codesandbox.io/s/custom-radio-button-group-forked-1do5u4?file=/src/App.tsx

A: As i mentioned in comment,
the code is working as expected
const drinks = [
    {
      label: "Coffee",
      name: "a"
    },
    {
      label: "Tea",
      name: "a"
    },
    {
      label: "Water",
      name: "a",
      disabled: true
    }
  ];

the name attribute is used to group radio buttons,and only one radio button in the group can be selected at a time.

A: It is working as expected. If it's a radio button, then it's ONE name and multiple possible values. Only one of them can be selected at a time.
  const drinks = [
  {
    label: "Coffee",
    name: "drinkType"
  },
  {
    label: "Tea",
    name: "drinkType"
  },
  {
    label: "Water",
    name: "drinkType",
    disabled: true
  }
  ];


Q: How to correctly use two DatePickerSingle in a Dash Application Hope you all doing well.
I have two DatePickerSingle  that I want to integer in a dash application to use them as a filter further. The problem is that my Dash app only returns values of the first DatePickerSingle, but not the second one ..

from datetime import date
import dash
from dash.dependencies import Input, Output, State
import dash_html_components as html
import dash_core_components as dcc

Min_d =datetime.strptime(str(df_sub['From'].min()), "%Y-%m-%d %H:%M:%S")
Max_d = datetime.strptime(str(df_sub['From'].max()), "%Y-%m-%d %H:%M:%S")

app = dash.Dash(__name__)
app.layout = html.Div([
    html.H2("Date for the First period"),
    dcc.DatePickerRange(
        id='my-date-picker-range',
    min_date_allowed = date(2021,4,1),
    max_date_allowed = date(2021,9,30)
    ),

    html.H2("Date for the Second period"),

    dcc.DatePickerRange(
        id='my-date-picker-range2',
    min_date_allowed = date(2021,4,1),
    max_date_allowed = date(2021,9,30)
    ),

    html.Div(id='output-container-date-picker-range')
])

@app.callback(
    Output('output-container-date-picker-range', 'children'),

    Input('my-date-picker-range', 'start_date'),
    Input('my-date-picker-range', 'end_date'),
    Input('my-date-picker-range2', 'start_date2'),
    Input('my-date-picker-range2', 'end_date2')
)

def update_output(start_date , end_date , start_date2 , end_date2):

        return ( str(start_date) + '   ' + str(end_date)+ '   ' +str(start_date2)+ '   ' +  str(end_date2))

if __name__ == '__main__':
    app.run_server(debug=False)

Here is what I got when I run the app :

A: The problem is with these lines:
Input('my-date-picker-range2', 'start_date2'),
Input('my-date-picker-range2', 'end_date2')

start_date2 and end_date2 are not valid properties of dcc.DatePickerRange, so change these instances to start_date and end_date.


Q: VB 2008 Express edition vs VB 6 Can any tell me what are the advantages of VB.NET(2008 Express Edition) over VB 6?
Thank you

A: Good comparison you can find in Wiki:
VB.NET
In short: the greatest feature in VB.NET is Managed Code. It also contains a little difference between Long and Integer in VB6 and VB.NET. There are also many small syntax changes (for example, VB.NET support structured exception handling).

A: VB6 is a old fashioned programming software from microsoft. It doesn't use as a base .NET framework which is used on every machine. Also visit Wkipedia VB

A: .NET have multithreading and more functional components (for work with network for example).

A: Visual Basic is a third-generation event-driven programming language and integrated development environment (IDE) from Microsoft for its Component Object Model (COM) programming model first released in 1991, final release was version 6 in 1998 (VB6) and declared legacy during 2008.
Visual Basic.net is part of the .net framework (like C# or F#), first released in 2002, with constant Microsoft updates.
You can use VB.Net in Visual Studio 2008 Express (free) or in any Visual Studio IDE, like the Visual Studio 2017 Community edition (also free).
https://en.wikipedia.org/wiki/Comparison_of_Visual_Basic_and_Visual_Basic_.NET
VB6 uses legagy frameworks like Dynamic Data Exchange (DDE) and DAO. The VB6 IDE is hard to install on new operating system (original setup gives errors on Windows 7, 8 or 10).


Q: VNC feed from a remote server I want to measure the performance of the VNC feed from a remote server. The use case is, there will be a  user login to the remote server and doing some operations. There will be many other users viewing these operations through the VNC viewer (ssh connection). Based on the different network speed I want to measure the performance of the VNC feeds of the users who are viewing. How to achieve this through JMeter?
Note that the users who are viewing are not doing any operations on the remote server.

A: VNC and SSH are different beasts so your VNC viewer (ssh connection) stanza doesn't make a lot of sense, VNC is a separate protocol and JMeter doesn't support it either via its samplers or via plugins
If you still want to use JMeter for load testing your VNC server you will need to implement the client login and getting initial image using some form of VNC Java client library like Vernacular VNC from JSR223 Sampler or come up with your own JMeter plugin


Q: How to set a Sharepoint lookup field when inserting a new record in PowerApps I am using the Collect function to insert a new record into a Sharepoint list using PowerApps. There is a Gallery with a list of values from another Sharepoint List. I want to use the Selected value from the Gallery to set one of the fields in the Insert List.
I thought it would be as easy as this:
Collect('Concert Log List',{Attendee: BrowseGallery1.Selected});

Essentially I want to add a new record to the Content Log List and reference the Attendee (which is the lookup list) every time the Attendee is referenced. Now the field just ends up being blank.

A: Hm. Gallery1.Selected represents the entire record in the Sharepoint List. Can you add another . to Selected to get to the actual field you want to write?
Gallery1.Selected.Attendee (or the like)

A: Got it:
Patch('Child List',
  Defaults('Child List'),
  {
    Title:"test",
    ParentItem:
      {
        Id:Gallery1.Selected.ID,
        Value:Gallery1.Selected.Title
      }
  }
)


Q: Gseapy: how to get gene list used for each pathway I am running an enrichment analysis with gseapy enrichr on a list of genes.
I am using the following code:
enr_res = gseapy.enrichr(gene_list = glist[:5000],
                            organism = 'Mouse',
                            gene_sets = ['GO_Biological_Process_2021'],
                            description = 'pathway',
                            #cutoff = 0.5
                            )

The result looks like this:
enr_res.results.head(10)

The question I have is, how do I get the full set of Genes (very right column in the picture) used for the individual pathways?
If I try the following code, it will just give me the already displayed genes. I added some correction to have a list that I then could further use for the analysis.
x = 'fatty acid beta-oxidation (GO:0006635)'

g_list = enr_res.results[enr_res.results.Term == x]['Genes'].to_string()

deliminator = ';'
g_list = [section + deliminator for section in g_list.split(deliminator) if section]

g_list = [s.replace(';', '') for s in g_list]
g_list = [s.replace(' ', '') for s in g_list]
g_list = [s.replace('.', '') for s in g_list]

first_gene = g_list[0:1]
first_gene = [sub[1 : ] for sub in first_gene]

g_list[0:1] = first_gene
for i in range(len(g_list)):
    g_list[i] = g_list[i].lower()
for i in range(len(g_list)):
    g_list[i] = g_list[i].capitalize()

g_list

I think my approach might be wrong to get all the Genes and I just get the displayed genes. Does somebody has an idea, how it is possible to get all genes?

A: pd.set_option('display.max_colwidth', 3000)

This increases the number of displayed characters and somehow this solves the problem for me. :)


Q: Disable a command box in Databricks notebook I have a Databricks Notebook. My notebook has several command. some of them is just for my test and I do not want ran them on production.
Is there any way to just disable a command. I do not want to delete them permanently.

A: Late ... but ... my solution is to set %md as first line. So no command would be executet.
David


Q: Canceling pending sends errors I am running Selenium WebDriver scripts on Chrome Browser, version 23.
The tests run successfully without any error but there is a message:
[0103/143909:ERROR:ipc_sync_channel.cc(378)] Canceling pending sends
[0103/143909:ERROR:ipc_sync_channel.cc(378)] Canceling pending sends
And because of the above error, the result of the test is FAILED.
Here is how I instantiate a chrome browser session:
public static boolean setup(String browserType){
    if(browserType.equals("IE")){
        webdriver1 = new InternetExplorerDriver();
    } else if(browserType.equals("Chrome")){
        System.setProperty("webdriver.chrome.driver","path to  chromedriver.exe");
        webdriver1 = new ChromeDriver();
}

Appreciate any feedback from anyone who has resolved this issue.

A: According to https://code.google.com/p/chromedriver/issues/detail?id=159 it has something to do with your browser has not yet finished loading a page, while selenium closes and quits the driver.


Q: Deleting table data from tablespace in Oracle I tried to delete the data from tablespace using the command

DROP USER xyz CASCADE;

I found that user was dropped but size of my tablespace did not decreased.
Is my data fom the tablespace have been deleted? If yes, how can I confirm that? And why was the space not deallocated?

A: Oracle does not automatically shrink datafiles, which is what a tablespace is made of.  Oracle simply marked the space which had been used by user XYZ's segments (tables, indexes, and the like) as free for some other user's segments to use.
SELECT * FROM DBA_OBJECTS WHERE OWNER = 'XYZ'; should demonstrate that user XYZ no longer owns any physical (tables, indexes, clusters) or logical (sequences, procedures, packages, triggers, types) objects in the database.

A: You can shrink datafile, under certain circumstances, with following command:
ALTER DATABASE DATAFILE 'filename2' RESIZE new_size;

Datafile size can be reduced if there is no data at the end of file. See "Managing Tablespaces" for detailed information.


Q: Influxdb python write_api not write specific fields I am trying to write several points into influxdb by using the python client.
Most of them are working but some specific fields of points are not saving.
Here's my code.
def getPoints(p_zones):
  # Writing max values to p_zones and then add to write_api
  points = []
  for p_zone in p_zones:
    point = Point("mem") \
      .tag("zone", p_zone.zone) \
      .field("historic", p_zone.historic) \
      .field("current", float(p_zone.current)) \
      .field("hourMaxValue", p_zone.hourMaxValue) \
      .time(p_zone.timestamp.astimezone(eastern), WritePrecision.NS)
      # .tag("label", p_zone.label) \
    points.append(point)
  return points

points = getPoints(p_zones)

# Writing to influx
with client.write_api(write_options=WriteOptions(retry_interval=15, max_retries=2, write_type=SYNCHRONOUS)) as write_api:
      write_api.write(bucket=bucket, org=org, record=points)

And here is the log of points before writing to influxdb.
mem,zone=Pool\ Deck current=0,historic=25,hourMaxValue=25 1653931921000000000
mem,zone=Pool\ Deck current=25,historic=25,hourMaxValue=25 1653931920000000000
mem,zone=Pool\ Deck current=25,historic=25,hourMaxValue=25 1653931915000000000
mem,zone=Game\ Room current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=Meeting\ Area\ EAST current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=Meeting\ Area\ WEST current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=Pool\ Club\ Room current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=TV\ Area\ WEST current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=Weight\ Room current=2,historic=2,hourMaxValue=2 1653931920000000000
mem,zone=Movie\ Theater current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=Business\ Conference\ Room current=0,historic=0,hourMaxValue=0 1653931920000000000
mem,zone=Cardio\ Room current=1,historic=1,hourMaxValue=1 1653931920000000000
mem,zone=TV\ Area\ EAST current=0,historic=0,hourMaxValue=0 1653931920000000000

But in online influxdb, I can see every points are looking good but the Pool Deck point's current andhourMaxValue fields are not saving.


Q: regex excluding time from text I would like to extract time from the text below using regex.
Text: "Media: a few minutes ago, 3:25 pm uts"
Regex pattern to select only time (ex: 3:25) from the above text?

A: Use regex /\b[0-9]+:[0-9]+\b/. Explanation:

*

*\b - word boundary

*[0-9]+ - 1+ digits

*: - literal colon

*[0-9]+ - 1+ digits

*\b - word boundary

I do not know your specific use in selenium, but here is an example:
src = 'Media: a few minutes ago, 3:25 pm uts'
pattern = re.compile(r'(\\b[0-9]+:[0-9]+\\b)')
match = pattern.search(src)
print match.groups()[0]

Output:
3:25


Q: Zend_Log with multiple writers in application.ini i have a logger in my config like this:
resources.log.stream.writerName = "Stream"
resources.log.stream.writerParams.stream = APPLICATION_PATH "/../logs/err.log"
resources.log.stream.writerParams.mode = "a"
resources.log.stream.filterName = "Priority"
resources.log.stream.filterParams.priority = 3

But i want to use it for only error logs. For another logs wanna use another log file. For that reason i added these lines to app.ini
resources.log.stream.writerName = "Stream"
resources.log.stream.writerParams.stream[] = APPLICATION_PATH "/../logs/debug.log"
resources.log.stream.writerParams.stream[] = APPLICATION_PATH "/../logs/info.log"
resources.log.stream.writerParams.mode = "a"
resources.log.stream.filterName = "Priority"
resources.log.stream.filterParams.priority[] = 7
resources.log.stream.filterParams.priority[] = 5

But this is not working i wanna use differetn files for different priorities. But logger overrides the first logger. How ?

A: Example of application.ini:
resources.log.err.writerName = "Stream"
resources.log.err.writerParams.stream =  APPLICATION_PATH "/../data/logs/ERR.log"
;resources.log.stream.formatterParams.format = "%priority%:%message% %timestamp% %priorityName%  %info% PHP_EOL"
resources.log.err.filterName = "Priority"
resources.log.err.filterParams.priority = 3
resources.log.err.filterParams.operator = "=="

resources.log.warn.writerName = "Stream"
resources.log.warn.writerParams.stream = APPLICATION_PATH "/../data/logs/WARN.log"
;resources.log.warn.formatterParams.format = "%priority%:%message%:%ip%:%userid% %timestamp% %priorityName%  %info% PHP_EOL"
resources.log.warn.filterName = "Priority"
resources.log.warn.filterParams.priority = 4
resources.log.warn.filterParams.operator = "=="

In bootstrap:
protected function _initLog() {
    $options = $this->getOption('resources');
    $partitionConfig = $this->getOption('log');
    $logOptions = $options['log'];
    $logger = Zend_Log::factory($logOptions);
    $logger->addPriority('USERACTION', 8);
    $logger->addPriority('DBLOG', 9);
    Zend_Registry::set('logger', $logger);
}

Then in codes:
$this->logger = Zend_Registry::get('logger');
$this->logger->setEventItem('ip', $_SERVER['REMOTE_ADDR']);
$this->logger->setEventItem('userid', $this->userId);

Use this way:
$this->logger->log('Test error', Zend_Log::WARN);

Or this way:
$this->logger->warn('Test error');

Or this way:
$this->logger->log('Test error', 4);

A: You can use filters to accomplish this. Just let higher priority events pass through the filters until you want to log them.
http://framework.zend.com/manual/en/zend.log.filters.html
What's wrong in your setup is that you are trying to use the same writer which you should not. Use the filters to choose the writers and associate certain log files with certain writers, as shown in the second part of the example.
I think something like that should do the trick:
resources.log.stream.writerName = "myDebugWriter"
resources.log.stream.writerParams.stream = APPLICATION_PATH "/../logs/debug.log"
resources.log.stream.filterName = "Priority"
resources.log.stream.filterParams.priority = Zend_Log::WARN
resources.log.stream.writerName = "myInfoWriter"
resources.log.stream.writerParams.stream = APPLICATION_PATH "/../logs/info.log"
resources.log.stream.filterName = "Priority"
resources.log.stream.filterParams.priority = Zend_Log::INFO


Q: Is there any Number recognition SDK or frameworks or libraries for iPhone I need number recognition for my project, as i will write the number using touches. i want that to be recognized.
Can anyone Please Help me, provide me any ideas or frameworks or libraries related to this.

A: this might get you started http://code.google.com/p/dollar-touch/


Q: Memory Problem when creating large Access reports We are having a problem. We have a complex Access 2003 application. When our main user is trying to create a particularly long report he getting a message “2004 - There isn't enough memory to perform this operation. Close unneeded programs and try the operation again”. The problem is the rest of us are able to run the same report fine. Our user is able to run the same report ok with fewer amounts of data. We looked at the obvious things such as the amount of memory on his machine and the disk space available. That seems to be ok compared to those of are able to run ok.
The failure occurs when he tries to write the report to a word file. He is able to create the report when he writes directly to a printer, but since the report is so long what we do is to write the output to a pdf file.
The report runs 4500 pages. These are oversize pages meaning that the data would be truncated if you use a normal size printer and page.
I have search the internet but none of the suggestions seem to work for us. Any suggestions you have will be appreciated.
Bob Avallone

A: Do you have graphics on the report?  Even a small one on the page header?  If so don't use the format event to fill the graphic.  Or change the grapic to a BMP.


Q: service / subscription manager engine Is there a good opensource service/subscription manager engine that contains things like service dependencies (i.e. if I choose service A, I also need Service B and Service C), subscription types, start and termination etc...
I'm building a site that sells various services and subscriptions and would prefer not to have to write that code as I'm pretty sure it's been done many times over (e.g. in e-commerce sw), but I'd prefer a small library / egine instead of having to integrate with an e-shop.

A: If your "Service" is just Java classes/package/modules then you can use Spring or any other DI container that supports lifecycle hookups.
If by "Service" you mean something big/bloated/enterprise you can also look into OSGI.
But for a small/library engine I suggest you look at plexus and picocontainer.


Q: How do I grab the AR1 estimate and its SE from the gls function in R? I am attempting to get the lag one autocorrelation estimates from the gls function (package {nlme}) with its SE. This is being done on a non-stationary univariate time series. Here is the output:
Generalized least squares fit by REML
  Model: y ~ year
  Data: tempdata
       AIC      BIC    logLik
  51.28921 54.37957 -21.64461

Correlation Structure: AR(1)
 Formula: ~1
 Parameter estimate(s):
      Phi
0.9699799

Coefficients:
                 Value Std.Error    t-value p-value
(Intercept) -1.1952639  3.318268 -0.3602072  0.7234
year        -0.2055264  0.183759 -1.1184567  0.2799

 Correlation:
        (Intr)
year    -0.36

Standardized residuals:
        Min          Q1         Med          Q3         Max
-0.12504485 -0.06476076  0.13948378  0.51581993  0.66030397

Residual standard error: 3.473776
Degrees of freedom: 18 total; 16 residual

The phi coefficient seemed promising since it was under the correlation structure in the output
Correlation Structure: AR(1)
 Formula: ~1
 Parameter estimate(s):
      Phi
0.9699799

but it regularly goes over one, which is not possible for correlation. Then there is the
Correlation:
        (Intr)
Yearctr -0.36

but I was advised that this was likely not a correct estimate for the data (there were multiple test sites so this is just one of the unexpected estimates). Is there a function that outputs an AR1 estimate and its SE (other than arima)?
sample of autocorrelated data:
set.seed(29)
y = diffinv(rnorm(500))
x = 1:length(y)
gls(y~x, correlation=corAR1(form=~1))

Note: I am comparing the function arima() to gls() (or another method) to compare AR1 estimates and SE's. I am doing this under adviser request.


Q: Editing repeating table INfoPath Form in form library? I created repeating table and I added two fields in it.while publishing its not giving me option to edit those properties in my document library...when we generally publish we get the option to edit those properties in document library but its disable while creating repeating table any suggestions how to do that?

A: Check the box to enable editing in SP during your form publish.


Q: Cannot link to libclang in OSX High Sierra I have installed llvm and clang through brew.
When I compile a program with the header file "clang-c/Index.h", I get
Undefined symbols for architecture x86_64:
"_clang_createIndex", referenced from:
  _main in t-c9baef.o
....

Here is the command I used for compiling my program:
CXX=/usr/local/opt/llvm/bin/clang++ CPPFLAGS=-I/usr/local/opt/llvm/include make prog

I am using OSX High Sierra.

A: I have managed to fix the issue.
The command I used for building is:
CXX=/usr/local/opt/llvm/bin/clang++ \
LDFLAGS+='-L/usr/local/opt/llvm/lib \
-L/usr/local/Cellar/llvm/5.0.1/lib -lclang' \
CPPFLAGS=-I/usr/local/opt/llvm/include \
make myprog

I had to link against the libclang.dylib and add -lclang


Q: checkbox onchange not working What am I missing. None of these checkboxes, when checked or unchecked, produces any messages, even if I just past this into a clean html file. It also doesn't work even in an html file where everything else is working fine in terms of the javascript.
Here is the form declaration:
 <form>
 <input type="checkbox" name="all"  id="all" onChange="alert('hi')">
 <input type="checkbox" name="all"  id="all" onClick="alert('hi')">
 <input type="checkbox" name="all"  id="all" onClick="javascript: alert('hi')">
 <input type="checkbox" name="all"  id="all" onclick="alert('hi')">
</form>

None of these work. I also tried radiobuttons, which also don't work. What gives?

A: Check if you have JavaScript disabled in your browser, running this example on jsFiddle does output the alert messages:

To enable JavaScript in Chrome

*

*Click the Chrome menu in the top right hand corner of your browser.

*Select Settings

*Click Show advanced settings

*Under the "Privacy" section, click the Content settings button.

*In the "Javascript" section, select "Allow all sites to run JavaScript (recommended)"

To enable JavaScript in Firefox
Click the Tools drop-down menu and select Options. Check the boxes next to Block pop-up windows, Load images automatically, and Enable JavaScript. Refresh your browser by right-clicking anywhere on the page and selecting Reload, or by using the Reload button in the toolbar.

As the poster mentioned above, if you have any other scripts running somewhere they might be throwing up errors and has nothing to do with JavaScript being disabled.


Q: Material properties databases (BRDF) I am working on a new Ray Tracing project which has to provide highly realistic simulation.
I have a problem with calculating reflection on target. I wanted to use the BRDF (bidirectional reflectance distribution function) model which gives information about diffuse and specular reflection to calculate how much energy was reflected from the target
What I wanted to ask:

*

*I was wondering if there are any databases with measurements of BRDF for different materials (including incoming light direction and outgoing direction) and for different wavelengths of the light source (the most interesting for me is the laser source 800-1600nm)?

*The second thing, do you know any good databases with material properties like: ambient, diffuse, specular, shininess and roughness of surface values.

What I've already found:
http://www.merl.com/brdf/
https://globe3d.sourceforge.io/g3d_html/gl-materials__ads.htm
http://www.cs.columbia.edu/CAVE/software/curet/
https://github.com/POV-Ray/povray/tree/master/distribution/include
But if I understand correctly all of them used a lamp as a light source and I don't see any references to the wavelengths of the light source. Moreover, there aren't any good values of material properties.
I am quite new in this so if you have any advice or I wrote something wrong, I will be grateful for any correction and information connecting with this topic.


Q: Bitrate by default for Audio Recording with MediaRecorder With java class MediaRecorder, you can record audio with encoder AMR NB (4.75 to 12.2 kbps sampled @ 8kHz)
I developed an app for a mobile with Android 2.2 and the bit rate used was 12.2 kbps by default, but I installed the same apk in a mobile with Android 2.3.3 and I think that bit rate changed to 4.75 kbps by default. Is it normal? The mobile used is Nexus One.
The codec lines for this issue are:
mrecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mrecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
mrecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

I tried to force MediaRecorder to use a specific bitrate with setAudioEncodingBitRate(int bitRate) but it didn´t work.
I don´t understand why bitrate has decreased.

A: setAudioEncodingBitRate(int bitRate) is not decreased, it is working since API 8 (2.2), and some encoding formats and frequencies, like AAC 44,1KHz, only since API 10 (2.3.3) :(


Q: How to define records count to a table that updated only when the table is updated
*

*I want to defint a view (or something else)
that will save a static variable of the table count.
I want this variable to be update only when the table is updated,
this way each time I call the view it will not calculate the count, just return the value.

in the past someone told me that "select count_bit(Id) from table1" will do the job.
is it right?

*

*I want to use the variable in mvc site using entity-framework . How do I do it?

A: Create a separate table to store the count value.
Create insert, update and delete triggers for table1, which calculates the new count and updates the count value.
But do you really need to do this? Are you having performance problems with select count(*) from table1? You know, triggers will slow down all update, delete and inserts a bit.

A: Just use a Select Count to  the  table ,even if you select just a column and count that for your rows or select the the whole table to count the complete table data...put  your count expression after your update is done .


Q: Why isn't xsl:for-each select="" working with this xml file? I am trying to display an xml file with an xsl stylesheet. I just canNOT seem to get it to work.
The feed I'm using is this: http://screamingdeals.tdn.travelscream.com/atom.xml
Here is an abbreviated copy of the xml for it:
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:ts="http://www.travelscream.com">
    <title type="text">Travelscream Deal Alerts</title>
    <updated>2012-08-08T11:09:44-06:00</updated>
    <id>http://screamingdeals.tdn.travelscream.com/</id>
    <link rel="alternate" type="text/html" hreflang="en" href="http://screamingdeals.tdn.travelscream.com"/>
    <link rel="self" type="application/atom+xml" href="http://screamingdeals.tdn.travelscream.com/atom.xml"/>
    <generator uri="http://screamingdeals.tdn.travelscream.com" version="1.0">screamingdeals.tdn.travelscream.com</generator>
    <entry>
        <title>New York City: Best Western President Hotel - $152</title>
        <link rel="alternate" type="text/html" href="http://screamingdeals.tdn.travelscream.com/a477908344.htm"/>
        <id>http://screamingdeals.tdn.travelscream.com/a477908344.htm</id>
        <updated>2012-08-08T11:09:44-06:00</updated>
        <published>2012-08-08T00:00:00-06:00</published>
        <author>
            <name>screamingdeals.tdn.travelscream.com</name>
            <uri>http://screamingdeals.tdn.travelscream.com</uri>
        </author>
        <content type="html" xml:base="screamingdeals.tdn.travelscream.com" xml:lang="en"> <table> <tr> <td valign="middle"> <img width="80" width="60"
            src="http://www.dealbase.com/assets/hotels/photos/000/002/953/icon.jpg"> </td> <td valign="top"> $152/night & up - Best Western President Hotel (New York City, NY) - 46%
            Off Travel Dates: Through Dec 31, 2012 </td> </tr> </table> </content>
        <ts:data>
            <ts:primarykey>477908344</ts:primarykey>
            <ts:location_data>
                <ts:location id="50" selected="0" airport_codes="EWR,JFK,LGA" type="dest">New York</ts:location>
                <ts:location id="55" selected="1" airport_codes="EWR,JFK,LGA" type="dest">New York City</ts:location>
                <ts:location id="199" selected="0" airport_codes="" type="dest">United States</ts:location>
                <ts:location id="288" selected="0" airport_codes="" type="dest">North America</ts:location>
                <ts:location id="524" selected="0" airport_codes="EWR,JFK,LGA,NYC" type="dest">Manhattan</ts:location>
                <ts:location id="525" selected="0" airport_codes="EWR,JFK,LGA,NYC" type="dest">Bronx</ts:location>
                <ts:location id="526" selected="0" airport_codes="EWR,JFK,LGA,NYC" type="dest">Brooklyn</ts:location>
                <ts:location id="527" selected="0" airport_codes="EWR,JFK,LGA" type="dest">Queens</ts:location>
                <ts:location id="528" selected="0" airport_codes="EWR,JFK,LGA" type="dest">Staten Island</ts:location>
                <ts:location id="613" selected="0" airport_codes="" type="dest">SoHo</ts:location>
            </ts:location_data>
            <ts:pkg_attributes>
                <ts:attribute id="3" type="TYPE">Honeymoon</ts:attribute>
                <ts:attribute id="40" type="MAIN">Hotel</ts:attribute>
                <ts:attribute id="62" type="DTYP">City</ts:attribute>
            </ts:pkg_attributes>
            <ts:deal_expires>2012-09-07T14:54:05-06:00</ts:deal_expires>
            <ts:deal_supplier>DealBase.com</ts:deal_supplier>
            <ts:feed_image>http://www.dealbase.com/assets/hotels/photos/000/002/953/icon.jpg</ts:feed_image>
            <ts:fullscreen_image/>
            <ts:price1>15200</ts:price1>
            <ts:alpha>0</ts:alpha>
            <ts:coord>
                <ts:lat>40.7606</ts:lat>
                <ts:long>-73.9864</ts:long>
                <ts:latlong>40.7606,-73.9864</ts:latlong>
            </ts:coord>
            <ts:desc>$152/night & up - Best Western President Hotel (New York City, NY) - 46% Off Travel Dates: Through Dec 31, 2012</ts:desc>
            <ts:tacomm/>
            <ts:direct>true</ts:direct>
            <ts:top>false</ts:top>
            <ts:traveldates>
                <ts:from>01/01/2050</ts:from>
                <ts:to>01/01/2050</ts:to>
            </ts:traveldates>
        </ts:data>
    </entry>
</feed>

the php page that loads up the stylesheet and tells it to transform the xml is coded thusly:
$xp = new XsltProcessor();
// create a DOM document and load the XSL stylesheet
$xsl = new DomDocument;
$xsl->load('deals_stylesheet.xsl');

// import the XSL styelsheet into the XSLT process
$xp->importStylesheet($xsl);

// create a DOM document and load the XML datat
$xml_doc = new DomDocument;
$xml_doc->load('http://screamingdeals.tdn.travelscream.com/atom.xml');

// transform the XML into HTML using the XSL file
if ($html = $xp->transformToXML($xml_doc)) {
    echo $html;
} else {
    trigger_error('XSL transformation failed.', E_USER_ERROR);
} // if

So far...so good. I'm not getting an error.
Here is the xsl file contents:
<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:template match="/">

                <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
                <title>Facebook Deals Page</title>

                        Title
                        ID

                    <xsl:for-each select="feed/entry">

                            <xsl:value-of select="title"/>
                            <xsl:value-of select="id"/>

                    </xsl:for-each>

    </xsl:template>
</xsl:stylesheet>

And here is a display of it not working: http://www.margaretpickarddesign.com/clients/travelscream/facebook_deals/facebook_rss.php
Looking at the xml structure, the node "feed" is followed by node "entry" which has child nodes "title" and "id". So why isn't it working? What am I missing?

A: Adding comment as an actual answer...
The ts prefixed namespace isn't the problem because you're not accessing any elements in that namespace. The problem is the default namespace (the xmlns with no prefix).
What you need to do is add xmlns:a="http://www.w3.org/2005/Atom" to xsl:stylesheet and use that prefix in your selects. (select="a:feed/a:entry", select="a:title", and select="a:id")
Also note that you can use any prefix, not just "a". The only thing that has to be the same is the namespace itself (http://www.w3.org/2005/Atom).


Q: typeof operator on Folder returns error In a google apps script function, I have a Folder parameter. So, this statement
Logger.log(typeof folder);

logs 'undefined' when the parameter is not supplied, which is right. But when a folder is supplied, I get this error:

Invalid JavaScript value of type $Proxy686. (line 15)

Not able to diagnose why. Need some help. Thanks.
Sanjay
Update: Here is the code reproducing the issue:
function typeOfTest() {

  var folders = DocsList.getAllFolders();
  for (var i = 0; i < folders.length; i++)
    Logger.log(typeof folders[i]);

};

A: In fact. I have the same behavior. I don't know either it is a bug or a feature. A possible workaround is to use the Folder's toString() function. Something like
function typeOfTest() {

  var folders = DocsList.getAllFolders();
  for (var i = 0; i < folders.length; i++)
    Logger.log(folders[i].toString());

};


Q: is there any way to add a custom library to jre there are some codes that I use very often in my programs and its kind of annoying to add it to my program every time I'm wondering if there is any way to solve this problem like adding


Q: AttributeError: 'NoneType' object has no attribute 'da' I am calling another program(script2.py) from the script1.py. The script1.py contains a button when i press it, it will start to execute the script2.py. I want to use a variable of script1 in script2. I have tried 2 way to fetch it but giving the error or the empty list. Please help me with this and let me know if any other information is needed. Thank you.
script1.py

class window2:  #i have tried to use d but even the value changes in the __init__function it is giving me a empty list in script2 print function
    d=[]
    def __init__(data):
        self.data=data
        window2.d=data
        data_copy()

def data_copy(): #so created this function to fetch da but giving the following error
    da=window2.d

script2.py

from script1 import data_copy
from script1 import window2

def view():
    print(window2.d) #giving empty list
    print(data_copy().da) #giving error

Error for data_copy:
Traceback (most recent call last):
  File "C:\Users\Desktop\Status\script2.py", line 59, in <module>
    view()
  File "C:\Users\Desktop\Status\script2.py", line 13, in view
    print(data_copy().da)
AttributeError: 'NoneType' object has no attribute 'da'

A: A common reason you have NoneType where you don't expect it is the assignment of an in-place operation on a mutable object. For example:
 mylist = mylist.sort()

The sort() method of a list sorts the list in-place, that is, mylist is modified. But the actual return value of the method is None and not the list sorted. So you've just assigned None to mylist. If you next try to do, say, mylist.append(1),
Python will give you this error.

A: You can try to create a function in the second script which takes your data as an argument and call it in the first script.
from script2 import view

class Window2:
    def __init__(self, data):  # init should take self, it is an instance of class
        self.data = data

window_2 = Window2('some data')  # creating instance

view(window_2.data)  # call function from script2

# script2

def view(data):
    print(data)

# > 'some data'