text:
Q: Which part of the JLS specifies that you can't cast from List extends List> to List>? (This question is inspired by this question, which I incorrectly answered.)
This code does not compile:
List<? extends List<Number>> list = new ArrayList<>();
List<List<Double>> anotherList = (List<List<Double>>) list;

Note that IntelliJ doesn't report any errors. It only fails to compile when I click "Run".
I understand why this doesn't compile on a conceptual level. list is a list of "something that extends List<Number>", and that "something" can never be List<Double>, because List<Double> is not a subtype of List<Number>, and because no type can implement both since they have the same erasure.
However, when I tried to follow the wording in the language specification to determine whether this cast is valid, I found that the language spec seems to say that this is a valid cast!
Here is my reasoning:
The cast fulfils all three requirements for there to be a Narrowing Reference Conversion from S (List<? extends List<Number>>) to T (List<List<Double>>).

5.1.6.1. Allowed Narrowing Reference Conversion
A narrowing reference conversion exists from reference type S to
reference type T if all of the following are true:

*

*S is not a subtype of T

*If there exists a parameterized type X that is a supertype of T, and a parameterized type Y that is a supertype of S, such that the
erasures of X and Y are the same, then X and Y are not provably
distinct (§4.5).

*One of the following cases applies:

*

*S and T are interface types.

*[...]

The first and third points are trivially true. To show that the second point is true, we take Collection<List<Double>> to be a parameterised super type of List<List<Double>>, and Collection<? extends List<Number>> to be a parameterised super type of List<? extends List<Number>>. They both erase to the same type Collection. Now we need to show that Collection<? extends List<Number>> and Collection<List<Double>> are not provably distinct (§4.5). The same argument also works for Iterable<...>.
Edit: I just realised that the supertypes of List<List<Double>> also include things like List<? extends List<Double>>, not just the superinterfaces of List. But I don't think that will invalidate this argument, as the point is that 1. out of X and Y there is at least one wildcard 2. the wildcard bounds/type arguments of X and Y are subtypes of each other.

Two parameterized types are provably distinct if either of the
following is true:

*

*They are parameterizations of distinct generic type declarations.

*Any of their type arguments are provably distinct.

Clearly, since they both erase to the same type, the first condition can't be true. We only need to show that the second condition is false.
In §4.5.1, the spec defines "type arguments are provably distinct":

Two type arguments are provably distinct if one of the following is
true:

*

*[...]

*One type argument is a type variable or wildcard, with an upper bound (from capture conversion (§5.1.10), if necessary) of S; and the
other type argument T is not a type variable or wildcard; and neither
|S| <: |T| nor |T| <: |S| (§4.8, §4.10).

(The other (trivially false) conditions are not shown for brevity) Here, S is List<Number> and T is List<Double>. Both |S| <: |T| and |T| <: |S| holds, as |S| and |T| are the same type. Yes, the subtype relation is reflexive, because the super type relation is reflexive (it's defined as the reflexive and transitive closure on the direct supertype relation).
Therefore the type arguments of Collection<? extends List<Number>> and Collection<List<Double>> are not provably distinct, and so List<? extends List<Number>> and List<List<Double>> are not provably distinct, and so there is (or should be) a conversion from List<? extends List<Number>> to List<List<Double>>!
Where is the error in my reasoning? Is there some other part of the spec that I missed?

A: Well, I'll just say it after Holger's confirmation and answer: JLS is underspecified (at least) at this location. There are some related JDK bugs that work around the same idea, noticeable this one, that directly hits your question via:

.... Otherwise, map wildcards and type variables to their upper bounds, and then test whether their erasures are related classes or interfaces (that is, one erased type is a subtype of the other)

Only to immediately start the next sentence with:

This is unsound...

So, that bug admits that JLS needs some corrections around this chapter(s).
What I have been struggling with too from your quotes of the JLS are two points:

*

*One type argument is a type variable or wildcard, with an upper bound (from capture conversion (§5.1.10), if necessary)...
I do know what capture conversion is, but I was not aware it might be optional to be performed (via that "if necessary"). I always thought that it is performed at each location, all the time.

*What is an upper bound from a captured conversion type?
In your case, is that upper bound List<Number> or List<?>, for example? In my understanding (or lack of precise JLS explanation), this could be understood either way.
All these (+ your great scrape of the JLS) makes me wonder about the correctness of the JLS here, especially since javac is not following these exact same rules.


text:
Q: Not able to Access Sitecore Mock Items (MS Fakes) through Sitecore Context in Unit Tests I am trying to write Unit Tests for an existing Sitecore Project on MVC5 that uses GlassMapper ORM and TDS. I have mocked the Sitecore Content Tree, Sitecore Context, Item Properties, Field Collections and Base Item using this extremely Beneficial Blog Post by Jeff Sulit.
https://oddeven.ch/blog/mocking-sitecore-using-ms-fakes/
Now the setup established in the above post (shared as link above.... please go through it before answering). I have kept the above setup inside a separate class file UnitTestAssist.cs in my Business Layer.
Now i have written the following basic unit test in which i create a fake item from my unit test Project and then access it through an object of UnitTestAssist class object by Sitecore.Context,Database.GetItem call which returns null.
namespace MySiteCoreUnitTest
{
[TestClass]
public class DataFetch
{
    IDisposable _context;
    readonly MySiteCoreUnitTest.UnitTestAssist _scFaker = new MySiteCoreUnitTest.UnitTestAssist();

    [TestInitialize]
    public void Initialize()
    {
        _context = ShimsContext.Create();
        _scFaker.Initialize();
    }

    [TestCleanup]
    public void Cleanup()
    {
        _context.Dispose();
    }

    [TestMethod]
    public void TestingDataFetch()
    {
        List<ShimField> lstfields = new List<ShimField>();

        //Arrange

        ShimField dummyField = new ShimField()
        {
            IDGet = () => ID.NewID,
            NameGet = () => "Ava_Title",
            ValueGet = () => "This is Crazy"
        };

         lstfields.Add(dummyField);

         var expectedItem = _scFaker.CreateFakeItem(_scFaker.Home, "sample item", (itemName, inputField) => { inputField = lstfields; });

        // Act:
        var actualItem = Context.Database.GetItem(expectedItem.Instance.Paths.FullPath);
        var actualItemFields = actualItem.Fields; // On Debugging i get the field i added forcefully inside **UnitTestAssist**.

        // Assert:
        Assert.AreEqual(expectedItem, actualItem);

    }

}
}

Here is the code that i have used for creating Mock Items.
namespace MySiteCoreUnitTest
{
public class UnitTestAssist
{
    private readonly Language ContextLanguage = Language.Parse("en");

    ShimItem CreateFakeItem(ShimItem parentItem, string name, Action<ShimItem, ShimTemplateItem, List<ShimField>> onItemCreating)
    {
        var id = ID.NewID;

        var item = new ShimItem()
        {
            // Assigning ID.NewID directly will return a new ID every time item.ID is called
            IDGet = () => id,
            KeyGet = () => name.ToLower(),
            NameGet = () => name,
            HasChildrenGet = () => false,
            ParentGet = () => parentItem,
            PathsGet = () =>
            {
                var path = (parentItem != null ? parentItem.Instance.Paths.Path : "") + "/" + name;

                return new ShimItemPath()
                {
                    PathGet = () => path,
                    FullPathGet = () => path,
                };
            },
            LanguageGet = () => ContextLanguage,
            VersionsGet = () => new ShimItemVersions() { CountGet = () => { return 1; } }
        };

        // Bind item to parent item
        if (parentItem != null)
        {
            var children = parentItem.Instance.HasChildren ? parentItem.Instance.Children.ToList() : new List<Item>();
            children.Add(item);

            parentItem.HasChildrenGet = () => true;
            parentItem.ChildrenGet = () => new ChildList(parentItem.Instance, children);
            parentItem.GetChildren = () => parentItem.Instance.Children;
        }

        // Start faking template and field collection
        var templateItem = new ShimTemplateItem();
        var field = new ShimField
        {

        };
        //var fields = new List<ShimField>();

        List<ShimField> fields = new List<ShimField>();

        //Arrange
        ShimField dummyField = new ShimField()
        {
            IDGet = () => ID.NewID,
            NameGet = () => "Ava_Title",
            ValueGet = () => "This is Crazy"
        };

        fields.Add(dummyField);

        // Call action to allow extension of item, template, and field collection faking
        onItemCreating(item, templateItem, fields);

        item.TemplateGet = () => templateItem;
        item.FieldsGet = () => CreateFakeFieldCollection(item, fields);

        return item;
    }

    // Create a dictionary to hold the field collection per item ID
    private Dictionary<ID, List<ShimField>> itemFields = new Dictionary<ID, List<ShimField>>();

    ShimFieldCollection CreateFakeFieldCollection(ShimItem item, List<ShimField> fields)
    {
        foreach (var field in fields)
            field.ItemGet = () => item;

        ShimField _newField = new ShimField();

        var fieldCollection = new ShimFieldCollection()
        {
            ItemGetString = (fieldName) =>
            {
                _newField = fields.SingleOrDefault(n => n.Instance.Name.Equals(fieldName, StringComparison.OrdinalIgnoreCase));
                return fields.SingleOrDefault(n => n.Instance.Name.Equals(fieldName, StringComparison.OrdinalIgnoreCase));

            }
        };

        Field testField = _newField;

        if (!itemFields.ContainsKey(item.Instance.ID))
              itemFields.Add(item.Instance.ID, fields);

        else
            itemFields[item.Instance.ID] = fields;

        fieldCollection.Bind(itemFields[item.Instance.ID]);

        return fieldCollection;
    }

    void FakeSitecoreContext()
    {
        ShimContext.LanguageGet = () => ContextLanguage;
        ShimContext.SiteGet = () => new ShimSiteContext()
        {
            ContentLanguageGet = () => ContextLanguage
        };

        Func<Func<Item, bool>, Item> getItem = (predicate) =>
        {
            Item result;

            return TryGetItem(this.Sitecore.Instance.Children, predicate, out result) ? result : null;
        };

        ShimContext.DatabaseGet = () => new ShimDatabase()
        {
            GetItemString = (path) => getItem(n => n.Paths.Path.Equals(path, StringComparison.OrdinalIgnoreCase)),
            GetItemStringLanguage = (path, lang) => getItem(n => n.Paths.Path.Equals(path) && (n.Language.Equals(lang) || n.Languages != null && n.Languages.Any(l => l.Name.Equals(lang.Name)))),
            GetItemID = (id) => getItem(n => n.ID.Equals(id)),
            GetItemIDLanguage = (id, lang) => getItem(n => n.ID.Equals(id) && (n.Language.Equals(lang) || n.Languages != null && n.Languages.Any(l => l.Name.Equals(lang.Name)))),
        };
    }

    bool TryGetItem(ChildList children, Func<Item, bool> predicate, out Item result)
    {
        result = null;

        if (children == null || !children.Any()) return false;

        result = children.FirstOrDefault(predicate);

        if (result != null) return true;

        var query = children.Where(n => n.HasChildren);

        if (!query.Any()) return false;

        foreach (var child in query.ToArray())
        {
            if (TryGetItem(child.Children, predicate, out result))
                return true;
        }

        return false;
    }

    void FakeBaseItem()
    {
        ShimBaseItem.AllInstances.ItemGetString = (baseItem, fieldName) =>
        {
            Item result;

            TryGetItem(Sitecore.Instance.Children, (n) => object.Equals(baseItem, n), out result);

            if (result != null)
            {
                var fields = itemFields[result.ID];

                var field = fields.FirstOrDefault(n => n.Instance.Name.Equals(fieldName, StringComparison.OrdinalIgnoreCase));

                if (field != null) return field.Instance.Value;
            }

            return string.Empty;
        };
    }

    public ShimItem Sitecore, Content, Site, Home;
    public void Initialize(Action<UnitTestAssist> onInitializing = null)
    {

        Sitecore = CreateFakeItem(null, "sitecore", (sitecore, someFieldSitecore) =>
        {
            Content = CreateFakeItem(sitecore, "content", (content, someFieldContent) =>
            {
                Site = CreateFakeItem(content, "site", (site, someFieldSite) =>
                {
                    Home = CreateFakeItem(site, "home", (home, someFieldHome) =>
                    {
                        // Add more items if you must to mimic your Sitecore tree
                    });
                });
            });
        });

        if (onInitializing != null)
            onInitializing(this);

        FakeBaseItem();
        FakeSitecoreContext();
    }

    public ShimItem CreateFakeItem(ShimItem parentItem, string name, Action<ShimItem,List<ShimField>> onItemCreating)
    {
        return CreateFakeItem(parentItem, name, (i, t, f) =>
        {
            if (onItemCreating != null)
                onItemCreating(i,f);
        });
    }
}
}

I have modified Jeff's code to be able to accept List<ShimField> as argument from the Unit Test but it still sends item field as null. Jeff can you help?

A: Hard to tell without seeing your actual code for the 'UnitTestHelperClass' class. Perhaps it'd be useful if you could share that as well.
UPDATE:
I've refactored your code to resolve your issue:
var expectedItem = _scFaker.CreateFakeItem(_scFaker.Home, "sample item", (itemName, inputField) => { inputField.AddRange(lstfields); });

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can one simulate nondeterministic finite transducers? A nondeterministic automaton can be simulated easily on an input string by just keeping track of the states the automaton is in, and how far in the input string it has gotten. But how can a nondeterministic transducer (a transducer, of course, can translate input symbols to output symbols, and give as output a string, not just a boolean value) be simulated? It seems that this is more complicated, since we need to keep track, somehow, of the output strings, which can be numerous because of the nondeterminism.

A: First of all, some theory. The following are distinct algebraic structures:

*

*generators (transition systems)

*acceptors (automata)

*transducers (machines)
The parenthesized terms are quite commonly found in the literature, alas they are wrongly used more often than not. These algebraic structures resemble each other notoriously much, and can be turned from one to another or hybrids via numerous small changes. But this should not distract from the fact that they ar fundamentally different:

*

*generators are a constructive representation of a language, i.e., a set of (finite or infinite) words. You non-deterministically traverse a generator and in doing so you produce all the words in that language.

*acceptors again are constructs for defining a set of words (language), but each represents an indicator function over all possible words (finite or infinite). So they map each word to a Boolean value (which could be appropriately extended to a finite or infinite output word, in an attempt to compare with transducers - there is though a distinguishing algebraic difference).

*a transducer represents a function mapping each admissible finite input word to a finite output word.
In the context of finite languages, the distinction between acceptors and transducers becomes less pronounced, because an acceptor can accept or not any finite word, irrespective of its length, thus it produces an output word for each such word. By catenation of the Boolean outputs from an acceptor, one can create a finite output word for each finite input word (i.e., by catenating the outputs from each prefix of the given input word). This attempt to bridge the two notions, though mechanistically correct, nonetheless distorts the notions involved.
In the context of infinite-word languages, the distinction is clearer. An infinite-word automaton cannot produce output for finite prefixes of a given (infinite) input word. This restriction is the consequence of infinite-word acceptance being defined over the entire (infinite) word. As a result, acceptors map each input word to a Boolean value, or output word if such a viewpoint is preferred. In contrast, transducers (machines) map each finite prefix of any input word, to a finite output word of equal length. For this reason, they are called sequential machines, because they react step-by-step.
There are two different types of transducers:

*

*Mealy machines

*Moore machines
A Moore machine can be represented by a Mealy machine. Not every Mealy machine is representable by a Moore machine. The literature is typically wrong in defining and comparing these two types of transducers, please refer to the original publications for the correct definitions.
So both definitions are deterministic. There is a reason for this restriction to determinism: a transducer is used to control a system, so we want to know deterministically what the next control action to apply should be. This has led to deterministic transducers becoming the standard in the literature.
However, non-deterministic transducers can also be useful, e.g., as compact representations of multiple strategies. However, when they are executed, it makes sense to only follow a single path and produce a single output word, not multiple simultaneously (as is the case for copies of non-deterministic acceptors spawned during their execution).
Therefore it becomes clear that the non-deterministic simulation of a transducer does not correspond to its intended use. It represents a set of alternative strategies (that can also be mixed, if one does not determinize in a fixed way during each single play).
So indeed you would have to create an (ever expanding) tree of the possible output words that quickly blows up. This tree is essentially the unfolding of the generator (transition system) that you would get by stripping the transducer of its input annotation.

A: Basically you do the same as for NFAs but this time instead of returning true or false you add the output to an output set. Here's a bit of pseudocode:
function rec(in, current_state, pos, out)
 if(current_state.isFinal && pos == in.length) out_set += out

 for(t <- lambda transition going out from current_state)
  rec(in, t.destination, pos, out + t.output_symbol)

 for(t <- transition going out from current_state for symbol in(pos)
  rec(in, t.destination, pos+1, out + t.output_symbol)


text:
Q: jquery running same function on multiple elements relatives to 'This' $(".column a").mouseenter(function() {
var color_column=$(this).closest('.column').children('.coloured-strip').css('color');

$(this).siblings('p').animate({color:color_column},2000);
$(this).animate({color:color_column},2000);
});

There's any way I can group the two animate functions into one since they're identical?
thanks
luca

A: Sure, just use .add():
$(this).siblings('p').add(this).animate({color:color_column},2000);

A: You can use the andSelf() method:
$(this).siblings('p').andSelf().animate({color:color_column},2000);

A: Instead of:
$(this).siblings('p').animate({color:color_column},2000);
$(this).animate({color:color_column},2000);

You can do:
$(this).siblings('p').add(this).animate({color:color_column},2000);

See the documentation for .add().


text:
Q: How can you speed up FileOutputStream and FileOutputStream close()? In my java application, I create threads where large files are copied using FileOutputStream and FileInputStream wrapped in BufferedInputStream and BufferedOutputStream. After a file is copied, I try to call close() for the buffered input/output streams but this takes several minutes on Ubuntu. When this is run on OS X, the streams close immediately. Is there a way to speed up this process?

A: On linux, a close() attempts to commit the data to disk.  This is much, much faster if you have an SSD (as much as 1000x faster) if you have a spinning disk you can write to about 40 files per second (even if very small) If you have an SSD this would be about 20,000 per second on a laptop.


text:
Q: Jest mocking / spying on Mongoose chained (find, sort, limit, skip) methods What I am looking to do:

*

*spy on the method calls chained onto find() used in a static Model method definition

*

*chained methods: sort(), limit(), skip()
Sample call

*

*goal: to spy on the arguments passed to each of the methods in a static Model method definition:
... static method def
const results = await this.find({}).sort({}).limit().skip();
... static method def

*what did find() receive as args: completed with findSpy

*what did sort() receive as args: incomplete

*what did limit() receive as args: incomplete

*what did skip() receive as args: incomplete

What I have tried:

*

*the mockingoose library but it is limited to just find()

*I have been able to successfully mock the find() method itself but not the chained calls that come after it

*

*const findSpy = jest.spyOn(models.ModelName, 'find');

*researching for mocking chained method calls without success

A: I was not able to find a solution anywhere. Here is how I ended up solving this. YMMV and if you know of a better way please let me know!
To give some context this is part of a REST implementation of the Medium.com API I am working on as a side project.
How I mocked them

*

*I had each chained method mocked and designed to return the Model mock object itself so that it could access the next method in the chain.

*The last method in the chain (skip) was designed to return the result.

*In the tests themselves I used the Jest mockImplementation() method to design its behavior for each test

*All of these could then be spied on using expect(StoryMock.chainedMethod).toBeCalled[With]()
const StoryMock = {
  getLatestStories, // to be tested
  addPagination: jest.fn(), // already tested, can mock
  find: jest.fn(() => StoryMock),
  sort: jest.fn(() => StoryMock),
  limit: jest.fn(() => StoryMock),
  skip: jest.fn(() => []),
};

Static method definition to be tested
/**
 * Gets the latest published stories
 * - uses limit, currentPage pagination
 * - sorted by descending order of publish date
 * @param {object} paginationQuery pagination query string params
 * @param {number} paginationQuery.limit [10] pagination limit
 * @param {number} paginationQuery.currentPage [0] pagination current page
 * @returns {object} { stories, pagination } paginated output using Story.addPagination
 */
async function getLatestStories(paginationQuery) {
  const { limit = 10, currentPage = 0 } = paginationQuery;

  // limit to max of 20 results per page
  const limitBy = Math.min(limit, 20);
  const skipBy = limitBy * currentPage;

  const latestStories = await this
    .find({ published: true, parent: null }) // only published stories
    .sort({ publishedAt: -1 }) // publish date descending
    .limit(limitBy)
    .skip(skipBy);

  const stories = await Promise.all(latestStories.map(story => story.toResponseShape()));

  return this.addPagination({ output: { stories }, limit: limitBy, currentPage });
}

Full Jest tests to see implementation of the mock
const { mocks } = require('../../../../test-utils');
const { getLatestStories } = require('../story-static-queries');

const StoryMock = {
  getLatestStories, // to be tested
  addPagination: jest.fn(), // already tested, can mock
  find: jest.fn(() => StoryMock),
  sort: jest.fn(() => StoryMock),
  limit: jest.fn(() => StoryMock),
  skip: jest.fn(() => []),
};

const storyInstanceMock = (options) => Object.assign(
  mocks.storyMock({ ...options }),
  { toResponseShape() { return this; } }, // already tested, can mock
);

describe('Story static query methods', () => {
  describe('getLatestStories(): gets the latest published stories', () => {
    const stories = Array(20).fill().map(() => storyInstanceMock({}));

    describe('no query pagination params: uses default values for limit and currentPage', () => {
      const defaultLimit = 10;
      const defaultCurrentPage = 0;
      const expectedStories = stories.slice(0, defaultLimit);

      // define the return value at end of query chain
      StoryMock.skip.mockImplementation(() => expectedStories);
      // spy on the Story instance toResponseShape() to ensure it is called
      const storyToResponseShapeSpy = jest.spyOn(stories[0], 'toResponseShape');

      beforeAll(() => StoryMock.getLatestStories({}));
      afterAll(() => jest.clearAllMocks());

      test('calls find() for only published stories: { published: true, parent: null }', () => {
        expect(StoryMock.find).toHaveBeenCalledWith({ published: true, parent: null });
      });

      test('calls sort() to sort in descending publishedAt order: { publishedAt: -1 }', () => {
        expect(StoryMock.sort).toHaveBeenCalledWith({ publishedAt: -1 });
      });

      test(`calls limit() using default limit: ${defaultLimit}`, () => {
        expect(StoryMock.limit).toHaveBeenCalledWith(defaultLimit);
      });

      test(`calls skip() using <default limit * default currentPage>: ${defaultLimit * defaultCurrentPage}`, () => {
        expect(StoryMock.skip).toHaveBeenCalledWith(defaultLimit * defaultCurrentPage);
      });

      test('calls toResponseShape() on each Story instance found', () => {
        expect(storyToResponseShapeSpy).toHaveBeenCalled();
      });

      test(`calls static addPagination() method with the first ${defaultLimit} stories result: { output: { stories }, limit: ${defaultLimit}, currentPage: ${defaultCurrentPage} }`, () => {
        expect(StoryMock.addPagination).toHaveBeenCalledWith({
          output: { stories: expectedStories },
          limit: defaultLimit,
          currentPage: defaultCurrentPage,
        });
      });
    });

    describe('with query pagination params', () => {
      afterEach(() => jest.clearAllMocks());

      test('executes the previously tested behavior using query param values: { limit: 5, currentPage: 2 }', async () => {
        const limit = 5;
        const currentPage = 2;
        const storyToResponseShapeSpy = jest.spyOn(stories[0], 'toResponseShape');
        const expectedStories = stories.slice(0, limit);

        StoryMock.skip.mockImplementation(() => expectedStories);

        await StoryMock.getLatestStories({ limit, currentPage });
        expect(StoryMock.find).toHaveBeenCalledWith({ published: true, parent: null });
        expect(StoryMock.sort).toHaveBeenCalledWith({ publishedAt: -1 });
        expect(StoryMock.limit).toHaveBeenCalledWith(limit);
        expect(StoryMock.skip).toHaveBeenCalledWith(limit * currentPage);
        expect(storyToResponseShapeSpy).toHaveBeenCalled();
        expect(StoryMock.addPagination).toHaveBeenCalledWith({
          limit,
          currentPage,
          output: { stories: expectedStories },
        });
      });

      test('limit value of 500 passed: enforces maximum value of 20 instead', async () => {
        const limit = 500;
        const maxLimit = 20;
        const currentPage = 2;
        StoryMock.skip.mockImplementation(() => stories.slice(0, maxLimit));

        await StoryMock.getLatestStories({ limit, currentPage });
        expect(StoryMock.limit).toHaveBeenCalledWith(maxLimit);
        expect(StoryMock.addPagination).toHaveBeenCalledWith({
          limit: maxLimit,
          currentPage,
          output: { stories: stories.slice(0, maxLimit) },
        });
      });
    });
  });
});

A:

jest.spyOn(Post, "find").mockImplementationOnce(() => ({
    sort: () => ({
        limit: () => [{
            id: '613712f7b7025984b080cea9',
            text: 'Sample text'
        }],
    }),
}));

A: Here is how I did this with sinonjs for the call:
 await MyMongooseSchema.find(q).skip(n).limit(m)

It might give you clues to do this with Jest:
sinon.stub(MyMongooseSchema, 'find').returns(
    {
        skip: (n) => {
            return {
                limit: (m) => {
                    return new Promise((
                        resolve, reject) => {
                            resolve(searchResults);
                        });
                }
            }
        }
    });

sinon.stub(MyMongooseSchema, 'count').resolves(searchResults.length);

A: This worked for me:
jest.mock("../../models", () => ({
     Action: {
         find: jest.fn(),
     },
}));

Action.find.mockReturnValueOnce({
    readConcern: jest.fn().mockResolvedValueOnce([
        { name: "Action Name" },
    ]),
});

A: All the above didn't work in my case, after some trial and error this worked for me:
const findSpy = jest.spyOn(tdataModel.find().sort({ _id: 1 }).skip(0).populate('fields'), 'limit')
NOTE: you need to mock the query, in my case I use NestJs:
I did the following:
 find: jest.fn().mockImplementation(() => ({
          sort: jest.fn().mockImplementation((...args) => ({
            skip: jest.fn().mockImplementation((...arg) => ({
              populate: jest.fn().mockImplementation((...arg) => ({
                limit: jest.fn().mockImplementation((...arg) => telemetryDataStub),
              })),
            })),
          })),
        })),
        findOne: jest.fn(),
        updateOne: jest.fn(),
        deleteOne: jest.fn(),
        create: jest.fn(),
        count: jest.fn().mockImplementation(() => AllTelemetryDataStub.length),

A: for me it worked like this:
AnyModel.find = jest.fn().mockImplementationOnce(() => ({
 limit: jest.fn().mockImplementationOnce(() => ({
       sort: jest.fn().mockResolvedValue(mock)
    }))
}))


text:
Q: My GUI repeat many times and can't input or click in netbeans I have a problem.
I coding JAVA MVC in Netbeans
When I run it, JFrame Show multiple windows and can't input or click
Image while run code
this is my code
View:
public StudentView() {
    initComponents();

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new StudentView().setVisible(true);

        }
    });
}

Controller:
public StudentController(Student model, StudentView view){
    this.model = model;
    this.view = view;
}

public void initController() {
    view.getBtnOKsing().addActionListener(e -> getText());
}
public void getData(){
    dataStd = model.getStudentNo();
    dataPass = model.getPass();
}
public void getText(){
    stdNo = view.getTextstd();
    pass = view.getTextpass();
    //singin();
}

in my program don't have loop.

A: change
new StudentView().setVisible(true);

to
setVisible(true).


text:
Q: Necklace Application I created a Necklace class with a static method that determines how many numbers the necklace sequence must generate to return to the original two numbers. Also the method called howLong that takes as parameters the first two items in the sequence. It generates a necklace sequence and return how many numbers must be generated to return to the original two numbers. I did not count the first two numbers in my total but did count them the final time they are generated. As you can see the code below I am printing something in the howLong method System.out.print(two + " ");, but it should not print anything. It should use a main method that calls howLong and prints the results. How can I do it?
import java.util.Scanner;
public class Necklace {
    public static int howLong (int firstStarting, int secondStarting) {

        int sum = 0;
        int temp;
        int one = firstStarting;
        int two = secondStarting;

        do{
            temp = (one + two) % 10;
            one = two;
            two = temp;
            System.out.print(two + " ");
        }while (two != secondStarting || one != firstStarting);

        return (sum);
    }
    public static void main (final String[] args) {

        int total;
        int first;
        int sec;

        Scanner in = new Scanner (System.in);
        System.out.print("Enter the first starting number: ");
        first = in.nextInt();

        System.out.print("Enter the second starting number: ");
        sec = in.nextInt();

        total = howLong (first, sec);
    }
}


text:
Q: Different mesh visualization WebGL I'm wondering why the mesh in lesson 10 looks more three-dimensional then mine. My meshes look like they have no surface and no depth. Here is an example picture:

Any suggestions? I don't see if there is a difference in loading the meshes (xtk's version compared to mine). I think it doesn't depend on the (type of) data because in ParaView it looks more three-dimensional.

A: It is because your mesh files have no normals.
Paraview will create normals if you don't provide it - not XTK -
You can generate normals for your meshes fairly easily with VTK:
http://www.vtk.org/doc/nightly/html/classvtkPolyDataNormals.html
1-vtkPolyDataReader
2-vtkPolyDataNormals
3-vtkPolyDataWriter
Maybe you can export the meshes from Paraview or Slicer? Maybe the exported meshes will contain the normals...


text:
Q: Update Query in SQL with numeric pattern in MS Access Good Day All,
I need assistance in an creating an update query that groups my data.
The data in my table is actually spatial in nature and can be thought of a matrix that is 10 columns by 5 rows.  I have the ObjectID, Row and Column but I want the column DesiredResult which is a 2x2 grouping of the rows & columns.
So the R,Cs of 1,1 1,2, 2,1 and 2,2, will have a DesiredResult of 1 while the 1,3 1,4 2,3 2,4 will have a DesiredResult of 2 and so on (see below for an example)  ....
I was able to create the R and C columns using a combination of Quotient & Mod so I assume I would do somethign similar but I am stuck.  How would I go about this query in MS Access ?
 ObjectID   R   C   DesiredResult
 1            1 1   1
 2            1 2   1
 3            1 3   2
 4            1 4   2
 5            1 5   3
 6            1 6   3
 7            1 7   4
 8            1 8   4
 9            1 9   5
 10           1 10  5
 11           2 1   1
 12           2 2   1
 13           2 3   2
 14           2 4   2
 15           2 5   3
 16           2 6   3
 17           2 7   4
 18           2 8   4
 19           2 9   5
 20           2 10  5
 21           3 1   6
 22           3 2   6
 23           3 3   7
 24           3 4   7
 25           3 5   8
 26           3 6   8
 27           3 7   9
 28           3 8   9
 29           3 9   10
 30           3 10  10
 31           4 1   6
 32           4 2   6
 33           4 3   7
 34           4 4   7
 35           4 5   8
 36           4 6   8
 37           4 7   9
 38           4 8   9
 39           4 9   10
 40           4 10  10
 41           5 1   11
 42           5 2   11
 43           5 3   12
 44           5 4   12
 45           5 5   13
 46           5 6   13
 47           5 7   14
 48           5 8   14
 49           5 9   15
 50           5 10  15

A: Something like ... ?
SELECT a.Row, a.Col, Col\2 AS D1, Col Mod 2 AS D2, [D1]+[D2] AS Desired
FROM  table  AS a
ORDER BY a.Row, a.Col;

A: Remou had a close approximation but it turns out this gives me what I need.  I needed both a row and a column index.
 SELECT ObjectID, R, C,
   Int(([C]-1)/2) AS ColIndex,
   Int(([R]-1)/2) AS RowIndex,
   [RowIndex]*5+[ColIndex]+1 AS DesiredResult
 FROM Testing
 ORDER BY ObjectID

The key in the query is that there is the number 2 in both the Column & Row Index (which is the grouping size) and the number 5 is used in Desired Result and represents the Number of Row cells.
Thanks !


text:
Q: Double pointer 2-d array declaration int** seq=new int* [n]; int n,q;
cin>>n>>q;
int** seq=new int* [n];          // what is the meaning of this ?

I have been trying to understand this array declaration for half an hour but the
int* [n] is really confusing me a lot.
Is there a more convenient way to write this declaration ?
How can I have such type of declaration in cpp ?

A:
Is there a more convenient way to write this declaration ?

The idiomatic way to declare that pointer array in c++ would be
int n,q;
cin>>n>>q;
std::vector<int*> seq(n);

Though it's questionable why int* pointers need to be stored in the array.

A: A int* is a pointer (I assume you know those).
 So int*[n] is an array of length n containing pointers on integers.
What confuses people most, is that variables containing arrays actually are pointers in C++. Because of that, the variable's type, we store int*[n] to, has to be int**. The pointer points at the first element of the array, and e.g. seq[2] would be compiled into *(seq+2). A array is not an object but a construct in memory the computer doesn't know about at runtime.


text:
Q: Multiple static libraries, swizzling and dispatch_once I have a main application, let's call it App.
It links two static libraries, StatLib1 and StatLib2.
StatLib1 links the StatLib2 library.
As you see, the StatLib2 library is linked twice.

In a category of the StatLib2 library, I'm doing some swizzling:
+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"test");

        [self itk_swizzleInstanceMethodWithSelector:@selector(someMethod:)
                                    withNewSelector:@selector(itk_someMethod:)];
    });
}

test is logged twice, meaning the methods will be swizzled back to original.
I'm sure that this is the issue, since when I remove the link of StatLib2 on the App target, this does not happen.

*

*First of all, why does this happen?

*How can I fix this, without actually removing the link to StatLib2 on the App target?

A: First of all, a static library is just an archive of object files, so
 you cannot really link one static library against another static library.
What probably happens is that all objects of StatLib2 are copied into
StatLib1. Later, when the application  is linked, another copy of StatLib2
is added to the executable.
So you end with two "instances" of the load method, each with its own
static dispatch_once_t onceToken. Both methods are called when the class
is loaded, and each one executes its own dispatch_once() block.
This is also shown by the output of
NSLog(@"test: class=%p, token=%p", self, &onceToken)

test: class=0x7fff7c76cdc8, token=0x100021f60
test: class=0x7fff7c76cdc8, token=0x100021f98

The class is the same (because it is a category for the same class), but the
onceToken is different.
As a solution, you should only link the final executable against both
static libraries.


text:
Q: Open Profinite Subgroup $\Rightarrow$ Profinite Group I'm currently struggling with profinite groups. I'm not able to solve many practice exercises. I was wondering if someone could give me some hints on the following: if $G$ is a compact group and $H$ is an open profinite subgroup show $G$ is profinite.

A: You have to show that $G$ is Hausdorff, compact and totally disconnected
https://en.wikipedia.org/wiki/Profinite_group#Definition
Compact by definition.
Hausdorff, let $x,y\in G$, $L_x$ the map defined by $L_x(u)=xu$. $L_x(H)$ is an open neighborhood of $x$. If $y\in L_x(H)$, $y=xh,h\in H$ since $H$ is Hausdorff, there exists neighborhoods $U$ of $1$ and $V$ of $h$ such that $U\cap V$ is empty. $U$ and $V$ are also open neighborhood of $1$ and $h$ in $G$ since $U$ is open. This implies that $L_x(U)$ is an open neighborhood of $x$ and $L_x(V)$ is an open neighborhood of $y$ such that $L_x(U)\cap L_x(V)$ is empty.
If $y\neq L_x(H)$, since $H$ is profinite, it is compact, so $L_x(H)$ is compact as the image of a compact set by a continuous map. This implies that $W$ the complementary subset of $L_x(H)$ is open. We have $y\in W$ and $W\cap L_x(H)$ is open.
Totally disconnected.
Let $x\in G$ and $C$ the connected component of $x$ in $U$. $C'=L_{x^{-1}}(C)\cap H$ is  open and closed since $H$ and $C$ are open and closed, it implies that $L_{x^{-1}}(C)\cap H$ is the connected component of $1$ in $H$ and in $G$, so $C'=\{1\}$ since $H$ is totally disconnect. This implies that $C=\{x\}$.


text:
Q: How to execute an Azure table storage query async? client version 4.0.1 Want to execute queries Async on Azure Storage Client Version 4.0.1
There is NO method ExecuteQueryAsync()..
I am missing something? Should we continue to use the ExecuteQuerySegmentedAsync still?
Thanks.

A: I end up making an extension method to use ExecuteQuerySegmentedAsync.
I am not sure whether this solution is optimal, if anybody has any comment please don't hesitate.
public static async Task<IList<T>> ExecuteQueryAsync<T>(this CloudTable table, TableQuery<T> query, CancellationToken ct = default(CancellationToken), Action<IList<T>> onProgress = null) where T : ITableEntity, new()
    {

        var items = new List<T>();
        TableContinuationToken token = null;

        do
        {

            TableQuerySegment<T> seg = await table.ExecuteQuerySegmentedAsync<T>(query, token);
            token = seg.ContinuationToken;
            items.AddRange(seg);
            if (onProgress != null) onProgress(items);

        } while (token != null && !ct.IsCancellationRequested);

        return items;
    }

A: When table query contains take clause specified solution will return more items than requested by query. Small change of while expression will solve that problem.
public static async Task<IList<T>> ExecuteQueryAsync<T>(this CloudTable table, TableQuery<T> query, CancellationToken ct = default(CancellationToken), Action<IList<T>> onProgress = null) where T : ITableEntity, new()
{
    var runningQuery = new TableQuery<T>()
    {
        FilterString = query.FilterString,
        SelectColumns = query.SelectColumns
    };

    var items = new List<T>();
    TableContinuationToken token = null;

    do
    {
        runningQuery.TakeCount = query.TakeCount - items.Count;

        TableQuerySegment<T> seg = await table.ExecuteQuerySegmentedAsync<T>(runningQuery, token);
        token = seg.ContinuationToken;
        items.AddRange(seg);
        if (onProgress != null) onProgress(items);

    } while (token != null && !ct.IsCancellationRequested && (query.TakeCount == null || items.Count < query.TakeCount.Value));

    return items;
}

EDITED: Thanks to a suggestion from PaulG, corrected the issue with result count when query contains take clause and ExecuteQuerySegmentedAsync returns items in several passes.

A: This is in addition on to @JoseCh.'s answer.
Here is an extension method which allows you to specify an EntityResolver:
public static async Task<IList<TResult>> ExecuteQueryAsync<T, TResult>(this CloudTable table, TableQuery query, EntityResolver<TResult> resolver, Action<IList<TResult>> onProgress = null, CancellationToken cancelToken = default(CancellationToken))
            where T : ITableEntity, new()
{
    var items = new List<TResult>();
    TableContinuationToken token = null;

    do
    {
        TableQuerySegment<TResult> seg = await table.ExecuteQuerySegmentedAsync(query: query, resolver: resolver, token: new TableContinuationToken(), cancellationToken: cancelToken).ConfigureAwait(false);
        token = seg.ContinuationToken;
        items.AddRange(seg);
        onProgress?.Invoke(items);
     }
     while (token != null && !cancelToken.IsCancellationRequested);
         return items;
     }
}

It can be used if you only want to return the result set of a single column in storage:
// maps to a column name in storage
string propertyName = nameof(example.Category);

// Define the query, and select only the Category property.
var projectionQuery = new TableQuery().Select(new string[] { propertyName });

// Define an entity resolver to work with the entity after retrieval.
EntityResolver<string> resolver = (pk, rk, ts, props, etag) => props.ContainsKey(propertyName) ? props[propertyName].StringValue : null;

var categories = (await someTable.ExecuteQueryAsync<DynamicTableEntity, string>(query: projectionQuery, resolver: resolver).ConfigureAwait(false)).ToList()


text:
Q: How can I create an fscanf format string to accept white space and comma (,) tokenization I've got some analysis code (myprog) that sucks in data using the following:
 if(5 == fscanf(in, "%s%lf%f%f%f", tag, & sec, & tgt, & s1, & s2))

which works just fine.  But in the situation where I've got data files that are separated by commas, I'm currently doing something like:
 sed 's/,/ /g' data | myprog

Can I modify the format string in the fscanf() function to accept both delimitation formats?

A: fscanf(in, "%[^, ]%*[, ]%lf%*[, ]%f%*[, ]%f%*[, ]%f", tag, &sec, &tgt, &s1, &s2)

Should work?

A: What about this:
char tmp;
fscanf(in, "%s%c%lf%c%f%c%f%c%f", tag,  &tmp, & sec,  &tmp,& tgt,  &tmp,& s1, &tmp, & s2)
If you are not going to care what single character delimits your values, just read it and store it in a throw-away variable.


text:
Q: Unable to transfer amount to bank account of user in stripe I want to transfer money to user bank account.
I have created "managed account" for that user and in that manage account there are multiple bank accounts. So How do I transfer money from stripe balance to users bank account?

A: 1.First transfer money to Managed Account.
2.Set key of managed account of bank account in which you need to transfer amount using following,
stripe.setApiKey("Set secret key of managed account");
3.Then transfer money to bank account using bank account id.
stripe.transfers.create({
       amount: "amount to be transferred",
       currency: "usd",
       destination: "Bank account id",
       statement_descriptor: "Transfer from Managed Account Stripe balance to Managed Account Bank Account"
                    })

A: By default a managed account will have automatic transfers enabled. This means that every day Stripe will go through, see if an account has available funds and if so create a transfer for that user to their bank account.
If you have disabled automatic transfers for an account, they would be on manual transfers, where the transfers have to be manually created via the api for that account
For instance the code below would transfer $10 to the connected account's bank account from their available balance.
curl https://api.stripe.com/v1/transfers \
   -u {PLATFORM_SECRET_KEY}: \
   -H "Stripe-Account: {CONNECTED_STRIPE_ACCOUNT_ID}" \
   -d amount=1000 \
   -d currency=usd \
   -d recipient=self

I'd also recommend reading Stripe's API documentation on this: https://stripe.com/docs/connect/bank-transfers


text:
Q: No command found with name "focus" When i click on textinput, there is this error. I danot know why
click to view image

A: Check if there isn't any code of yours trying to trigger focus on an element that doesn't support focus.
For example, in my case, I got this error when setting the autoFocus prop on an element different than TextInput, e.g. a Button or a View.

A: I encountered a similar problem while using react native, with an accompanying version mismatch problem between js (0.62) and react native (0.63). The app I am developing also shows bad keyboard behavior for TextInput. Solved all problems by downgrade react native to 0.62.0, like so:

*

*change the react native version # in package.json to 0.62.0

*$ rm -rf node_modules yarn.lock

*$ yarn install

So it's the version mismatch bug causing the keyboard focus issue in my case. Good luck!


text:
Q: Invalid postback or callback argument (HiddenField and container Visible=false) I've not found answers that matched my circumstances, so I'm posting an answered question hoping it will help others.
I was getting the error

Invalid postback or callback argument.  Event validation is enabled
  using  in configuration or <%@
  Page EnableEventValidation="true" %> in a page.  For security
  purposes, this feature verifies that arguments to postback or callback
  events originate from the server control that originally rendered
  them.  If the data is valid and expected, use the
  ClientScriptManager.RegisterForEventValidation method in order to
  register the postback or callback data for validation.

   at System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument)
   at System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument)
   at System.Web.UI.WebControls.HiddenField.LoadPostData(String postDataKey, NameValueCollection postCollection)
   at System.Web.UI.WebControls.HiddenField.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection)
   at System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad)
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

I've got a Databound ListView (with a few 100s rows), with buttons on each row. The buttons bring a popup. The popup has dropdownlists and other controls doing asynchronous postbacks. I need to make sure I do asynchronous postbacks to avoid refreshing my big table.
I get the error when I click the button on one row, then change a dropdownlist inside the popup which fires a postback (selected item changed). Boom.
Here's the markup for a reduced sample, without popup and javascript at all! It still exhibits the problem. Click twice on a button in a row to get the error.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestPopupAsynchPostback.Default" %>
<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">
        <asp:ScriptManager ID="scriptMgr" runat="server" ScriptMode="Debug" EnablePartialRendering="true"
            EnableScriptGlobalization="true" EnableScriptLocalization="true" EnablePageMethods="true"/>
        <asp:ObjectDataSource ID="ListDataSource" runat="server" SelectMethod="List" TypeName="TestPopupAsynchPostback.Default" />
        <asp:Label runat="server" ID="PageLabel"></asp:Label>
        <asp:ListView ID="EL" runat="server" DataSourceID="ListDataSource" OnItemDataBound="EntityList_OnItemDataBound">
            <LayoutTemplate>

            </LayoutTemplate>
            <ItemTemplate>

                        <asp:Label ID="Lbl" runat="server" EnableViewState="false" />

                        <button runat="server" type="button" id="ReportingButton" enableviewstate="false" onserverclick="ReportingButton_OnClick" causesvalidation="false">click</button>

                <%-- Fix part 1: Change SpecialRow  visible = true--%>

                        <asp:Label ID="Lbl2" runat="server" EnableViewState="false" />
                        <asp:HiddenField runat="server" ID="fn_hid" />

            </ItemTemplate>
        </asp:ListView>
    </form>

Here's the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace TestPopupAsynchPostback
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ScriptManager sm = ScriptManager.GetCurrent(Page);
            PageLabel.Text = DateTime.UtcNow.ToString() + " IsPostBack:" + IsPostBack + " IsInAsyncPostBack:" + (sm == null ? "" : sm.IsInAsyncPostBack.ToString());
        }

        protected override void Render(HtmlTextWriter writer)
        {
            ScriptManager sm = ScriptManager.GetCurrent(this.Page);
            if (sm != null)
            {
                foreach (ListViewDataItem row in EL.Items)
                {
                    HtmlButton reportingButton = row.FindControl("ReportingButton") as HtmlButton;
                    if (reportingButton != null)
                        sm.RegisterAsyncPostBackControl(reportingButton);
                }
            }
            base.Render(writer);
        }

        public IList<string> List()
        {
            return (new string[] { "ONE", "TWO"}).ToList();
        }

        protected void ReportingButton_OnClick(object sender, EventArgs e)
        {
            //Do something useful here, for now, just a postback event
        }

        protected void EntityList_OnItemDataBound(object sender, ListViewItemEventArgs e)
        {
            Label lbl = e.Item.FindControl("Lbl") as Label;
            Label lbl2 = e.Item.FindControl("Lbl2") as Label;
            lbl.Text = lbl2.Text = e.Item.DataItem.ToString();

            HtmlTableRow specialRow = e.Item.FindControl("SpecialRow") as HtmlTableRow;
            if (e.Item.DataItemIndex%2 == 0)
            {
                HiddenField fn_hid = e.Item.FindControl("fn_hid") as HiddenField;
                fn_hid.Value = "test1";
                specialRow.Visible = true;
            }
            //Fix part 2: set SpecialRow Visible = false in code behind
            //else
            //    specialRow.Visible = false;
        }
    }
}

A: I initially thought my javascript was at fault as I am modifying things with it. However, the process of creating a sample page has helped me find the problem.
It turns out it has nothing to do with the javascript or the popup. It's to do with a HiddenField contained inside a TR HtmlControl (asp.net server side control) with Visible=false IN THE MARKUP. I then use the code behind to set Visible=true when I need to in OnItemDataBound event.
This is what is causing the error for me: It seems that because the container (the TR SpecialRow) is Visible=false, I guess something is not rendered. I then come along in OnItemDataBound, decide that this row must be shown, and set Visible=true and set the value of my HiddenField. Boom.
If I remove the markup for the hidden field and don't set its value, no crash.
So it's not just the visibility of the TR on its own, it's the HiddenField too.
My fix: don't set Visible=false in the markup, and change OnItemDataBound to set Visible=false when required.
In other words: I was defaulting to hide things in markup and use code behind to show them. I changed this around and show things by default in markup and hide them using the code behind.
I've added the fix in the markup and code above.


text:
Q: How start SurfaceHolder.Callback() event if Button Clicked? i tried to start SurfaceCallback of Camera if Button Clicked, but i cannot , if i did Camera.setPreviewCallback() does not invoked although it works in i invoked SurfaceHolder.Callback() from onCreat()method as shown in code below
public class HeartRateMonitor extends ActionBarActivity {

private static final String TAG = "HeartRateMonitor";
private static SurfaceView preview = null;
private static SurfaceHolder previewHolder = null;
private static Camera camera ;
private static View image = null;
private static TextView text = null;
private static WakeLock wakeLock = null;
private static long startTime = 0;
static Context context;
static CircleButton cb ;
static int txt ;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    PlaceholderFragment  p = new PlaceholderFragment() ;
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.contain, p)
                .commit();
    }
    preview = (SurfaceView) findViewById(R.id.preview);
    previewHolder = preview.getHolder();
    previewHolder.addCallback(surfaceCallback);
    previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    image = findViewById(R.id.image);
    text = (TextView) findViewById(R.id.text);
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotDimScreen");
    HeartRateMonitor.context = getApplicationContext();
}

 class PlaceholderFragment extends Fragment implements View.OnClickListener {
     // this Fragment for Circular Button .
    View rootView ;
    public PlaceholderFragment() {
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.start, container, false);
        cb = (CircleButton) rootView.findViewById(R.id.startButton);
        cb.setImageResource(R.drawable.start);
        cb.isClickable();
        cb.findViewById(R.id.startButton).setOnClickListener(this);
        return rootView;
    }
    @Override
    public void onClick(View v) {
       // Toast.makeText(getActivity(), "Button clicked", Toast.LENGTH_SHORT).show();
        cb.setImageResource(R.drawable.stop);
        start();
    }
}

public void start(){
    // here i want start preview .
}

@Override
protected void onResume() {
    super.onResume();
    wakeLock.acquire();
    camera = Camera.open();
    startTime = System.currentTimeMillis();
}

@Override
public void onPause() {
    super.onPause();
    wakeLock.release();
    camera = null;
}

private static PreviewCallback previewCallback = new PreviewCallback() {

    @Override
    public void onPreviewFrame(byte[] data, Camera cam) {
      // process preview data here .
    }
};

private static SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
    @Override
    public void surfaceCreated(SurfaceHolder holder) {

        try {
            camera.setPreviewDisplay(previewHolder);
            camera.setPreviewCallback(previewCallback);
        } catch (Throwable t) {
        }
    }
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Camera.Parameters parameters = camera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        Camera.Size size = getSmallestPreviewSize(width, height, parameters);
        if (size != null) {
            parameters.setPreviewSize(size.width, size.height);
        }
        camera.setParameters(parameters);
        camera.startPreview();
    }
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // Ignore
    }
};

private static Camera.Size getSmallestPreviewSize(int width, int height, Camera.Parameters parameters) {
    Camera.Size result = null;

    for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
        if (size.width <= width && size.height <= height) {
            if (result == null) {
                result = size;
            } else {
                int resultArea = result.width * result.height;
                int newArea = size.width * size.height;
                if (newArea < resultArea) result = size;
            }
        }
    }
    return result;
}
}

A: If you delay calling previewHolder.addCallback(), the actual events of surfaceCreated() and surfaceChanged() will be fired as usual, only your callbacks won't be called.
You can startPreview at any time after the preview surface is created and bound (i.e. after you call camera.setPreviewDisplay(previewHolder)). You can setPreviewCallback only when you need its data. You can set preview to be transparent, or hide it behind some other view.


text:
Q: Is there a way to trigger two consecutive events in Blazor with a single click? Background
I have created the card game called SET in Blazor WASM. In this game you click 3 cards and this can result in either a succesful SET, or a false submission. It works well and now I want to add an additional functionality to signal the outcome of the submission.
Desired result
First method: Upon clicking the 3rd card, the 3 cards should get a green (correct) or red (false) background and after x amount of time (say 1 second) a second method should fire.
Second method: If set was correct, replace the 3 cards with 3 new ones. If set was false, reset background color to white and reset border color to black.
Actual current result
What currently happens is that the result of the first method (green/red background) doesn't show, because there is only one callbackevent. So it does get executed, but it won't become visible until the second method is also executed, by which time either the cards have been replaced, or the backgroundcolor/bordercolor have been reset.
Tried so far
I tried to separate the two methods within the @onclick event, but there is still only one eventcallback and I could not find another way to do this so far, nor on stack overflow.
@onclick="() => { ProcessSelection(uniqueCardCombinations[index]); ProcessSetReplacement(); }

The most notable difference is that EventCallback is a single-cast
event handler, whereas .NET events are multi-cast. Blazor
EventCallback is meant to be assigned a single value and can only
call back a single method. https://blazor-university.com/components/component-events/

I also tried the "State Container" as described here by Chris Sainty, but that only re-renders it and I couldn't adjust it to my situation (not sure that's even possible tbh):
https://chrissainty.com/3-ways-to-communicate-between-components-in-blazor/
Code
I do intend to clean up the code once I get it working, making it more descriptive and splitting up the ProcessSetReplacement a bit more, but wanted to make it work first.
If you need more background/code info either let me know or you can find the entire repository here: https://github.com/John-Experimental/GamesInBlazor/tree/21_AddSetValidationVisualisation
SetPage.razor:

    @for (int i = 0; i < numberOfCardsVisible; i++)
    {
        var index = i;

 { ProcessSelection(uniqueCardCombinations[index]); ProcessSetReplacement(); }">
            @for (int j = 0; j < uniqueCardCombinations[i].Count; j++)
            {

            }

    }

Relevant parts of SetPage.razor.cs (code behind)
private void ProcessSelection(SetCardUiModel setCard)
    {
        numberOfSelected += _uiHelperService.ProcessCardSelection(setCard);

        if (numberOfSelected == 3)
        {
            var setSubmission = uniqueCardCombinations.Where(card => card.BackGroundColor == "yellow").ToList();
            var potentialSet = _mapper.Map<List<SetCardUiModel>, List<SetCard>>(setSubmission);
            var isSet = _cardHelperService.VerifySet(potentialSet);

            _uiHelperService.SignalSetSubmissionOutcome(setSubmission, isSet);
        };
    }

private void ProcessSetReplacement()
    {
        // If it wasn't a set submission, you do nothing
        if (numberOfSelected == 3)
        {
            var redBorderedCards = uniqueCardCombinations.Where(card => card.BorderColor == "red").ToList();
            var countGreenBorders = uniqueCardCombinations.Count(card => card.BorderColor == "green");

            // The while ensures that the 'ProcessSelection' function, which is also called, has run first
            while (redBorderedCards.Count == 0 && countGreenBorders == 0)
            {
                Thread.Sleep(125);
                redBorderedCards = uniqueCardCombinations.Where(card => card.BorderColor == "red").ToList();
                countGreenBorders = uniqueCardCombinations.Count(card => card.BorderColor == "green");
            }

            // Wait 1.5 seconds so that the user can see the set outcome from 'ProcessSelection' before removing it
            Thread.Sleep(1500);

            if (countGreenBorders == 3)
            {
                // Replace the set by removing the set submission entirely from the list
                uniqueCardCombinations.RemoveAll(card => card.BackGroundColor == "yellow");
                numberOfSelected = 0;

                // Check if the field currently shows more cards than normal (can happen if there was no set previously)
                // If there are more cards, then remove 3 cards again to bring it back down to 'normal'
                numberOfCardsVisible -= numberOfCardsVisible > settings.numberOfCardsVisible ? 3 : 0;

                EnsureSetExistsOnField();
            }
            else
            {
                foreach (var card in redBorderedCards)
                {
                    card.BackGroundColor = "white";
                    card.BorderColor = "black";
                }
            }
        };
    }

A: When you need to execute several timed actions in an event, async is your main tool.
Blazor will recognize async event handlers:
//private void ProcessSelection(SetCardUiModel setCard)
private async Task ProcessSelection(SetCardUiModel setCard)
{
    ... // old code
    await Task.Delay(1000);
    ProcessSetReplacement();
}

when you have more than one Task.Delay() then add StateHasChanged() calls before them.
And in the markup section:
@onclick="() => ProcessSelection(uniqueCardCombinations[index])"

A: Do not call both methods in onclick.

*

*Call ProcessSelection, process result and set red/green there.

*Call StateHasChanged()

*Set timer to one second in ProcessSelection. Use Timer from System.Timers.

*On Elapsed of the timer call ProcessSetReplacement.


text:
Q: Webscraping with requests_html but it says a chromium file is missing I trying to web scrape using requests-html but it returns an error saying there is a missing file even though I pip install requests-html and it said all req fulfilled. how do I get around this.
from requests_html import HTMLSession
import time

url = 'https://soundcloud.com/jujubucks'

s = HTMLSession()
r = s.get(url)

r.html.render()

songs = r.html.xpath('//*[@id="content"]/div/div[4]/div[1]/div/div[2]/div/div[2]', first=True)

print(songs)

this produces a sxstrace error.
OSError: [WinError 14001] The application has failed to start because its side-by-side
configuration is incorrect. Please see the application event log or use the command-line
sxstrace.exe tool for more detail

apparently this is the missing file according the event log but I dont know where to get it.
Activation context generation failed for "C:\Users\houst\AppData\Local\pyppeteer\pyppeteer\local-chromium\588429\chrome-win32\chrome.exe". Dependent Assembly 71.0.3542.0,language="*",type="win32",version="71.0.3542.0" could not be found. Please use sxstrace.exe for detailed diagnosis.

A: I came here with the same question, but the only answer didn't apply to me.  My win10x64 PC has 5 versions of python, 4 installed via anaconda and python 3.10 installed via the microsoft store. Debugging the process in vscode using the MS store version... with pip install requests-html installed for that version of python only.
VScode stack trace showed that subprocess.py failed to launch a subprocess.
Windows event viewer showed a failed attempt to launch chrome.exe in:
C:\Users\username\AppData\Local\pyppeteer\pyppeteer\local-chromium\588429\chrome-win32
Windows search showed that chrome.exe - which was downloaded and extracted automatically the first time an attempt was made to call response.html.render() - was actually located at:
C:\Users\username\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\Local\pyppeteer\pyppeteer\local-chromium\588429\chrome-win32
As a work around, and although I've no idea why the issue occured, I moved the chrome-win32 directory to the location expected, and found that chrome ran the javascript on the page and returned html correctly.

A: requests_html depends upon pyppeteer but it seems your pypeteer has not installed chromium completely. Try installing chromium manually, just activate your environment containing pyppeteer and run pyppeteer-install.exe.


text:
Q: Unity3D C# Script : Class Variable Array Data Issue I got a simple question to ask. Just Check below code and the question is in the end at the result of code. I hope you guys can help me..
file inventory.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;

public class inventory : MonoBehaviour {
    public List<item> tmp = new List<item> ();
    public item itema;

    itemDatabase database;

    // Use this for initialization
    void Start () {
        int slotAmount = 0;

        database = GameObject.FindGameObjectWithTag ("itemDatabase").GetComponent<itemDatabase> ();
        //Generate the Slot and Slot Name;
        for(int i = 1; i <= 24; i++) {
                tmp.Add (new item());
        }

        itema = database.items [0];
        tmp [0] = itema;
        tmp [0].itemStock = 1;
        Debug.Log (tmp[0].itemID + " - " + tmp[0].itemStock);
        itema = database.items [0];
        tmp [1] = itema;
        tmp [1].itemStock = 2;
        Debug.Log (tmp[1].itemID + " - " + tmp[1].itemStock);
        itema = database.items [0];
        tmp [2] = itema;
        tmp [2].itemStock = 3;
        Debug.Log (tmp[2].itemID + " - " + tmp[2].itemStock);
        Debug.Log (tmp[0].itemID + " - " + tmp[0].itemStock);
        Debug.Log (tmp[1].itemID + " - " + tmp[1].itemStock);

    }

}

and the result was :
tmp Array [0] : 1 Stock 1

tmp Array [1] : 1 Stock 2

tmp Array [2] : 1 Stock 3

tmp Array [0] : 1 Stock 3 // this array recently stock was 1 now replace with 3 Why it is replace i have use an array ?

tmp Array [1] : 1 Stock 3 // this array recently stock was 2 now replace with 3 Why it is replace i have use an array ?

The Question is on tmp Array[0] and tmp Array[1] it was replace by tmp Array[2].
THanks
Dennis

A: That is because in C# itema = database.items [0]; will not create a copy but rather itema will always point to object. So what is happening is you are not adding duplicates to your array but rather all the things point to same element that is the value of database.items[0]. Which in turn is getting modified.
I would rather suggest you to create a new class instance like this
Set database.items[0] values in items
itema = new items( database.items [0].name, database.items [0].ID, ....)
then assign this itema
tmp [0] = itema;
remember in c# the varibles just point to the object and will not create duplicate when you try to assign it. You will need to manage that.


text:
Q: Using 'lest' in a sentence a quick question:

Don't let the sun go down in your heart, my child, lest fear and woe
  would follow in your wake.

Is the above sentence correct, mainly the 'lest' part? English is not my native language. I am also uncertain about the use of the word 'would'.
Thanks in advance!

A:
The conjunction 'lest' has a similar meaning to 'in case' or
  'so that...not'.
If we rewrite the sentence using 'so that...not', the meaning will be
  clearer:
  Don't let the sun go down in your heart, my child, so that fear and woe wouldn't follow in your wake.

The use 'lest' is very rare in modern British English; it is a little more common in formal American English.

Lest can be followed by a subjunctive verb.
The government should take immediate action, lest the problem of child poverty grow worse.

Screen shot from Michael Swan's PEU

A: It's: "lest fear and woe follow in your wake". "Lest" is followed by an infinitive phrase with a bare infinitive. Otherwise it's fine !


text:
Q: Rails/Sidekiq/Devise: Is the job being handled by Sidekiq? How can I be sure? I've set Devise to send emails asynchronously, like so:
class User < ApplicationRecord
  ...

  def send_devise_notification(notification, *args)
    DeviseMailerJob.perform_now(devise_mailer, notification, id, *args)
  end
end

class DeviseMailerJob < ApplicationJob
  queue_as :mailers

  def perform(devise_mailer, method, user_id, *args)
    user = User.find(user_id)
    devise_mailer.send(method, user, *args).deliver_now
  end
end

My sidekiq.yml looks like this:
---
:concurrency: 5
:queues:
  - mailers

I can go to the sign up page, sign up and I will see that everything seems ok in the logs:
2018-10-09T10:02:27.793848+00:00 app[web.1]: I,
[2018-10-09T10:02:27.793770 #4]  INFO -- :
[646a58f7-9588-4a1f-a258-9fbede3cf87d] [ActiveJob] [DeviseMailerJob]
[5ceac77e-d498-4436-8f12-7cd4aff2c004] Performed DeviseMailerJob (Job ID:
5ceac77e-d498-4436-8f12-7cd4aff2c004) from Sidekiq(mailers) in 3301.06ms

But the job does not show up in the Sidekiq dashboard. I do receive the confirmation email however. So the job does get processed. Only, I cannot be sure that Sidekiq is handling it.
Looking at the Heroku logs, I cannot see any logs from Sidekiq. On the dashboard, I would expect to see the 'processed' tally increment for every email that is sent. I'm not sure how to investigate this.
With Heroku, what's the best way of seeing wether or not the job is being handled by Sidekiq? Is there anything in my code to suggest that the job isn't being handled by Sidekiq?

A: You've explicitly told the code to execute immediately by calling perform_now:
DeviseMailerJob.perform_now


text:
Q: Docker: effect of logging driver on logs I want to use the elk stack (Elastic search, kibana, logstash) for logging of an application built with multiple microservices running in docker (currently in a swram).
We want to log messages from stdout / stderr. Our system should add the serviceName, ContainerID, timestamp (if possible to do it automatically and precise), hostname.... to each logentry without any work for the developer.
Docker supports multiple logging drivers such as Json, syslog and Gelf (only UDP) which can be directly shipped to logstash or through a shipping system (like logspout or others).
My question: How does the logging driver and log shipping choice effect the logs? Does docker always include the same data (like container id, timestamp, actual log message) packaged in different ways or does it actually effect the content?
My colleagues used logspout to collect the logs from the standard docker json logs. Will I get the exact same information into logstash if I use --log-driver=gelf (assuming no packages are lost)?

A: I found out that the Json logs only contain: {"log":"log message","stream":"stderr","time":"2017-04-20T07:05:19.584571658Z"} simply by viewing the logfile found with docker inspect. Gelf logs however have a lot of additional fields as described here:
fields := gelfFields{
hostname:      hostname,
containerID:   ctx.ContainerID,
containerName: string(containerName),
imageID:       ctx.ContainerImageID,
imageName:     ctx.ContainerImageName,
command:       ctx.Command(),
tag:           ctx.Config["gelf-tag"],
created:       ctx.ContainerCreated, }

Unfortunately docker only transmits gelf log messages with udp so packets might be lost. However over localhost udp packages are not lost.
Logspout which ships the json logs to Logstash collects additional information about the containter and ships that too so the end result is not so different from the gelf entries. Logspout is however not maintaned by docker and changes to docker might break or change the functionality since the data is not in the actual json log entry.


text:
Q: Where should Meteor.methods() be defined? http://docs.meteor.com/#meteor_methods
I have tried it in publish.js in my server folder.
I am successfully calling Meteor.apply and attempting the server call from the client.  I always get an undefined response.

A: I've uploaded a short example here, should you need a working example of this: https://gist.github.com/2387816

A: I hope some will find use of this addition, and this doesn't cloud the issue that methods are primarily intended to run on the server as debergalis has explained.
Using Meteor.methods() on the client is useful too. (look for "stub" in the Meteor.call() section too...)
This allows the client to (synchronously) simulate the expected effect of the server call.
As mentioned in the docs:

You use methods all the time, because the database mutators (insert,
  update, remove) are implemented as methods. (...)

A separate section explaining use of stubs on the client might ease the understanding of methods calls on the server.

A: Calling Meteor.methods on the server is correct.  That will define remote methods that run in the privileged environment and return results to the client.  To return a normal result, just call return from your method function with some JSON value.  To signal an error, throw a Meteor.Error.
On the client, Meteor.apply always returns undefined, because the method call is asynchronous.  If you want the return value of the method, the last argument to apply should be a callback, which will be passed two arguments: error and result, in the typical async callback style.
Is your server code actually getting called?  You can check that by updating the DB in the method and seeing if the client's cache gets the new data, or calling console.log from inside the method body and looking at the output of the "meteor" process in your terminal.

A: There are several places I can define my Meteor.methods() (with pro's and con's):

*

*On the server only - when the client calls the method, it'll have to wait for the server to respond before anything changes on the client-side

*On the server, and uses a stub on the client - when the client calls the method, it will execute the stub method on the client-side, which can quickly return a (predicted) response. When the server comes back with the 'actual' response, it will replace the response generated by the stub and update other elements according.

*The same method on both client and server - commonly used for methods dealing with collections, where the method is actually a stub on the client-side, but this stub is the same as the server-side function, and uses the client's cached collections instead of the server's. So it will still appear to update instantly, like the stub, but I guess it's a bit more accurate in its guessing.


text:
Q: UITextField - resignFirstResponder Query I have an application which has a couple of UITextField present to allow my user to enter their age, and another numerical value.  Ideally, I want the keyboard to bring up the numeric keypad when the TextField is being edited.  At present I have it set to Numer and Punctuation merely to make use of the 'Done' button to dismiss the keyboard as the Numeric pad does not have a done button.
In an attempt to use the Numeric keypad, I have tried to set it to dismiss by tapping the background of my main view.
-(IBAction)backgroundTapped:(id)sender;

I created the above action in my header file.
-(IBAction)backgroundTapped:(id)sender {
    [ageEntry resignFirstResponder];
}

I have expanded on the above method in my implementation file to tell the ageEntry TextField to resignFirstResponder.  I have also changed my main view to a UIControl class and connected the buttonTapped action to the relevant alert through Interface Builder.  Yet when I touch the background nothing happens.
Any ideas?

A: Just detect the touch in your viewController's view using the method
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [urAgeField resignFirstResponder];
    [urOtherField resignFirstResponder];
}

and resign the keyboard in this method

A: A much easier method is to add a inputAccessoryView to your text field. This input accessory view can be a UIToolbar with a single UITabBarButton for your Done button.
Much less of a hack, and will look like the accessory view that is used in for example Safari to dismiss the keyboard.

A: i had a similar problem. here is the solution..
EDITED
add
- (void)viewDidLoad
{
        [super viewDidLoad];
         UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                    action:@selector(tap:)];
        tap.numberOfTapsRequired = 1;

        [self addGestureRecognizer:tap];

}

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
   [ageEntry resignFirstResponder];
}


text: Q: Tor and inverse images Let $X$ and $Y$ be two schemes over $\mathbb C$, $E$ a coherent sheaf on $X$, $F$ a coherent sheaf on $Y$, and $p:X\times Y\to X$, $q:X\times Y\to Y$ the projections. Is it always true that $\text{Tor}^i(p^*(E),q^*(F))=0$ for $i>0$ ?


text:
Q: VBA script to trigger Python and saving down xlsx file I am trying to save the .xlsx file and using VBA as a wrapper to execute the python file. However,  I can validate that python code runs, but somehow .xlsx file is not saved. When I run the same python file via IDE, it saves down the .xlsx file.
VBA code
Sub RunPython()

Dim shell As Object
Dim exepath, scriptPath As String

Set Shell = VBA.CreateObject("Wscript.Shell")
exePath = """C:\Program Files\...\python.exe"""
scriptPath = "C:\....\mymodule.py"

Python Script
import pandas as pd
import xlsxwriter

df = pd.DataFrame(np.random.randn(5,2),index=range(0,10,2),columns =list('AB'))
excel_file ='sample.xlsx'
writer = pd.ExcelWriter(excel_file,engine='xlsxwriter')
df.to_excel(writer,sheet_name='Data')
print ("file read")
writer.save()
writer.close()

A: Does that 'excel_file' have a path?
Does Python use a current directory and automatically add it to Excel file name?
If yes, do you know how to obtain it and can you look for .xlsx file there?
If not, how do you check if the .xlsx file has been saved? Where are you looking for?
Does Python raise any error?
I am looking to the code mostly like a VBA user...
I would suggest to send a message from Python, containing the current directory path. Supposing that the .xlsx workbook path has not somehow been defined and the code presented here does not include that part. Theoretically it should use the same current directory, but I think it is good to be checked...


text:
Q: Populate form based on selected item php I have a page with a select list (gets successfully populated from mysql) and a text box. The text box has to be populated with a value from mysql based on the item selected in the list. But the ajax call to php is not working and i can not figure out what the issue is. I am just learning ajax and php, so a novice.. Please help. i am stuck with this for a long time.

<form id="assign-fundraiser_form" class="form-horizontal" action="" method="post">

     <select class="selectpicker form-control" id="fundraiser" name="fundraiser" required>
       <option value="" selected disabled>Select a Fundraiser</option>
       <?php
         include('session.php');
         $result1 = mysqli_query($db,"select concat(f_firstname,' ',f_lastname) fundraiser from fundraiser where f_company in (select contractor_name from contractor where company_name = '$_SESSION[login_user]') and f_status = 'Active' order by concat(f_firstname,' ',f_lastname)");
         while ($rows = mysqli_fetch_array($result1))
         {
          echo "<option>" .$rows[fundraiser]. "</option>";
         }
       ?>
     </select>

<input type="text" name="charity" id="charity_new" />
</form>

<?php
include "session.php";
if (ISSET($_POST['.selectpicker'])) {
    $ref = $_POST['.selectpicker'];
    $query = $db->query("select f_charity charity_new from fundraiser limit 1");
    $row = $query->fetch_assoc();
    $charity_new = $row['charity_new'];
    $json = array('charity_new' => $charity_new);
    echo json_encode($json);
}

$db->close();
?>

A: I think, it should be
$('#charity_new').val(res.charity_new);

instead of
$('#charity_new').val(data.charity_new);

A: There are a few problems that I've spotted from quick glance, so I've separated them below.
PHP
In your AJAX request, you are using data: { selected_data: selected_data } which means the PHP code will be expecting a POSTed key named selected_data but you're looking for .selectpicker. You seem to have mixed up a couple of things, so instead of:
$_POST['.selectpicker']

it should be:
$_POST['selected_data']

JavaScript
As Ravi pointed out in his answer, you also need to change your success function. The parameter passed through to this function is res not data, so instead of:
$('#charity_new').val(data.charity_new);

it should be:
$('#charity_new').val(res.charity_new);

MySQL
It also appears as though your query itself is invalid - you seem to be missing a comma in the column selection.
select f_charity charity_new from fundraiser limit 1

should be:
select f_charity, charity_new from fundraiser limit 1

or, seeing as you're not using the f_charity column in the results anyway:
select charity_new from fundraiser limit 1

You aren't using the value that is being POSTed either, meaning that whatever option is selected in the dropdown makes no difference to the query itself - it will always return the first record in the database.
Other
One other thing to be aware of is you're using a class selector on your change function. This means if you have multiple dropdowns with the same class name in your HTML, they will all be calling the same AJAX function and updating the textbox. I don't know if this is what you're aiming for, but from your code posted, you only have one dropdown in the form. If you only want that one dropdown to be calling the AJAX function, you should use an ID selector instead:
$('#fundraiser').on("change", function() {
    // ...
}


text:
Q: How to prevent kernel or any broadcast messages from flooding the TTYs? Because of some hot-plugging issue, similar to what talked of here, the TTY displays show a continuous stream of messages (which are also logged in the /var/log directory). Every text I key in flows away visually, but it does take the inputs (I can log in and run commands).
Is there a way to prevent such error and/or any other broadcast messages from flooding the TTYs?
Update: Here's the content of the requested file /etc/rsyslog.conf:
#  /etc/rsyslog.conf    Configuration file for rsyslog.
#
#           For more information see
#           /usr/share/doc/rsyslog-doc/html/rsyslog_conf.html
#
#  Default logging rules can be found in /etc/rsyslog.d/50-default.conf

#################
#### MODULES ####
#################

$ModLoad imuxsock # provides support for local system logging
$ModLoad imklog   # provides kernel logging support (previously done by rklogd)
#$ModLoad immark  # provides --MARK-- message capability

# provides UDP syslog reception
#$ModLoad imudp
#$UDPServerRun 514

# provides TCP syslog reception
#$ModLoad imtcp
#$InputTCPServerRun 514

# Enable non-kernel facility klog messages
$KLogPermitNonKernelFacility on

###########################
#### GLOBAL DIRECTIVES ####
###########################

#
# Use traditional timestamp format.
# To enable high precision timestamps, comment out the following line.
#
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat

# Filter duplicated messages
$RepeatedMsgReduction on

#
# Set the default permissions for all log files.
#
$FileOwner syslog
$FileGroup adm
$FileCreateMode 0640
$DirCreateMode 0755
$Umask 0022
$PrivDropToUser syslog
$PrivDropToGroup syslog

#
# Where to place spool files
#
$WorkDirectory /var/spool/rsyslog

#
# Include all config files in /etc/rsyslog.d/
#
$IncludeConfig /etc/rsyslog.d/*.conf

A: The easy workaround is to comment out this line in /etc/rsyslog.conf:
# Everybody gets emergency messages
#*.emerg                    :omusrmsg:*

At least it worked for my RHEL 7.9 box.
To preserve these messages and make them easy to find, you could write them to a specific file. Something like this:
*.emerg                    /var/log/remote.log

Yes. That setting as a default is super intrusive. On a syslog server, any server in the environment throwing emerg messages can flood the console.


text:
Q: What happens with these registry items...? I'm aware that the following registry values relate to the login process, I found in a youtube video that switching out the .bak on the two similar items you can fix a login service error. My question is how does that fix the issue, what is the purpose of the .bak item, and why can't I just delete the one that was giving me an issue entirely?
The video concerned: https://www.youtube.com/watch?v=vEyxD6ZG-jI
The registry location:
HKEY_LOCALMACHINE\
 SOFTWARE\
  Microsoft\
   Windows NT\
    CurrentVersion\
     ProfileList\
      S-1-5-18
      S-1-5-19
      S1-5-21-3428083748234-9230492304-92348923429834-1000
      S1-5-21-3428083748234-9230492304-92348920329834-1000.bak

A: You could just delete it. The video suggests renaming it probably because this Microsoft KB article says to. Under normal circumstances (i.e. when this temporary profile business isn't occurring), Windows won't look at the extra key since it doesn't correspond to any valid SID, so it's not doing anything, but it's not hurting anything either.
The .bak is your real entry and was renamed to that when you were signed into a temporary profile, as explained by that KB article. Changing it back to its original name and updating the RefCount and State makes it loadable again.


text:
Q: Why can't I use downloaded voices for speech Synthesis in Lion? This drove me nuts, so I thought I'd document the answer here.
To choose a voice, you give -[NSSpeechSynthesizer initWithVoice] the identifier in reverse-DNS format, e.g. com.apple.speech.synthesis.voice.Agnes  But if a user downloads one, such as Paolo, you can't get to it the same way.

A: The answer turns out to be that Apple names it "voice.premium", so you get to Paolo with com.apple.speech.synthesis.voice.paolo.premium.  So even though I got the list of [NSSpeechSynthesizer availableVoices], I only printed out the last word, and I didn't notice premium added to the list.  To get the real printable name of a voiceIdentifier in availabVoices,(instead of looking at the last word), use:
[[NSSpeechSynthesizer attributesForVoice:voiceIdentifier]
    valueForKey: NSVoiceName]


text:
Q: Can I boot a netbook pc from a desktop pc using a usb adapter cable? Can I boot my Windows XP SP3 / Ubuntu Linux Netbook 10.04 netbook pc from my Ubuntu Linux 10.04 desktop pc using a usb adapter cable and boot the netbook from the desktop?
I have the following error on boot

error: no such partition
  grub rescue>

ls returns the following result

(hd0) (hd0,4) (hd0,3) (hd0,2) (hd0,1)

I have tried to restore grub 2 on the Master Boot Record but have no terminal command line available.
I have tried usb pendrive linux without success.
I have no external optical drive for the Ubuntu live CD or DVD.
Short of buying an external optical drive, do I have any other options?

A: Your netbook's BIOS boot options define whether or not you need to buy an external optical drive.  Grub seems to notice only partitions on your netbook's internal hd:  I'd enable all other available options in the BIOS, then re-try your pendrive (that's a USB connected flash drive, right?  Just checking, but the linux instance on that drive has to be properly installed on the flash drive to be bootable).
What kind of "usb adapter cable" do you have?  Is it a USB-to-SATA (or PATA, or SCSI) cable?  (Do consider getting one, as they can be handy for situations like this.)   If so, you can also remove your desktop's hard drive (or its optical drive), connect it to the netbook via said USB cable, and boot from there.

A: you cannot, in general, connect two USB host devices together - the 'closest' thing to that was the firewire disk mode on PPC era macs.
Basically there's two (and a half) types of USB devices - Hosts that use type A plugs, and devices, which use type B, mini (a or b) and micro USB ports (there's also USB OTG, which is supposed to be able to act as both a device and a guest). Of course for some odd reason, portable HDDs often use type A connections, which is incorrect according to the conventions
Your best bet is to get an optical drive with a USB interface or to bootstrap the XP install from a USB pen drive  for example, like this


text:
Q: Asterisk for Small Business - Where to Start? I have been in IT for a long time now doing software development and some system/server administration, but all mostly software-related services.  I would like to help set up a small business (~50 employees) with Asterisk, but I am not very familiar with how the whole T1, data/voice channels, etc work.  I have set up a personal Asterisk server (functional), but have not done so with a pipe like a T1 (which sounds more complex than residential cable/DSL).
Are there any resources out there to help me understand what may be needed of me to help set this business up with Asterisk and re-use their existing T1 pipe?
Any help would be greatly appreciated.

A: Partial answer.
First, know that Asterisk configuration is more like a programming language than, say, Apache configuration. There are numerous ways to create "nonsense" configurations. On the other hand, you can create very nifty services.
There are three aspects to setting up an Asterisk installation:

*

*call quality

*what manner of phones will you be using?

*which services do the users expect?

Quality
In my experience, your company suffers in reputation from bad phone lines, so make sure you get get decent quality from your installation. Quality is among other things:

*

*low upstream latency and high link uptime

*Asterisk server uptime; use separate UPS. People tend to get cranky if they can't call the janitor and tell that there is a power failure in the house.

*decent end-user equipment

Don't do a big bang implementation. Start with some users and work from there.
End user equipment
How are your users going to talk on the phone and how do you connect that equipment to Asterisk. Some users appreciate a headset connected to their PC, while others need a grey handset with analog dial pad or they will just be confused. Which will you provide and how will they connect to Asterisk?
For so called softphones (i.e. a SIP client installed on your PC) not much need to be done. You need a mechanism to handle accounts for these users (e.g. LDAP) and they need decent headsets. For connecting traditional analog phones, there are various sorts of equipment. For small installation, you may be able to get your hands on Zyxel Prestige 2002s (2 ports each), but for larger installations you need rack-mountable equipment of some sort.
Services
In my experience it is very difficult to get users to actually tell what they expect from a phone system, but once you give them something, they start having all sorts of opinions. So you need to be very clear about what services you provide and require a somewhat anal change management process (more so than is normally required in a small company).
Conclusion
This sounds dangerous and ominous, but know that the reward is equally great. The advantage of being able to create dedicated phone services, with the same sort of detailed control that you have with other IT services can be very rewarding. It will take some time for your users to get used to the thought that they can actually request fancy features from their phones, but once they get started, you can make their work a lot easier. Some features my users found very useful:

*

*voice mail that sends mail with audio files

*queues and fallback for all users

*softphone and multiple phones for all users

*phone conferences

*redirection to mobile phones, and

*routing calls through company phone system from private phones so that company picks up tab for international/expensive calls.

Also, traditionally, most phone extensions are personal, but in a modern company, most incoming calls are actually to a company function. You should probably consider not having personal extensions at all, and simply have an extension per function that rings all phones in that department/function.

A: Solid answer by @Bittrance already.
My main highlights for a new to all this 'VoIP guy for a small office' would be:
Server setup:

*

*Consider buying an appliance with a nice GUI. Several vendors make 'Asterix bundled with hardware' packages, like the "Asterisk Appliance 50" or "Trixbox".

*If not an appliance, then at least consider a nice virtual machine / server software image (OS + Asterix + Addons + GUI) like AsteriskNOW, Trixbox, etc.
Upstream connection:

*

*You can use an IP based telephony service provider, i.e. send SIP VoIP data over the T1 to your telephony service provider. This is where much of the business innovation, low telephony rates etc can be had. In a good design, you want QoS on the upstream (T1) line, to guarantee good voice quality in all conditions.

*You can use a traditional telephony service provider, and use ISDN/2, ISDN/30, or multiple analog lines to connect to your upstream service provider. This is very reliable, time-proven, and doesn't have any QoS needs as you are not mixing data and voice on the same physical circuit.
QoS:

*

*"Quality of Service (QoS) is the biggest design issue. QoS, at very high level, refers to the ability to prioritize data flows though shared pipes, i.e. make sure voice traffic gets priority over computer data.

*How to best implement QoS in a given network is very dependent on what equipment is being used.

*In a few cases, the simplest/cheapest QoS solution is to just use 2 physical circuits -- one for data, and another for voice. For example, some small offices use a new high-speed FiOS package for Internet connectivity/data, and an old T1 or something for voice uplink. The most cost-effective option will depend on what is being offered in your area, and the QoS capabilities of your existing firewall/router.

*You should go for QoS on your internal network too. That's not so hard; the common solution is setting up dedicated VLANs for voice and data, and using the QoS implementations in your (managed Cisco) switch. Some really cheap installations use 2 switches, one dump ~30 USD switch for data/PCs, and another dumb switch for SIP phones exclusively. That works too, but is inelegant and can lead to lots of cable runs.
Phones:

*

*Read some reviews, and get good SIP phones for your office. Sound quality differs substantially between models (mostly due to different microphones & speakers).

*A SIP phone is basically a micro-computer. It needs an IP address (DHCP), it must be registered with Asterix, from time to time you might want to update the phone firmware, etc. Plan how you will administrate this.


text:
Q: wifi antenna issue signal amp 10 dbi antenna I am running a dlink 2100ap with a (30dBm) 1W signal amp to a 10 dbi antenna. I am having issues picking up the signal on my laptop, could it be possible that the amp is making the antenna broadcast at a higher frequency? (it operates in the 2.4 Ghz spectrum up to 2.5). How far should my antenna reach?

A: The amplifier doesn't change the frequency, just the power.
1 W + 10 dBi means in the directions the antenna transmits best, a receiver will see the same power as a 10 W ideal transmitter broadcasting omnidirectionally.