text:
Q: Wordpress database sync in team development environment Right now I'm working on a wordpress web-site that synchronize its codebase using GIT. It works well for files but when it comes to a database nightmare starts to happen. We have several servers, one for QA, another for marketing and a final one for production. All of these servers have their own database setup. If I work on one of the servers and modify smth. in a database through wp-admin and someone else do smth else on another server, we need to manually merge all of our database changes.
So the question is: Is there a way to work from the same database on different web-site instances? If I make some change to the db, I want these change to be reflected on all of the servers. Thanks.

A: The main problem is that you need to all be working from the same database. I haven't found anything that handles a merge very well. The closest I got was WP-Stagecoach though that doesn't quite cover it. I've been told that Datahawk will do it but it's still in development.
This may help though - I work with another developer, we both work locally on our computers using MAMP. We use one database which is hosted by our local server. Git is then used to download files between our local setups. So there's no need for merging the database as that seems to be the biggest headache.


text:
Q: Vue transitioned element not showing after transition is complete I'm trying to animate an element to full browser height when the user clicks on the top bar. The animation works, but once the (enter) animation is finished the container jumps back to zero height, while it's supposed to stay until the user clicks the close button.
How do I make the container stay 100vh when the animation is finished?
I tried adding height: 100vh; on the element, but by doing that the transition animation stopped working. (by removing the height, the animation works but the element disappears)
Not sure if it matters, but I changed v-if into v-show and also added a key on the container, but that didn't seem to make a difference.
Here's a link to my code. And to view the animation.

<template>

        CLICK ME

    <ExtendTransition>

    </ExtendTransition>

</template>

<template>
  <transition appear name="extend" mode="out-in">
    <slot></slot>
  </transition>
</template>

A: A transition only is applied while the transition is playing. Once the transition finished, all transition classes are removed. This means that your element must have the CSS you want it to have after the transition is finished. You can then use the transition classes to set the initial state and define the transition to get to that point, and from that point to the initial state.
The easiest way to solve this problem is by making ExtendTransition.vue the only component that worries about the transition, and using a wrapper that wraps the thing you want to extend.
<template>
  <transition appear name="extend" mode="out-in">

      <slot></slot>

  </transition>
</template>

The only thing you then have to do is to set the default state of your wrapper:
.extend-transition-wrapper {
  height: 100vh;
  will-change: height;
  position: relative;
}

In your ABoutMeComponent.vue you then use a prop to show and hide the content:
<ExtendTransition :extended="extended">

</ExtendTransition>

And finally you set .main-container to always have a height of 100%. Since we set the wrapper to have position: relative, this will force the main container to become the height of that element.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Forms onsubmit How does one reference the default 'Submit' Forms button to link the 'onsubmit' trigger with another action?  Thank you.
For example, with onsubmit,
Logger.log('do something');

A: This is an old answer.
Currently (Jan 2014) there are two ways for onSubmit. One is simply to make a function onSubmit() which supposedly (it doesn't work for me...) allows a limited set of actions under the permission of the current submitting user only. You cannot access his submitted email, for example, or modify the underlying form for next submit.
Then there is is the trigger on submit which you can add and attach to any function and do whatever you want under your own permissions. looks same as screenshot of trigger adding in the answer above, except that its the first column shows methods in you forms script, the next column reads: From-Form  and in the third column you choose: On Submit.
Typically your method will receive an event e  , who's e.values are the same as the values saved in the spreadsheet. So
function formSubmitted(e){ ...

A: There seems to be two applications which trigger code: (1) the form and (2) the spreadsheet linked to the form responses.
(1) There is not much one can do programmaticly from the form as the event is not sent to functions, as noted by Mogsdad and JohnB above. One can, for example, send an email "On form submit" or "On open" but without the event object, one can't even record the number or rows nor anything about the document or submission.
(2) However, if a spreadsheet is linked to the responses of the form, then a trigger can be set on the spreadsheet, where one has access to the event and thus row, column, and other data.
From linked response Google Spreadsheet:

*

*Step 1: Tools > Script editor

*Step 2: write some code, for example:

Code.gs:
function onSpreadsheetSubmit(e) {
     var row = e.range.getRow();
     MailApp.sendEmail("me@example.com",
                "Your subject, rows: "+ row,
                "A new application has been submitted on row: "+
                row,
                {name:"From your friendly spreadsheet"});
}

*

*Step 3: Run > Run function > onSpreadsheetSubmit (or |> icon)

*

*The event likely doesn't have an actual row because the test is not associated with a real submit.

*Step 4: You'll be asked to choose a user and authenticate yourself

*Step 5: Edit > Current project's triggers (or clock-like icon)

*Step 6: Add a new trigger

*Step 7: onSpreadsheetSubmit | From spreadsheet | On form submit

*Step 8: Authenticate and Save (or reverse)

*Step 9: Test by waiting (or executing) a real form submission

*Step 10: Check your email

For more info: https://developers.google.com/apps-script/guides/triggers/events#google_sheets_events

A: Instead of adding a script to the Spreadsheet receiving responses from the Form (as in Mogsdad's answer), I added a script which gets triggered by the Form's Submit button.
Step 1: first create a Google Form

Step 2: Then from the menu, click Tools->Script editor

Step 3: give your function a name like onSubmit()

Step 4: Write some code to send an email like this, then test by click Run button
function onSubmit() {
  MailApp.sendEmail("fred@email.com,alice@email.com",
                    "Subject",
                    "A new application has been submitted.\n\n" +
                    "Here is the link to all Applications:\n" +
                    "https://docs.google.com/spreadsheets/x/1-fdasjhFAKEfdaahfkhsa/",
                    {name:"From Name"});
}

Step 5: in the Script Editor's menu, click Run, or click the Play button on the toolbar to test your code (e.g. make sure you get the email)

Step 6: in the Script Editor's menu, click Resources-> Current project's triggers

Step 7: select the settings Events From form On form submit

Step 8: Then from the Form Editor's menu, click Tools->Script manager and make sure your script is selected

Step 9: try the form.  You should get an email after clicking the form's submit button.

A: JohnB's HOWTO above is excellent. Update (Nov 2017):

*

*Step 2: "Script Editor..." is in the vertical "..." burger menu top right of form

*Step 6: "Project Triggers" is found in the (clock-like icon) (second icon displayed above).

*Step 7: Click "Add a new trigger", ignore the "no myFunctions" warning.

*Step 8: doesn't seem to exist, may not be necessary, works for me without.

Many of the steps above require validation/acceptance by the form owner.

A: One doesn't. The Form Service does not allow any programmatic control over the product. There is an open issue on the Issue Tracker for this general topic. Star it to "vote", and receive updates.
However, you're not lost. In the spreadsheet receiving your form responses, you can add a script with an Installable Trigger to fire "On form submit". From there, you can do many things to the submitted data, including Logging as you wish... but nothing to the Form itself.

These references explain triggers and events.

*

*Using Container-Specific Installable Triggers

*Understanding Events

A: I'd recommend using trigger from Forms. In your form open script editor and paste the code:
function onFormSubmit(e) {
  // for tests
  if (!e) {
    // test object
    var form = FormApp.getActiveForm()
    var responses = form.getResponses();
    e = {"authMode":"FULL",
         "response": responses[responses.length - 1], // last response
         "source": form,
         "triggerUid":"5125265"};
  };
  // do your job here
  try {
    // paste useful code here...
    //
    //
  }
  catch (err) {
    MailApp.sendEmail("testemail@test.com",
                      "Error in the app",
                      "New error, please check.\n\n" +
                      "Here is the event object:\n" +
                      e + "\n" +
                      JSON.stringify(e) + "\n\n" +
                      "Here's an error:\n" + err,
                      {name:"From Name"});
    throw err;
  }
  return 0;
}

Set this function as an installable trigger.
Ref:

*

*https://developers.google.com/apps-script/reference/forms/form-response

*https://developers.google.com/apps-script/guides/triggers/installable

*https://webapps.stackexchange.com/questions/112123/how-do-you-create-an-installable-trigger-for-a-google-apps-script


text:
Q: python scrapy conversion to exe file using pyinstaller I am trying to convert a scrapy script to a exe file.
The main.py file looks like this:
from scrapy.crawler import CrawlerProcess
from amazon.spiders.amazon_scraper import Spider

spider = Spider()
process = CrawlerProcess({
    'FEED_FORMAT': 'csv',
    'FEED_URI': 'data.csv',
    'DOWNLOAD_DELAY': 3,
    'RANDOMIZE_DOWNLOAD_DELAY': True,
    'ROTATING_PROXY_LIST_PATH': 'proxies.txt',
    'USER_AGENT_LIST': 'useragents.txt',
    'DOWNLOADER_MIDDLEWARES' :
    {
        'rotating_proxies.middlewares.RotatingProxyMiddleware': 610,
        'rotating_proxies.middlewares.BanDetectionMiddleware': 620,
        'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,
        'random_useragent.RandomUserAgentMiddleware': 400
    }
})

process.crawl(spider)
process.start() # the script will block here until the crawling is finished

The scrapy script looks like any other. I am using pyinstaller.exe --onefile main.py to convert it to an exe file. When I try to open the main.exe file inside dist folder it starts outputing errors:
FileNotFoundError: [Errno 2] No such file or directory: '...\\scrapy\\VERSION'

I can fix it by creating a scrapy folder inside the dist folder and uploading a VERSION file from lib/site-packages/scrapy.
After that, many other errors occur but I can fix them by uploading some scrapy libraries.
In the end it starts outputing error:
ModuleNotFoundError: No module named 'email.mime'

I don`t even know what does it mean. I have never seen it.
I am using:
Python 3.6.5
Scrapy 1.5.0
pyinstaller 3.3.1

A: I had the same situation.
Instead of trying to make pyinstaller count this file (I failed all my attempts to do it) I decided to check and change some part of scrapy code in order to avoid this error.
I noticed that there is only one place where \scrapy\VERSION file used-- \scrapy\__init__.py
I decided to hardcode that value from scrapy\version by changing scrapy__init__.py
:
#import pkgutil
__version__ = "1.5.0" #pkgutil.get_data(__package__, 'VERSION').decode('ascii').strip()
version_info = tuple(int(v) if v.isdigit() else v
                     for v in __version__.split('.'))
#del pkgutil

After this change there is no need to store version in external file.
As there is no reference to \scrapy\version file - that error will not occure.
After that I had the same FileNotFoundError: [Errno 2] with \scrapy\mime.types file.
There is the same situation with \scrapy\mime.types - it used only in \scrapy\responsetypes.py
...
#from pkgutil import get_data
...
    def __init__(self):
        self.classes = {}
        self.mimetypes = MimeTypes()
        #mimedata = get_data('scrapy', 'mime.types').decode('utf8')
        mimedata = """
        Copypaste all 750 lines of \scrapy\mime.types here
"""
        self.mimetypes.readfp(StringIO(mimedata))
        for mimetype, cls in six.iteritems(self.CLASSES):
            self.classes[mimetype] = load_object(cls)

This change resolved FileNotFoundError: [Errno 2] with \scrapy\mime.types file.
I agree that hardcode 750 lines of text into python code is not the best decision.
After that I started to recieve ModuleNotFoundError: No module named scrapy.spiderloader . I added "scrapy.spiderloader" into hidden imports parameter of pyinstaller.
Next Issue ModuleNotFoundError: No module named scrapy.statscollectors.
Final version of pyinstaller command  for my scrapy script consist of 46 hidden imports - after that I received working .exe file.


text:
Q: Issues implementing the "Wave Collapse Function" algorithm in Python In a nutshell:
My implementation of the Wave Collapse Function algorithm in Python 2.7 is flawed but I'm unable to identify where the problem is located. I would need help to find out what I'm possibly missing or doing wrong.
What is the Wave Collapse Function algorithm ?
It is an algorithm written in 2016 by Maxim Gumin that can generate procedural patterns from a sample image. You can see it in action here (2D overlapping model) and here (3D tile model).
Goal of this implementation:
To boil down the algorithm (2D overlapping model) to its essence and avoid the redondancies and clumsiness of the original C# script (surprisingly long and difficult to read). This is an attempt to make a shorter, clearer and pythonic version of this algorithm.
Characteristics of this implementation:
I'm using Processing (Python mode), a software for visual design that makes image manipulation easier (no PIL, no Matplotlib, ...). The main drawbacks are that I'm limited to Python 2.7 and can NOT import numpy.
Unlike the original version, this implementation:

*

*is not object oriented (in its current state), making it easier to understand / closer to pseudo-code

*is using 1D arrays instead of 2D arrays

*is using array slicing for matrix manipulation

The Algorithm (as I understand it)
1/ Read the input bitmap, store every NxN patterns and count their occurences.
  (optional: Augment pattern data with rotations and reflections.)
For example, when N = 3:

2/ Precompute and store every possible adjacency relations between patterns.
In the example below, patterns 207, 242, 182 and 125 can overlap the right side of pattern 246

3/ Create an array with the dimensions of the output (called W for wave). Each element of this array is an array holding the state (True of False) of each pattern.
For example, let's say we count 326 unique patterns in input and we want our output to be of dimensions 20 by 20 (400 cells). Then the "Wave" array will contain 400 (20x20) arrays, each of them containing 326 boolan values.
At start, all booleans are set to True because every pattern is allowed at any position of the Wave.
W = [[True for pattern in xrange(len(patterns))] for cell in xrange(20*20)]

4/ Create another array with the dimensions of the output (called H). Each element of this array is a float holding the "entropy" value of its corresponding cell in output.
Entropy here refers to Shannon Entropy and is computed based on the number of valid patterns at a specific location in the Wave. The more a cell has valid patterns (set to True in the Wave), the higher its entropy is.
For example, to compute the entropy of cell 22 we look at its corresponding index in the wave (W[22]) and count the number of booleans set to True. With that count we can now compute the entropy with the Shannon formula. The result of this calculation will be then stored in H at the same index H[22]
At start, all cells have the same entropy value (same float at every position in H) since all patterns are set to True, for each cell.
H = [entropyValue for cell in xrange(20*20)]

These 4 steps are introductory steps, they are necessary to initalize the algorithm. Now starts the core of the algorithm:
5/ Observation:
Find the index of the cell with the minimum nonzero entropy (Note that at the very first iteration all entropies are equal so we need to pick the index of a cell randomly.)
Then, look at the still valid patterns at the corresponding index in the Wave and select one of them randomly, weighted by the frequency that pattern appears in the input image (weighted choice).
For example if the lowest value in H is at index 22 (H[22]), we look at all the patterns set to True at W[22] and pick one randomly based on the number of times it appears in the input. (Remember at step 1 we've counted the number of occurences for each pattern). This insures that patterns appear with a similar distribution in the output as are found in the input.
6/ Collapse:
We now assign the index of the selected pattern to the cell with the minimum entropy. Meaning that every pattern at the corresponding location in the Wave are set to False except for the one that has been chosen.
For example if pattern 246 in W[22] was set to True and has been selected, then all other patterns are set to False. Cell 22 is assigned pattern 246.
In output cell 22 will be filled with the first color (top left corner) of pattern 246. (blue in this example)
7/ Propagation:
Because of adjacency constraints, that pattern selection has consequences on the neighboring cells in the Wave. The arrays of booleans corresponding to the cells on the left and right, on top of and above the recently collapsed cell need to be updated accordingly.
For example if cell 22 has been collapsed and assigned with pattern 246, then W[21] (left), W[23] (right), W[2] (up) and W[42] (down) have to be modified so as they only keep to True the patterns that are adjacent to pattern 246.
For example, looking back at the picture of step 2, we can see that only patterns 207, 242, 182 and 125 can be placed on the right of pattern 246. That means that W[23] (right of cell 22) needs to keep patterns 207, 242, 182 and 125 as True and set all other patterns in the array as False. If these patterns are not valid anymore (already set to False because of a previous constraint) then the algorithm is facing a contradiction.
8/ Updating entropies
Because a cell has been collapsed (one pattern selected, set to True) and its surrounding cells updated accordingly (setting non adjacent patterns to False) the entropy of all these cells have changed and needs to be computed again. (Remember that the entropy of a cell is correlated to the number of valid pattern it holds in the Wave.)
In the example, the entropy of cell 22 is now 0, (H[22] = 0, because only pattern 246 is set to True at W[22]) and the entropy of its neighboring cells have decreased (patterns that were not adjacent to pattern 246 have been set to False).
By now the algorithm arrives at the end of the first iteration and will loop over steps 5 (find cell with minimum non zero entropy) to 8 (update entropies) until all cells are collapsed.
My script
You'll need Processing with Python mode installed to run this script.
It contains around 80 lines of code (short compared to the ~1000 lines of the original script) that are fully annotated so it can be rapidly understood. You'll also need to download the input image and change the path on line 16 accordingly.
from collections import Counter
from itertools import chain, izip
import math

d = 20  # dimensions of output (array of dxd cells)
N = 3 # dimensions of a pattern (NxN matrix)

Output = [120 for i in xrange(d*d)] # array holding the color value for each cell in the output (at start each cell is grey = 120)

def setup():
    size(800, 800, P2D)
    textSize(11)

    global W, H, A, freqs, patterns, directions, xs, ys, npat

    img = loadImage('Flowers.png') # path to the input image
    iw, ih = img.width, img.height # dimensions of input image
    xs, ys = width//d, height//d # dimensions of cells (squares) in output
    kernel = [[i + n*iw for i in xrange(N)] for n in xrange(N)] # NxN matrix to read every patterns contained in input image
    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] # (x, y) tuples to access the 4 neighboring cells of a collapsed cell
    all = [] # array list to store all the patterns found in input

    # Stores the different patterns found in input
    for y in xrange(ih):
        for x in xrange(iw):

            ''' The one-liner below (cmat) creates a NxN matrix with (x, y) being its top left corner.
                This matrix will wrap around the edges of the input image.
                The whole snippet reads every NxN part of the input image and store the associated colors.
                Each NxN part is called a 'pattern' (of colors). Each pattern can be rotated or flipped (not mandatory). '''

            cmat = [[img.pixels[((x+n)%iw)+(((a[0]+iw*y)/iw)%ih)*iw] for n in a] for a in kernel]

            # Storing rotated patterns (90°, 180°, 270°, 360°)
            for r in xrange(4):
                cmat = zip(*cmat[::-1]) # +90° rotation
                all.append(cmat)

            # Storing reflected patterns (vertical/horizontal flip)
            all.append(cmat[::-1])
            all.append([a[::-1] for a in cmat])

    # Flatten pattern matrices + count occurences

    ''' Once every pattern has been stored,
        - we flatten them (convert to 1D) for convenience
        - count the number of occurences for each one of them (one pattern can be found multiple times in input)
        - select unique patterns only
        - store them from less common to most common (needed for weighted choice)'''

    all = [tuple(chain.from_iterable(p)) for p in all] # flattern pattern matrices (NxN --> [])
    c = Counter(all)
    freqs = sorted(c.values()) # number of occurences for each unique pattern, in sorted order
    npat = len(freqs) # number of unique patterns
    total = sum(freqs) # sum of frequencies of unique patterns
    patterns = [p[0] for p in c.most_common()[:-npat-1:-1]] # list of unique patterns sorted from less common to most common

    # Computes entropy

    ''' The entropy of a cell is correlated to the number of possible patterns that cell holds.
        The more a cell has valid patterns (set to 'True'), the higher its entropy is.
        At start, every pattern is set to 'True' for each cell. So each cell holds the same high entropy value'''

    ent = math.log(total) - sum(map(lambda x: x * math.log(x), freqs)) / total

    # Initializes the 'wave' (W), entropy (H) and adjacencies (A) array lists

    W = [[True for _ in xrange(npat)] for i in xrange(d*d)] # every pattern is set to 'True' at start, for each cell
    H = [ent for i in xrange(d*d)] # same entropy for each cell at start (every pattern is valid)
    A = [[set() for dir in xrange(len(directions))] for i in xrange(npat)] #see below for explanation

    # Compute patterns compatibilities (check if some patterns are adjacent, if so -> store them based on their location)

    ''' EXAMPLE:
    If pattern index 42 can placed to the right of pattern index 120,
    we will store this adjacency rule as follow:

                     A[120][1].add(42)

    Here '1' stands for 'right' or 'East'/'E'

    0 = left or West/W
    1 = right or East/E
    2 = up or North/N
    3 = down or South/S '''

    # Comparing patterns to each other
    for i1 in xrange(npat):
        for i2 in xrange(npat):
            for dir in (0, 2):
                if compatible(patterns[i1], patterns[i2], dir):
                    A[i1][dir].add(i2)
                    A[i2][dir+1].add(i1)

def compatible(p1, p2, dir):

    '''NOTE:
    what is refered as 'columns' and 'rows' here below is not really columns and rows
    since we are dealing with 1D patterns. Remember here N = 3'''

    # If the first two columns of pattern 1 == the last two columns of pattern 2
    # --> pattern 2 can be placed to the left (0) of pattern 1
    if dir == 0:
        return [n for i, n in enumerate(p1) if i%N!=2] == [n for i, n in enumerate(p2) if i%N!=0]

    # If the first two rows of pattern 1 == the last two rows of pattern 2
    # --> pattern 2 can be placed on top (2) of pattern 1
    if dir == 2:
        return p1[:6] == p2[-6:]

def draw():    # Equivalent of a 'while' loop in Processing (all the code below will be looped over and over until all cells are collapsed)
    global H, W, grid

    ### OBSERVATION
    # Find cell with minimum non-zero entropy (not collapsed yet)

    '''Randomly select 1 cell at the first iteration (when all entropies are equal),
       otherwise select cell with minimum non-zero entropy'''

    emin = int(random(d*d)) if frameCount <= 1 else H.index(min(H))

    # Stoping mechanism

    ''' When 'H' array is full of 'collapsed' cells --> stop iteration '''

    if H[emin] == 'CONT' or H[emin] == 'collapsed':
        print 'stopped'
        noLoop()
        return

    ### COLLAPSE
    # Weighted choice of a pattern

    ''' Among the patterns available in the selected cell (the one with min entropy),
        select one pattern randomly, weighted by the frequency that pattern appears in the input image.
        With Python 2.7 no possibility to use random.choice(x, weight) so we have to hard code the weighted choice '''

    lfreqs = [b * freqs[i] for i, b in enumerate(W[emin])] # frequencies of the patterns available in the selected cell
    weights = [float(f) / sum(lfreqs) for f in lfreqs] # normalizing these frequencies
    cumsum = [sum(weights[:i]) for i in xrange(1, len(weights)+1)] # cumulative sums of normalized frequencies
    r = random(1)
    idP = sum([cs < r for cs in cumsum])  # index of selected pattern

    # Set all patterns to False except for the one that has been chosen
    W[emin] = [0 if i != idP else 1 for i, b in enumerate(W[emin])]

    # Marking selected cell as 'collapsed' in H (array of entropies)
    H[emin] = 'collapsed'

    # Storing first color (top left corner) of the selected pattern at the location of the collapsed cell
    Output[emin] = patterns[idP][0]

    ### PROPAGATION
    # For each neighbor (left, right, up, down) of the recently collapsed cell
    for dir, t in enumerate(directions):
        x = (emin%d + t[0])%d
        y = (emin/d + t[1])%d
        idN = x + y * d #index of neighbor

        # If that neighbor hasn't been collapsed yet
        if H[idN] != 'collapsed':

            # Check indices of all available patterns in that neighboring cell
            available = [i for i, b in enumerate(W[idN]) if b]

            # Among these indices, select indices of patterns that can be adjacent to the collapsed cell at this location
            intersection = A[idP][dir] & set(available)

            # If the neighboring cell contains indices of patterns that can be adjacent to the collapsed cell
            if intersection:

                # Remove indices of all other patterns that cannot be adjacent to the collapsed cell
                W[idN] = [True if i in list(intersection) else False for i in xrange(npat)]

                ### Update entropy of that neighboring cell accordingly (less patterns = lower entropy)

                # If only 1 pattern available left, no need to compute entropy because entropy is necessarily 0
                if len(intersection) == 1:
                    H[idN] = '0' # Putting a str at this location in 'H' (array of entropies) so that it doesn't return 0 (float) when looking for minimum entropy (min(H)) at next iteration

                # If more than 1 pattern available left --> compute/update entropy + add noise (to prevent cells to share the same minimum entropy value)
                else:
                    lfreqs = [b * f for b, f in izip(W[idN], freqs) if b]
                    ent = math.log(sum(lfreqs)) - sum(map(lambda x: x * math.log(x), lfreqs)) / sum(lfreqs)
                    H[idN] = ent + random(.001)

            # If no index of adjacent pattern in the list of pattern indices of the neighboring cell
            # --> mark cell as a 'contradiction'
            else:
                H[idN] = 'CONT'

    # Draw output

    ''' dxd grid of cells (squares) filled with their corresponding color.
        That color is the first (top-left) color of the pattern assigned to that cell '''

    for i, c in enumerate(Output):
        x, y = i%d, i/d
        fill(c)
        rect(x * xs, y * ys, xs, ys)

        # Displaying corresponding entropy value
        fill(0)
        text(H[i], x * xs + xs/2 - 12, y * ys + ys/2)

Problem
Despite all my efforts to carefully put into code all the steps described above, this implementation returns very odd and disappointing results:
Example of a 20x20 output

Both the pattern distribution and the adjacency constraints seem to be respected (same amount of blue, green, yellow and brown colors as in input and same kind of patterns: horizontal ground , green stems).
However these patterns:

*

*are often disconnected

*are often incomplete (lack of "heads" composed of 4-yellow petals)

*run into way too many contradictory states (grey cells marked as "CONT")

On that last point, I should clarify that contradictory states are normal but should happen very rarely (as stated in the middle of page 6 of this paper and in this article)
Hours of debugging convinced me that introductory steps (1 to 5) are correct (counting and storing patterns, adjacency and entropy computations, arrays initialization). This has led me to think that something must be off with the core part of the algorithm (steps 6 to 8). Either I am implementing one of these steps incorrectly or I am missing a key element of the logic.
Any help regarding that matter would thus be immensely appreciated !
Also, any answer that is based on the script provided (using Processing or not) is welcomed.
Useful additionnal ressources:
This detailed article from Stephen Sherratt and this explanatory paper from Karth & Smith.
Also, for comparison I would suggest to check this other Python implementation (contains a backtracking mechanism that isn't mandatory) .
Note: I did my best to make this question as clear as possible (comprehensive explanation with GIFs and illustrations, fully annotated code with useful links and ressources) but if for some reasons you decide to vote it down, please leave a brief comment to explain why you're doing so.

A: While looking at the live demo linked in one of your examples, and based on a quick review of the original algorithm code, I believe your error lies in the "Propagation" step.
The propagation is not just updating the neighbouring 4 cells to the collapsed cell. You must also update all of those cells neighbours, and then the neighbours to those cells, etc, recursively. Well, to be specific, as soon as you update a single neighbouring cell, you then update its neighbour (before getting to the other neighbours of the first cell), i.e. depth-first, not breadth-first updates. At least, that's what I gather from the live demo.
The actual C# code implementation of the original algorithm is quite complicated and I don't fully understand it, but the key points appear to be creation of the "propagator" object here, as well as the Propagate function itself, here.

A: The hypothesis suggested by @mbrig and @Leon that the propagation step iterates over a whole stack of cells (instead of being limited to a set of 4 direct neighbors) was correct. The following is an attempt to provide further details while answering my own questions.
The problem occured at step 7, while propagating. The original algorithm does update the 4 direct neighbors of a specific cell BUT:

*

*the index of that specific cell is in turns replaced by the indices of the previously updated neighbors.

*this cascading process is triggered every time a cell is collapsed

*and last as long as the adjacent patterns of a specific cell are available in 1 of its neighboring cell
In other words, and as mentionned in the comments, this is a recursive type of propagation that updates not only the neighbors of the collapsed cell, but also the neighbors of the neighbors... and so on as long as adjacencies are possible.
Detailed Algorithm
Once a cell is collapsed, its index is put in a stack. That stack is meant later to temporarily store indices of neighoring cells
stack = set([emin]) #emin = index of cell with minimum entropy that has been collapsed

The propagation will last as long as that stack is filled with indices:
while stack:

First thing we do is pop() the last index contained in the stack (the only one for now) and get the indices of its 4 neighboring cells (E, W, N, S). We have to keep them withing bounds and make sure they wrap around.
while stack:
    idC = stack.pop() # index of current cell
    for dir, t in enumerate(mat):
        x = (idC%w + t[0])%w
        y = (idC/w + t[1])%h
        idN = x + y * w  # index of neighboring cell

Before going any further, we make sure the neighboring cell is not collapsed yet (we don't want to update a cell that has only 1 pattern available):
        if H[idN] != 'c':

Then we check all the patterns that could be placed at that location. ex: if the neighboring cell is on the left of the current cell (east side), we look at all the patterns that can be placed on the left of each pattern contained in the current cell.
            possible = set([n for idP in W[idC] for n in A[idP][dir]])

We also look at the patterns that are available in the neighboring cell:
            available = W[idN]

Now we make sure that the neighboring cell really have to be updated. If all its available patterns are already in the list of all the possible patterns —> there's no need to update it (the algorithm skip this neighbor and goes on to the next) :
            if not available.issubset(possible):

However, if it is not a subset of the possible list —> we look at the intersection of the two sets (all the patterns that can be placed at that location and that, "luckily", are available at that same location):
                intersection = possible & available

If they don't intersect (patterns that could have been placed there but are not available) it means we ran into a "contradiction". We have to stop the whole WFC algorithm.
                if not intersection:
                    print 'contradiction'
                    noLoop()

If, on the contrary, they do intersect --> we update the neighboring cell with that refined list of pattern's indices:
                W[idN] = intersection

Because that neighboring cell has been updated, its entropy must be updated as well:
                lfreqs = [freqs[i] for i in W[idN]]
                H[idN] = (log(sum(lfreqs)) - sum(map(lambda x: x * log(x), lfreqs)) / sum(lfreqs)) - random(.001)

Finally, and most importantly, we add the index of that neighboring cell to the stack so it becomes the next current cell in turns (the one whose neighbors will be updated during the next while loop):
                stack.add(idN)

Full updated script
from collections import Counter
from itertools import chain
from random import choice

w, h = 40, 25
N = 3

def setup():
    size(w*20, h*20, P2D)
    background('#FFFFFF')
    frameRate(1000)
    noStroke()

    global W, A, H, patterns, freqs, npat, mat, xs, ys

    img = loadImage('Flowers.png')
    iw, ih = img.width, img.height
    xs, ys = width//w, height//h
    kernel = [[i + n*iw for i in xrange(N)] for n in xrange(N)]
    mat = ((-1, 0), (1, 0), (0, -1), (0, 1))
    all = []

    for y in xrange(ih):
        for x in xrange(iw):
            cmat = [[img.pixels[((x+n)%iw)+(((a[0]+iw*y)/iw)%ih)*iw] for n in a] for a in kernel]
            for r in xrange(4):
                cmat = zip(*cmat[::-1])
                all.append(cmat)
                all.append(cmat[::-1])
                all.append([a[::-1] for a in cmat])

    all = [tuple(chain.from_iterable(p)) for p in all]
    c = Counter(all)
    patterns = c.keys()
    freqs = c.values()
    npat = len(freqs)

    W = [set(range(npat)) for i in xrange(w*h)]
    A = [[set() for dir in xrange(len(mat))] for i in xrange(npat)]
    H = [100 for i in xrange(w*h)]

    for i1 in xrange(npat):
        for i2 in xrange(npat):
            if [n for i, n in enumerate(patterns[i1]) if i%N!=(N-1)] == [n for i, n in enumerate(patterns[i2]) if i%N!=0]:
                A[i1][0].add(i2)
                A[i2][1].add(i1)
            if patterns[i1][:(N*N)-N] == patterns[i2][N:]:
                A[i1][2].add(i2)
                A[i2][3].add(i1)

def draw():
    global H, W

    emin = int(random(w*h)) if frameCount <= 1 else H.index(min(H))

    if H[emin] == 'c':
        print 'finished'
        noLoop()

    id = choice([idP for idP in W[emin] for i in xrange(freqs[idP])])
    W[emin] = [id]
    H[emin] = 'c'

    stack = set([emin])
    while stack:
        idC = stack.pop()
        for dir, t in enumerate(mat):
            x = (idC%w + t[0])%w
            y = (idC/w + t[1])%h
            idN = x + y * w
            if H[idN] != 'c':
                possible = set([n for idP in W[idC] for n in A[idP][dir]])
                if not W[idN].issubset(possible):
                    intersection = possible & W[idN]
                    if not intersection:
                        print 'contradiction'
                        noLoop()
                        return

                    W[idN] = intersection
                    lfreqs = [freqs[i] for i in W[idN]]
                    H[idN] = (log(sum(lfreqs)) - sum(map(lambda x: x * log(x), lfreqs)) / sum(lfreqs)) - random(.001)
                    stack.add(idN)

    fill(patterns[id][0])
    rect((emin%w) * xs, (emin/w) * ys, xs, ys)

Overall improvements
In addition to these fixes I also did some minor code optimization to speed-up both the observation and propagation steps, and shorten the weighted choice computation.

*

*The "Wave" is now composed of Python sets of indices whose size decrease as cells are "collapsed" (replacing large fixed size lists of booleans).

*Entropies are stored in a defaultdict whose keys are progressively deleted.

*The starting entropy value is replaced by a random integer (first entropy calculation not needed since equiprobable high level of uncertainty at start)

*Cells are diplayed once (avoiding storing them in a array and redrawing at each frame)

*The weighted choice is now a one-liner (avoiding several dispensable lines of list comprehension)


text:
Q: Errors after updating to Android 3.0 and SDK 27 After Android Studio was released to 3.0 I was forced to update my SDK from 25 to 27 (couple libraries problems).
But now when try to build my app I get next error messages:
>Information:Gradle tasks [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar]
C:\Users\Alice\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.0.0.aar\63ec32742d97434c1d2e0dbe96345ab9\res\values\values.xml
Error:(252, 5) error: resource android:attr/foregroundInsidePadding is private.
C:\Users\Alice\AndroidStudioProjects\Ghiduldrumetului cu Loco\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml
Error:(941) resource android:attr/foregroundInsidePadding is private.
Error:failed linking references.
Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:Execution failed for task ':app:processDebugResources'.
> Failed to execute aapt
Information:BUILD FAILED in 16s
Information:7 errors
Information:0 warnings
Information:See complete output in console

Any suggestion how to fix it?

A: I fixed adding android.enableAapt2=false to gradle.properties file.

A: Try disabling the AAPT2 by adding android.enableAapt2=false to your gradle.properties file.
Builds may fail while AAPT2 is enabled. Additionally, AAPT2 is currently not compatible with Robelectric. If your build fails due to an AAPT2 resource processing issue or you want to use Roboelectric, you can disable AAPT2 by setting android.enableAapt2=false in your gradle.properties file and restarting the Gradle daemon by running ./gradlew --stop from the command line.
Reference :
https://developer.android.com/studio/build/gradle-plugin-3-0-0.html

A: Check if you're using "android:attr/foregroundInsidePadding" anywhere in your resources. It should be "attr/foregroundInsidePadding" instead.
More info: https://developer.android.com/studio/build/gradle-plugin-3-0-0-migration.html#aapt2


text:
Q: React.cloneElement { ReactComponent as SomeSVG } I am trying to get an SVG, which is passed as a prop. After I get it in the child component I want to add some props like that:
{React.cloneElement(ReactSVGasProp, { className: class })}

But I get:

A: try to replace ReactSVGasProp with <ReactSVGasProp/>


text:
Q: One hot encoding for logit and the sklearn pipeline I am trying to use the Dalex package in Python to visualize certain characteristics of a binary logit model.
I copied a piece of code from the example book here
(the whole fifth code cell) but now I am not quite sure about how the results should be interpreted...
In my basic logit model - which I created using statsmodels - I have manually selected one reference-level variable for each category in order to avoid multicollinearity (this means that all the results from the model are interpreted with respect to the reference level).
But when I use the piece of code from the link above (also copied below this post), it first creates some pipeline object in sklearn, one-hot encodes the categorical variables, and then the pipeline object is fitted to the data and used in the Dalex explainer as the model to be explained.
The problem is that when I use a function like model_profile() in Dalex, which should output a graph showing the ceteris paribus effect of a variable on the prediction, I do not know how to interpret the results because it seems as if all values in one categorical variable are included in the graph.
For example, the model shows the effect of the "gender" categorical variable on the average prediction for both male and female...
This also shows a horizontal line named "mean prediction" but what is the "mean prediction"? Was it calculated based on male as a reference level, or female?
I am really confused here about what the results mean... Can anyone please clarify this? The function model_profile() I am trying to use is also explained in the notebook. Thank you!
The piece of code I copied:
    numerical_features = ['age', 'fare', 'sibsp', 'parch']
    numerical_transformer = Pipeline(
        steps=[
            ('imputer', SimpleImputer(strategy='median')),
            ('scaler', StandardScaler())
        ]
    )

    categorical_features = ['gender', 'class', 'embarked']
    categorical_transformer = Pipeline(
        steps=[
            ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),
            ('onehot', OneHotEncoder(handle_unknown='ignore'))
        ]
    )

    preprocessor = ColumnTransformer(
        transformers=[
            ('num', numerical_transformer, numerical_features),
            ('cat', categorical_transformer, categorical_features)
        ]
    )

    classifier = MLPClassifier(hidden_layer_sizes=(150,100,50), max_iter=500, random_state=0)

    clf = Pipeline(steps=[('preprocessor', preprocessor),
                          ('classifier', classifier)])
    clf.fit(X, y)
    exp = dx.Explainer(clf, X, y)

A: Why is this happening?
This is happening because by default, sklearn's OneHotEncoder does the one hot transformation for every category in your data. For linear models like logit, however, it is usually preferred to leave one of the categories out to avoid multicollinearity and to make your results interpretable with regards to a reference point. In this case, you need to change the default settings of your encoder.
Example
You can achieve that by setting drop="first", which drops the first category of the one hot encoding process. The example below illustrates how that would work on a simple example. Here, the "female" category is dropped from the one hot encoding and only the "male" category gets encoded, which returns the result you are expecting. Note that this also works for non-binary features.
from sklearn.preprocessing import OneHotEncoder
X = pd.DataFrame({"gender":["male","female","female","male"]})
OHE = OneHotEncoder(drop="first")
OHE.fit_transform(X).toarray()
#[[1.],
# [0.],
# [0.],
# [1.]]
OHE.get_feature_names()
#['x0_male']

What you need to do
So, all you need to change in your code is the following line in your pipeline definition:
'onehot', OneHotEncoder(drop='first', handle_unknown='ignore')


text:
Q: Remove list in list I have a list that stores an instance of the list. I want to remove the object from the sublist with IdName == "149"
        List<Product> productList = new List<Product>()
        {
            new Product()
            {
                Id = 1,
                Model = "Phone",
                TypeProd = new CheckTypes() { ChTypes = new List<CHType> { new CHType() { Id =  8, IdName = "261"}, new CHType () {Id = 9 , IdName = "149" } } }

            },
            new Product()
            {
                Id = 1,
                Model = "Printer",
                TypeProd = new CheckTypes() { ChTypes = new List<CHType> { new CHType() { Id =  8, IdName = null}, new CHType () {Id = 8 , IdName = "261" } } }
            }
        };

        var pr = productList.Select(s => s.TypeProd).Where(w => w.ChTypes.Any(a => a.IdName != null && a.IdName.Contains("149"))).ToList();
        // I
        var pr0 = pr.Select(s => s.ChTypes).Where(w => w.Any(a => a.Id == 9)).ToList();
        // II
        var pr1 = pr.Select(s => s.ChTypes).Except(pr0);
        // III
        pr.Select(s=>s.ChTypes).ToList().RemoveAll(a => a.Any(item => item.IdName.Contains("149")));
        foreach (var item in pr)
        {
            foreach (var item2 in item.ChTypes)
            {
                Console.WriteLine(item2.IdName);
            }

            Console.WriteLine("End");
        }

        Console.ReadKey();

I get to delete the whole sequence, but how to delete one element from the sequence?

A: Use Remove() to remove a given item, or use RemoveAt() to remove the item at a given location.

A: I think, you are complicating it more than it needs to be. You simply need to loop over all the ChTypes List and remove the unwanted ChType. It can be easily accomplished by the below code
foreach (var chType in productList.Select(prod => prod.TypeProd.ChTypes))
    chType.RemoveAll(c => c.IdName != null && c.IdName.Contains("149"));

All your LINQ lines for pr, pr0, pr1 and pr.Select().ToList().RemoveAll() are all unnecessary. Also, in your current code you are picking up only CHType with Id = 9, not sure if that is by mistake or your code is correct but your question missed specifying it.
Since the OP insists on avoiding foreach below is a a bad LINQ way of doing it
productList.Select(prod => prod.TypeProd.ChTypes)
           .Select(chType => chType.RemoveAll(c => c.IdName != null && c.IdName.Contains("149")))
           .ToList();


text: Q: Почему Fluent forms отправляет письмо из формы дважды? На сайте есть контактная форма fluent forms. Письма отправляются с помощью WP Mail SMTP. Почему при отправке одной формы на почту приходит два одинаковых письма? Как это исправить? Есть в плагине какая-то настройка переадресации писем или дублирования? С почтовым ящиком все в порядке, письма из других почт приходят в одном экземпляре.


text:
Q: Using "only because" in a different way?
1- The squad is only on night shift because they disobeyed a
  direct order to save me.

I saw this sentence above but it seems kind of unusual to me. I would say it this way:

2- The squad is on night shift only because they disobeyed a
  direct order to save me.

Do they mean the same thing? Is there a difference between them? Using "only" in that position can imply different things I think. (I am talking about the position of "only" in sentence 1)

A: Yes your sentences 1 and 2 have identical meanings.
In general "X is only A because Z" and "X is A only because Z" will have identical meanings. The exception will be when "only A" forms a distinct term, usually when A is some sort of level in a ranking system. For example:

*

*This group are only novices because they have not learned how to perform squeezes. (The lack of the ability to perform squeezes shows that they are still novices.)

*This group are novices only because they have not learned how to perform squeezes. (The ability to perform squeezes is the only thing the group lacks. once they master that, they will no longer be novices.)

Evene here the difference is subtle.


text:
Q: How to implement a callback method within DLL (Delphi / TJVPluginManager + TJvPlugin) I'm building an application working with plugins. I'm using the excellent JVCL plugin framework. I first started to use package plugin. It worked like a charm but had a big drawback : the needs to give runtimes bpl (23Mo). So I switch to DLL plugin.
I need to call a method (procedure having 3 parametes) from hostapplication but I don't know how to do it. OBones explained in the Jedi newgroup to use callback functions but I have no clue on how to achieve this.
Can someone kindly explain me or better, send me an example? You can take the JVCL  1SimplePlugin demo and update it.
Thank in in advance
BR
Stephane Wierzbicki

A: The basic concept is pretty simple.  A callback method is a pointer to a method that you pass to some code so that it can call it at a specific time to allow you to customize its behavior.  If you have any experience at all with Delphi, you're already familiar with callback methods under a different name: "event handlers".
Try something like this in your plugin:
type
   TMyEvent = procedure(param1, param2, param3: integer) of object;

procedure AddCallback(callback: TMyEvent);

This procedure would take the TMyEvent method pointer passed in and store it somewhere. Let's say in a variable called FCallback.  When the time comes for it to call your app, the code would look like this:
if assigned(FCallback) then
   FCallback(param1, param2, param3);

You would call it from your app like this, when you're setting up the plugin:
MyPlugin.AddCallback(self.callbackProc);

Sometimes you'll need to put an @ in front of it (@self.callbackProc) so the compiler can tell that it's a method pointer and not a method call, but this is not always necessary.


text:
Q: I thought only usercontrol can navigate page inside a window frame in WPF app, is there any workarounds? I am trying to jump to an error page if reading data fails, although I thought only if usercontrol activates(eg. button pressed) can successfully navigate, but is there anyway to do it automactally?
Window
|--Page
|--Page

*

*Windows

*--Page

*--Page

Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;

namespace Launcher
{
    /// <summary>
    /// Interaction logic for BootPage.xaml
    /// </summary>
    public partial class BootPage : Page
    {
        public BootPage()
        {
            InitializeComponent();
            readConfig();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            bootError(1001); **//This works**
        }

        void readConfig()
        {

            string gamePath;
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("e:\\bootstrap.xml");
            XmlNodeList boot = xmlDoc.DocumentElement.SelectNodes("/config/startup/arkkdmca/boot");

            foreach (XmlNode node in boot)
            {
                try
                {
                    gamePath = node.SelectSingleNode("drive").InnerText + ":\\" + node.SelectSingleNode("directory").InnerText;
                    MessageBox.Show(gamePath);
                }
                catch(Exception)
                {
                    gamePath = "null";
                    bootError(1001); **//This Failed**
                    return;
                }
            }
        }

        void bootError(int errorCode)
        {
            this.NavigationService.Navigate(new ErrorPage(errorCode));
        }
    }
}


text:
Q: React-Router Match-component does not trigger shouldComponentUpdate() In my React app build on estejs (devstack), which uses react-router, I ran into the following problem:
<Match pattern="/cards/:sub?" component={Cards}/>
Matches localhost:3000/cards and localhost:3000/cards/test perfectly,
but does not call shouldComponentUpdate() as expected from the
documentation. Since :sub is a parameter, it should just change the prop this.props.params.sub of the card component and because of that also call shouldComponentUpdate() where I then want to return false to denie the render()-call.
Why does the Match component not just update the prop but trigger a not denieable rerender of my component?
Any suggestions?
Thanks!


text:
Q: Buttons are covering Scrollview check out this code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ScrollView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fadeScrollbars="true"
    android:scrollbarStyle="insideInset" >

    <TextView
        android:id="@+id/txt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:autoLink="all"
        android:paddingLeft="3dp"
        android:paddingRight="3dp"
        android:textIsSelectable="true" />
</ScrollView>

<Button
    android:id="@+id/nextbtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:onClick="nextButton"
    android:text="@string/next" />

<Button
    android:id="@+id/backbtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:onClick="prevButton"
    android:text="@string/back" />

the result i am getting is that, while the scrollview and text is showing, the buttons at the bottom left and bottom left are on top of the text/scrollview. i have tried using linearlayout, but no luck. help, please.

A: Try the following by adding android:layout_above="@+id/nextbtn" at your ScrollView :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ScrollView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fadeScrollbars="true"
        android:scrollbarStyle="insideInset"
        android:layout_above="@+id/nextbtn" >

        <TextView
            android:id="@+id/txt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:autoLink="all"
            android:paddingLeft="3dp"
            android:paddingRight="3dp"
            android:textIsSelectable="true" />
    </ScrollView>

    <Button
        android:id="@id/nextbtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:onClick="nextButton"
        android:text="next" />

    <Button
        android:id="@+id/backbtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:onClick="prevButton"
        android:text="back" />

</RelativeLayout>

edit : Unfortunately the Justin V. answer doesn't work because Android fill the screen with your ScrollView and put your buttons below, out of the screen.


text:
Q: setup multiple webservers on network i have 2 webservers (windows and linux(ubuntu))
I am using a static IP and point all of my sites using defaults webserver(windows) port 80
I just setup a linux server for certain sites but need to know how I can route specific domains to that particular server on port 8080
I currently have this working
http://judsonlinux.dyndns.org:8080/
but again I need to know how to point specific domains to this. I have read some things about using reverse proxy on the windows server. Is this the way to go?
Thanks
UPDATE: I got the rewrite working but for some reason its not pulling up the site. Its going to the default apache server page.
here is my conf...

Ther is an index page in public folder

A: after setting up the linux server, I had to change the default port on linux to 8080, then added this on my main server(80) in windows. It now works.  a website in IIS on windows. Then used the URL rewrite rule as follows.

A: You can write rewrite rules for the domains.
ex: in apache
RewriteCond %{HTTP_HOST} ^(www\.)?domain1.org$  [NC]
RewriteRule ^(.*)$ http://judsonlinux.dyndns.org:8080/$1 [P,L]

ex: IIS
 <rewrite>
  <rules>
    <rule name="Fail bad requests">
      <match url=".*"/>
      <conditions>
        <add input="{HTTP_HOST}" pattern="localhost" negate="true" />
      </conditions>
      <action type="AbortRequest" />
    </rule>
    <rule name="Redirect from blog">
      <match url="^domain/([_0-9a-z-]+)/([0-9]+)" />
      <action type="Redirect" url="www.d.com:8080/{R:2}/{R:1}" redirectType="Found" />
    </rule>
    <rule name="Rewrite to article.aspx">
      <match url="^article/([0-9]+)/([_0-9a-z-]+)" />
      <action type="Rewrite" url="article.aspx:8080?id={R:1}&title={R:2}" />
    </rule>
  </rules>
</rewrite>

ref:IIS Reference


text:
Q: How to search for two strings in one line using batch and then count the occurence I have this project in mind, my goal is to achieve below condition using a batch(.bat) file.
Search through a .log file the patterns, "[YYYY-MM-DD HH:MM:SS]"(1) and "Error"(2) in a single line and then output the total number of occurrences in .csv file.
Code used:
@ECHO OFF
findstr /i /C:"Error" *.log | find /i /c "Error" >> Error.csv

Here is a sample log file pattern:
[2012-04-25 16:20:2] [INFO] [SAMPLE] Error in...

Expected output in .csv file

Here is the expected result:
[Time]
[Error Count]
1:00-2:00         125
2:00-3:00         45
3:00-4:00         246
and so on until 23:00-24:00
The counts of the string ERROR, which will be distributed under the column Error Count should be fetched/count the occurrence depending on the timestamp.
Thanks so much. I appreciate the help! :-)

A: I almost certainly missed something in testing, but this should be along the lines of what you're looking for.
@echo off
setlocal enabledelayedexpansion
cls

:: Proper regex would make this /\[\d{4}(-\d{2}){2} \d{2}(:\d{2}){2}\]/g
:: Unfortunately, findstr regex is extremely limited and so our options
:: are either a short search string or a super long string
set regex_check_1=\[[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9]\]
set regex_check_2=Error

:: Search (the results of searching for regex_check_1) for regex_check_2
:: and output the results to a temp file for later processing
findstr /R /C:"%regex_check_1%" data.log|findstr /I /R /C:"%regex_check_2%">temp.txt

:: Initializes the error_count arraylike values to 0
for /L %%A in (0,1,23) do set error_count[%%A]=0

:: Searches the HH column of the timestamp and, every time a number is found,
:: increments the value of the element in the error_count arraylike
for /F "tokens=2 delims=: " %%A in (temp.txt) do (
    REM convert HH to H if HH<10 to avoid number being considered octal
    set /a hr_num=1%%A-100
    call :arraylike_inc !hr_num!
)

:: Output the data to the CSV file
echo Time Error Count>log.csv
for /L %%A in (0,1,23) do (
    set start_hour=%%A
    set /a end_hour=%%A+1

    echo !start_hour!:00-!end_hour!:00 !error_count[%%A]!>>log.csv
)

:: End the script here so that we don't accidentally call the function again
exit /b

:: Increments the value of error_count[hour]
:: This is a function because delayed exansion can only take us so far
:arraylike_inc
set /a error_count[%1]=!error_count[%1]!+1


text:
Q: Nginx rewrite rule for codeigniter for URL parameters I did the following configurations for nginx server for code igniter and worked correctly , unfortunately there is one case not working.
When I request URL with parameter Like
servername.com/ControllerName/methodName?param=value
 I got Not found Page 404
Server Configurations :
server {
    # access from localhost only
    listen       127.0.0.1:80;
    server_name  serverName.com;
    root         API;

    log_not_found off;
    charset utf-8;

    access_log  logs/accessservername.log main;
index index.php;
    # handle files in the root path /www
     location / {
         try_files $uri $uri/ /index.php?$args;
     }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   API;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9100
    #
    location ~ \.php$ {
        try_files      $uri =404;
        fastcgi_pass   php;
        fastcgi_index  index.php;
        #fastcgi_param  PHP_FCGI_MAX_REQUESTS 1000;
        #fastcgi_param  PHP_FCGI_CHILDREN 100;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_param   REMOTE_ADDR $http_x_real_ip;
        include        fastcgi_params;

    }

    # add expire headers and speed up image access with a vary header
    location ~* ^.+.(gif|ico|jpg|jpeg|png|flv|swf|pdf|mp3|mp4|xml|txt|js|css)$ {
        expires 30d;
        add_header Vary Accept-Encoding;
    }

    # only allow these request methods
    if ($request_method !~ ^(GET|HEAD|POST)$ ){ return 405; }

}


text:
Q: how to develop modular software with web services I need to develop this application which:
Has 1 central module, and 3 sub-modules. In a simple java project would be:
package com.proj.manager
   Gui.Java
   MonitorizeSubModules.Java
   WebServiceSOAP.Java
package com.proj.submodule1
   ManageConnections.Java
   DoThingsInThreads.Java
package com.proj.submodule2
   ManageConnections.Java
   DoThingsInThreads.Java

Because each one of these packages will tend to be complex, I would like to develop them in a modular way (for example, using OSGi), and provide internal APIs for them to communicate with each other.
So, my main question is: How do I develop my project as a modular application and how can I make the application interface (ex. com.proj.manager.WebServicesSOAP.Java) available as Web Services?
I hope I made my question clear, and that it is not too newbie for the community :)
Thanks.

A: In the meanwhile, I choose to use EJB by Netbeans (Enterprise Java Beans). It does exactly what I need: Netbeans Enterprise Applications


text:
Q: RestSharp deserialize utf-8 content into a class I am making a REST API call and the response JSON consists of UTF8-8 encoding. How can I deserialize into a class and have the encoding intact? Though this code doesn't fail but I lose the encoding.
var request = new RestRequest("some url", Method.GET);
request.AddHeader("Accept-Charset","utf-8");
request.AddHeader("Accept","*/*");
request.AddHeader("ContentType","application/x-www-form-urlencoded; charset=UTF-8");
request.AddHeader("Accept-Encoding", "gzip, deflate, br");
request.AddUrlSegment("FrameworkGUID", FrameworkGUID);
var response = Client.Execute<RootObject>(request);
var str = System.Text.Encoding.UTF8.GetString(Encoding.ASCII.GetBytes(response.Content));
return JsonConvert.DeserializeObject<RootObject>(str);

JSON response:
{"fullStatement":"Extend polynomial identities to include factoring with complex numbers. For example, rewrite x\u00b2 + 4 as (x + 2i)(x \u2013 2i).","language":"en"}

Edit: I wasn't debugging correctly. The deserialization is happening fine. In fact you just need this code:
var request = new RestRequest("some url", Method.GET);
request.AddUrlSegment("FrameworkGUID", FrameworkGUID);
var response = Client.Execute<RootObject>(request);
return response.Data;


text:
Q: Building a .Net project from a Console Application I'm trying to set up a CI/CD enviroment, and decided to rely in c# as much as possible.
In order to do that, I created a console application that is going to be responsible from building several .Net projects.
One of those projects is a plain simple console application targeting .Net 6, but when building it, yields a couple of errors. The code from the builder project is this simple:
var projectFileName = @"..\..\..\..\ConsoleApp2\ConsoleApp2.csproj";
var pc = new ProjectCollection();
var GlobalProperty = new Dictionary<string, string>();

GlobalProperty.Add("Configuration", "Debug");
GlobalProperty.Add("Platform", "x86");
var BuidlRequest = new BuildRequestData(projectFileName, GlobalProperty, null, new string[] { "Build" }, null);
var buildResult = BuildManager.DefaultBuildManager.Build(new BuildParameters(pc), BuidlRequest);

I'm receiving the error:

Could not load SDK Resolver. A manifest file exists, but the path to
the SDK Resolver DLL file could not be found.  Manifest file path
'C:\Users\myUser\source\BuilderProject\bin\Debug\net6.0\SdkResolvers\Microsoft.Build.NuGetSdkResolver\Microsoft.Build.NuGetSdkResolver.xml'.
SDK resolver path:
C:\Users\myUser\source\BuilderProject\bin\Debug\net6.0\Microsoft.Build.NuGetSdkResolver.dll
C:\Users\myUser\source\repos\WpfApp1\ZConsoleApp2\ZConsoleApp2.csproj

Any clues in how to get rid of the error, on how to build a project from a .Net project? I have been flicking through many links but didn't find much information.
Thanks!


text:
Q: Can't Display All Records In Laravel Pivot Table I have a Players / Lessonhours pivot table that is saving all of the values passed to it from a form. In my view however, it only shows some of the records associated. It seems I am having a problem when I do a $players->lessonhour->toArray. When I do $lessonhours->players->toArray(), I only get some of the records. I can't see what I am doing wrong in the relationship setup. Something obviously needs tewaking. Can anyone help?
Tinker:

MySql:

Player Model:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Collective\Html\Eloquent\FormAccessible;
use Carbon\Carbon;

class Players extends Model
{
    public $table = "players";

    protected $fillable = array('fname', 'lname', 'gender', 'birthdate');

    public function users()
    {
        return $this->belongsTo('App\User', 'users_id');
    }

    public function lessonhours()
    {
        return $this->belongsToMany('App\Lessonhours', 'lessonhour_player',    'lessonhours_id', 'players_id');
    }

    public function getFullName($id)
    {
        return ucfirst($this->fname ) . ' ' . ucfirst($this->lname);
    }

   protected $dates = ['birthdate'];

    public function setBirthdateAttribute($value)
    {
        $this->attributes['birthdate'] = Carbon::createFromFormat('m/d/Y',   $value);
    }
}

Lessonhours Model:

     <?php

namespace App;

use Illuminate\Database\Eloquent\Model;
 use Collective\Html\Eloquent\FormAccessible;
use Carbon\Carbon;

class Lessonhours extends Model
{
    protected $fillable = array('signup_date', 'players_id', 'packages_id');

    public $table = "lessonhours";

    public function players()
    {
        return $this->belongsToMany('App\Players', 'lessonhour_player',  'lessonhours_id', 'players_id');
    }

    public function packages()
    {
        return $this->belongsTo('App\Packages', 'packages_id');
     }

    public function hoursused()
    {
       return $this->hasMany('App\Hoursused', 'lessonhours_id');
    }

    protected $dates = ['signup_date'];

    public function setSignUpDateAttribute($value)
    {
        $this->attributes['signup_date'] = Carbon::createFromFormat('m/d/Y',     $value);
    }
}

This is what the view shows. Everyone on the list should have at least 1 package, some have 2.

A: In Players model swap lessonhours_id and players_id:
public function lessonhours()
        {
            return $this->belongsToMany('App\Lessonhours', 'lessonhour_player', 'players_id', 'lessonhours_id');
        }


text:
Q: "SyntaxError: missing ) after argument list" I am getting this error in firebug:
SyntaxError: missing ) after argument list

From this code:
table +=
'
'+
  '
'+
  ''+this.zona+'	' +
  ''+this.rruga+'

	' +
  ''+this.dita+'	' +
  '	' +
'
'+
'
';

I am not quite sure which parenthesis ) is missing in my code.

A: This is because of your use of + with your quotes. You code
str = '...' + 'onclick="show(' + this.rruga + ', ' + this.id + ');"' + '...';

will generate HTML that looks like
onclick="show(hello world,foo bar);"

This obviously won't work, as your function's arguments are no longer quoted properly, so are treated as variable names, then the spaces cause the exception to be thrown. In a worst case scenario, that you do not have this.rruga or this.id quoted or HTML encoded, someone could possibly pass a specially crafted piece of code which would inject custom HTML into the page.
You can keep using a string as long as you encode your arguments so they're HTML-safe and won't end the quotes, and then adding quotes around them them (\').
HTML+JavaScript encoded quotes are \\" for \" and \\' for \'. The preceeding \\ is so that it does not break the JavaScript quotes, then the &foo; is the HTML-encoding for the character.
str = '...' + 'onclick="show(\''
            + (''+this.rruga).replace(/"/g, '\\"').replace(/'/g, '\\'') + '\', \''
            + (''+this.id).replace(/"/g, '\\"').replace(/'/g, '\\'') + '\');"'
            + '...';

As you are generating all of this in JavaScript, consider keeping your listener out of the HTML string and attaching it to the element with addEventListener or simply node.onclick. This will mean you can inherit the scope of where you are in the function you want (although this will still change to mean the Node), and if you use DOM methods you have much less to worry about by way of special encoding as the browser will do the work for you.

EDIT I'll add a function to make it easy for you
function quoteAndEscape(str) {
    return ''
        + '''                      // open quote '
        + (''+str)                     // force string
            .replace(/\\/g, '\\\\')    // double \
            .replace(/"/g, '\\"') // encode "
            .replace(/'/g, '\\'')  // encode '
        + ''';                     // close quote '
}

quoteAndEscape('I\'ll say "hello" to the WORLD!');
// 'I\'ll say \"hello\" to the WORLD!'
// which is a HTML-encoded JavaScript String literal.
// You may also want to encode the opening and closing quotes
// these ones don't need to be backslash-escaped though.
// edited that too

A: I assume what you posted is part of a command, so there's a preceeding '.
You can get this error message if this.rruga has special characters, for example a space.. eg: the code will create something like show(hello there, 12); which is syntactically incorrect. You can verify this by just checking the generated html content.
Solution: Put that argument within quotes. ...\''+this.rruga+'\'...

A: You can't use this inside '' .
Moreover, you need to use getAttribute() in order to get rugga  value from the specific element.
Here's a working fiddle.


text:
Q: Does meteor application need a flux-like architecture? The core of Flux is unidirectional data flow:

*

*View emit an Action to Dispatcher

*Dispatcher broadcast the Action to Store

*Store make data modification and notice View data changed

*View catch the change notification and make proper render.

But implementation of Meteor platform has similar architecture, as I think.

*

*View subscribe to Collections

*View call a Meteor method to update data

*In Meteor method, we do the data modification to change Collections

*View re-render the page automatically.

So, do we really need Flux in Meteor?

A: i don't think youre making the right comparison here. flux occurs mostly in the browser while meteor subscriptions/publications deal with caching/security and meteor methods deal with server calls.
the purpose of flux is to give your meteor application some sort of architecture, or organization.
from https://atmospherejs.com/meteorflux/meteorflux,

Flux is a new architecture created by Facebook for their reactive apps. Although they released to the public only 2 years ago, they have been using it for some more time. It has a new set of principles to make it simpler and easier to reason about than MVC:

*

*It decouples data/logic and views using an event bus: the Dispatcher.

*The data/logic is organized by common domains: the Stores.

*Views are not allowed to change the app state, only to dispatch Actions.

*It makes the data flow simpler (one-way only) and forbids cascading events.

  Do I need React?
No, you don't. React is just a frontend framework and Flux is an architecture. You can use it if you like, but the Flux principles can be applied even if you use Blaze, Angular, ViewModel, Blaze Components, Flow Components or whatever comes out next month.
Is Flux the best architecture for everything?
I don't think so. But it can be useful for sure. I find Flux apps easy to understand and reason about. A lot of Meteor apps lack architecture. Logic and state are spread among the different parts of the app and there is no way to know where is what. Debugging, scaling and testing becomes difficult.
When you choose an architecture you spend less time thinking "where do I put this" and more time just coding because it is clear where things belong. In the long run, it helps you make your app easier to understand, easier to test and easier to scale.
There are many different implementations of Flux, just like there are many different implementations of MVC. This is a good sign, and once you get the concept you can adapt Flux to your particular needs.


text:
Q: System Linq Enumerable error while using intersect I have 3 lists and I'm trying to display their common items in a text box, and while I am implementing the method
var result = l1.Intersect(l2);
textBox1.Text = "";
textBox1.Text = result.ToString();

while l1 is my first list and l2 is my second list
I get the error:

System.Linq.Enumerable+d__70`1[System.String]

any help would be appreciated.

A: Because result is an IEnumerable, and that interface does not override ToString(), you're seeing the default implementation of Object.ToString(), which is to return the fully qualified name of the type of the object.
To resolve this, you can decide how you want to display the items and write them out yourself, for example the following displays the items separated by a comma:
textBox1.Text = string.Join(", ", result);


text:
Q: User based deploying in Kubernetes I am slightly newbie on kubernetes. And we want the present some of our products as SaaS to our costumers. So i need the user based isolated deployments. After some research i decided to create a namespace to each user. Then deploy what user wants from our template to user's namespace. But there is a problem about port mapping. Lets say we have 6 user and all of them want's the deploy django app. So all of them wants to access their project from 80 and 443 ports. Is there any solution for this in kubernetes? If it is how should i proceed?
And how can i seperate each users deployments to diffrent networks or vlans to isolate their networks from each other?

A: You can either put a dedicated load balancer to each of them (the expensive solution, but straight forward), or make your Ingress Controller to only accept requests with a hostname, and point each hostname to it's service, in its namespace (cheap solution but complicate).
Load Balancer Solution:
This one is easy, if you are with a cloud provider, so every time a client exposes the app, you just create a LoadBalancer type service pointing to his app. Since for each app you get a new load balancer, you have no problem of port collision. Now, the drawbacks are that this you can do only with a cloud provider, and it will be quite expensive.
Ingress Solution:
This one is the pro solution. It's cheap, but it's also more complex. So, you would create an Ingress resource like this:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress
spec:
  tls:
  - secretName: tls
  rules:
  - host: site1.domain.com
    http:
      paths:
      - path: /path1/
        backend:
          serviceName: service1
          servicePort: 80
  - host: site2.domain.com
    http:
      paths:
      - backend:
          serviceName: service1
          servicePort: 80
    ...

Here, you just have one L7 load balancer, and that's Ingress Controller doing all the routing. Depending on Ingress Controller, you might get an L4 load balancer (e.g. nginx, Traefik), but still that's Ingres Controller doing the routing.
Complexity? You will have to figure out a way to update the Ingress Controller records without a downtime for other users. Also, on Kubernetes, an Ingress Controller can't pass a request from one namespace to another. So, the service needs to run in the same namespace that the Ingress resource has been created (Note, I'm saying Ingress resource, being the rules (like the yaml above); not Ingress Controller). This is a known limitation that Kubernetes team already announced that will never be changed, as it introduces a huge security hole.
You will need to create headless services without selectors in the same namespace that Ingress object, and separately create Endpoint objects pointing to the service in the other namespaces. It might look like cumbersome, but that's quite pro actually.

A: To separate external access to the apps you need to deploy an Ingress Controller and create different Ingresses pointing to Services of each application. Every Ingress will hold its unique URL per application.
To prohibit internal cross-namespace communication you need to deploy network policies. Fr this you'll need to deploy an addon.
Or you can solve it by deploying any common service mesh: Istio, Linkerd, Consul etc.


text:
Q: On the basis of quantity and product price, total price Update My HTML structure:

         129,00
        $

        <input type="text" value="1" name="am" id="quantity">
        <button class="submitbtn" type="submit">add to Cart</button>

My JS code:
$('#quantity').keyup(function(){
  $('#quantity').each(function () {
  var qty = $('#quantity').val();
  var price = $('#totalprice').val();
  var total = price * qty;
  });

  $('#totalprice').html(total);
});

I have found many examples, not suitable. :-(
After entering Quantity Item Price will be Automatically Updated. If "0", letter, "empty" or after canceling Original price must be restored.
I always get "0" value Back!
I am very grateful for any help!

A:    var price = $('#totalprice').val();//this is wrong!!!

get the  html of span.Not the value
var price = $('#totalprice').text();//this is the correct syntax

So,Your code becomes--:
  $('#quantity').keyup(function () {
        var qty = $('#quantity').val();
        var price = parseInt($('#totalprice').text()); //or $('#totalprice').html()
        var total = price * qty;
        $('#totalprice').html(total);
    });

A: Try this........HTML

        <input type="text" id="productPrice"/>

         129,00
        $

        <input type="text" value="1" name="am" id="quantity">
        <button class="submitbtn" type="submit">add to Cart</button>

...............JS........
$('#quantity').keyup(function(){
  var qty = $('#quantity').val();
  var price = $('#productPrice').val();
  var total = price * qty;

  $('#totalprice').html(total);
});

A: Why is there a loop on #quantity ? You don't need that. Try the following code.
$('#quantity').keyup(function () {
    var qty = $('#quantity').val();
    var price = parseInt($('#totalprice').text());
    var total = price * qty;
    $('#totalprice').html(total);
});

Notice parseInt($('#totalprice').text());
.val() doesn't work with span so you would have to use .text() and parse the result in int

A: Try
var $totalprice = $('#totalprice');
var price = parseInt($.trim($totalprice.text()).replace(',', '.'));
$totalprice.data('totalprice', price);
$('#quantity').keyup(function(){
    var qty = this.value;
    var price = $totalprice.data('totalprice');
    var total = price * qty;

    $totalprice.html(total ? total : price);
});

Note: The number formatting is not done

A: Your first problem is that totalprice is a span, so it doesn't have a .val() function (that's only for inputs), use .text() instead.
The contents of the span currently has a comma in it, which won't be automatically parsed into a number. You need to use parseFloat(), and you need to use a decimal point, not a comma.
parseFloat("129,50") is 129
parseFloat("129.50") is 129.50
Secondly, you're doing an each over your quantity fields but there's only one. Maybe you wanted that for the future (in which case you should use classes not IDs), but here's some JS that should implement the feature you wanted and fix your bug as well (untested):
$('#quantity').keyup(function(){
    var qty = $('#quantity').val();
    if (qty && qty > 0){
        var price = parseFloat($('#totalprice').text());
        var total = price * qty;
        $('#totalprice').text(total);
    }
    else{
        //Find a better way of restoring this value
        $('#totalprice').text("129.50");
    }
});

Hope this helps. :)


text:
Q: What exactly is "wordpress theming"? When a book says that it is all about wordpress theming, what does it mean?

A: In short, it refers to WordPress theme development.
Theme development, i.e. the creating, designing and developing of a theme that will be available for the WordPress CMS/platform. Themes can be accessed from the Appearance > Themes menu, and have settled on two niches, free and premium themes.
The book you mention, if about 'wordpress theming', will either guide you through, or point-out the relevant aspects of developing/customizing a theme for WordPress.
EDIT: Just to clarify, the verb 'theming' itself can be translated to skinning, customizing, adapting, etc. Hence, WordPress theming could also just refer to customizing rather subtle aspects and elements of an existing theme, such as widgets, navigation menus, and so on.


text:
Q: Using PDFsharp and MigraDoc to write to and then read from a PDF I'm trying to write verification code for our PDF generating routines, and I'm having difficulty getting PDFsharp to extract text from files created with MigraDoc. The ExtractText code works with other PDFs, but not with the PDFs that I generate with MigraDoc (see code below.)
Any tips on what I'm doing wrong?
//Create the Doc
var doc = new MigraDoc.DocumentObjectModel.Document();
doc.Info.Title = "VerifyReadWrite";
var section = doc.AddSection();
section.AddParagraph("ABCDEF abcdef");

//Render the PDF
var renderer = new PdfDocumentRenderer(true);
var pdf = new PdfDocument();
renderer.PdfDocument = pdf;
renderer.Document = doc;
renderer.RenderDocument();
var msOut = new MemoryStream();
pdf.Save(msOut, true);
var pdfBytes = msOut.ToArray();

//Read the PDF into PdfSharp
var ms = new MemoryStream(pdfBytes);
var pdfRead = PdfSharp.Pdf.IO.PdfReader.Open(ms, PdfDocumentOpenMode.ReadOnly);
var segments = pdfRead.Pages[0].ExtractText().ToList();

Results in the following:
segments[0] = "\0$\0%\0&\0'\0(\0)"
 segments[1] = "\0D\0E\0F\0G\0H\0I"
I'd expect to see:
segments[0] = "ABCDEF"
 segments[1] = "abcdef"
I'm using the ExtractText code from here:
C# Extract text from PDF using PdfSharp
and it works very well for all but PDFs generated with MigraDoc.
    public static IEnumerable<string> ExtractText(this PdfPage page)
    {
        var content = ContentReader.ReadContent(page);
        var text = content.ExtractText();
        return text.Select(x => x.Trim());
    }

    public static IEnumerable<string> ExtractText(this CObject cObject)
    {
        if (cObject is COperator)
        {
            var cOperator = (COperator) cObject;
            if (cOperator.OpCode.Name == OpCodeName.Tj.ToString() ||
                cOperator.OpCode.Name == OpCodeName.TJ.ToString())
            {
                foreach (var cOperand in cOperator.Operands)
                    foreach (var txt in ExtractText(cOperand))
                        yield return txt;
            }
        }
        else
        {
            var sequence = cObject as CSequence;
            if (sequence != null)
            {
                var cSequence = sequence;
                foreach (var element in cSequence)
                    foreach (var txt in ExtractText(element))
                        yield return txt;
            }
            else if (cObject is CString)
            {
                var cString = (CString) cObject;
                yield return cString.Value;
            }
        }
    }

A: It seems the code used to extract text does not support all cases.
Try new PdfDocumentRenderer(false) (instead of 'true'). AFAIK this will lead to a different encoding and the text extraction might work.


text:
Q: A set with volume zero can be covered by finitely many open boxes A set $X\subseteq\mathbb{R}^n$ is said to have $n$-dimensional volume zero iff for any $\epsilon>0$, there exist finitely many closed $n$-boxes $R_1,\cdots,R_s$ such that $X\subseteq \bigcup_i R_i$ and $\sum_{i} \text{vol}(R_i)<\epsilon$.
Given a set $X$ with volume zero, I would like to show that for any $\epsilon>0$, there exists such a cover where each point in $X$ is an interior point of the cover and its volume is less than $\epsilon$. In other words, is it possible to cover $X$ with open boxes instead (with total volume less than $\epsilon$)?
I encountered this problem in the proof of Proposition 7.1.8 in Multivariable Mathematics: Linear Algebra, Multivariable Calculus, and Manifolds by T. Shifrin. The proposition asserts that if the set $X$ of discontinuities of a bounded function $f:R\to\mathbb{R}$ has volume zero, then $f$ is integrable on $R$. In the proof, $X$ is covered in the manner mentioned in the previous paragraph so that the closure of the complement of the covered portion does not contain any discontinuity point. However, the author did not provide a proof for why such a cover exists. This is intuitive to me, but I struggle to produce a rigorous proof.

A: Hint: A closed box can be covered by an open box with slightly larger volume.
Hint 2: Trying to prove your statement about open boxes for some value of $\epsilon$, you want to apply the other statement that has closed boxes. But you don't need to apply it with the same $\epsilon$. You could apply it with, say, $\epsilon/2$ or $2\epsilon$ or $\epsilon^2$. Which of these would be useful for proving your statement?


text:
Q: How to make ng-select disabled using Reactive forms? How can I make ng-select disabled? I tried [disabled] property, but it does not work here. Also tried to make it disabled using form control, but nothing works.
Stackblitz example

A: You can disable/enable a form control when you initialize it by setting disabled to true
creds.push(this.fb.group({
  fruitType: this.fb.control({value: 'Apple', disabled: true})
}));

To disable/enable the control later dynamically in your component. You can do so by calling the disable/enable methods for that particular form control.
// To enable form control
fruitType.enable();

// To disable form control
fruitType.disable();

A: If you are looking to disable ng-select in html using any dynamic condition then you can use [readonly] property.
<ng-select
formControlName="myControl"
[readonly]="condition_resolving_to_true_or_false"
</ng-select>

A: you can set the value and the disabled state directly by pass an object same @nash11 example but without using this.fb.control it will be done internally
  addFruits() {
    const creds = this.form.controls.fruits as FormArray;
    creds.push(this.fb.group({
      fruitType: { value: 'Apple', disabled: true } //
    }));
  }

in case you want to pass a validator you can use an array and the initial value is an object
  addFruits() {
    const creds = this.form.controls.fruits as FormArray;
    creds.push(this.fb.group({
      fruitType: [{ value: 'Apple', disabled: true },Validators.required] //
    }));
  }

demo
initialize form control object by FormBuilder


text:
Q: UICollectionView self sizing not working for long text Below code working but when come to long text then it's cutting some of text show just according  view frame width for example replacing it with abstractions or using data normalization to avoid redundancy.
replacing it with abstractions or using data n showing other content not showing
class AyatWordByWordViewController : UIViewController {

        let celled = "celled"

        var texts : [String] = ["Don't", "repeat", "yourself", "is a principle", "of", "software development", "aimed", "at", "reducing", "repetition of software patterns", "replacing it with abstractions or using data normalization to avoid redundancy."]

        //word by work
        var collectionView : UICollectionView!

        override func viewDidLoad(){

           let alignedFlowLayout = UICollectionViewFlowLayout()
            alignedFlowLayout.scrollDirection = UICollectionView.ScrollDirection.vertical
            collectionView = UICollectionView(frame: .zero, collectionViewLayout: alignedFlowLayout)
            collectionView.delegate = self
            collectionView.dataSource = self
            collectionView.register(AyatTableViewWordByWordItemCell.self, forCellWithReuseIdentifier: celled)
            collectionView.backgroundColor = UIColor.clear
           self.view.addSubview(collectionView)
                collectionView.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 150, leftConstant: 10, bottomConstant: 0, rightConstant: 10, widthConstant: 0, heightConstant: 0)

            if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
               // flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
                flowLayout.estimatedItemSize = CGSize(width: 1, height:1)
            }
        }
    }

    extension AyatWordByWordViewController : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return texts.count
        }

        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier:celled, for: indexPath) as! AyatTableViewWordByWordItemCell
                cell.subTitleLabel.text = texts[indexPath.item]
                cell.backgroundColor = UIColor.blue

            return cell
        }

  }

cell :
public func fillSuperview() {
    translatesAutoresizingMaskIntoConstraints = false
    if let superview = superview {
        leftAnchor.constraint(equalTo: superview.leftAnchor).isActive = true
        rightAnchor.constraint(equalTo: superview.rightAnchor).isActive = true
        topAnchor.constraint(equalTo: superview.topAnchor).isActive = true
        bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true
    }
}

Used:
subTitleLabel.fillSuperview()

here is the output iPhoneX OS12.2

A: Please try below code
 let layout = yourCollectionView?.collectionViewLayout as! UICollectionViewFlowLayout
 layout.itemSize = UICollectionViewFlowLayout.automaticSize
 layout.estimatedItemSize = CGSize(width: 93, height: 31)
 layout.sectionInset = UIEdgeInsets(top: 0, left: 9, bottom: 0, right: 0)

Give label leading, trailing, top and bottom constraints with cell i hope its work for you


text:
Q: why would an express route be overwritten by react router on aws but not localhost I'm trying to create an api route to save lead data from my state in a react app. From my localhost, get and post work fine and when I go to the url, I get the a json, just as I wanted. However, when I sync these files to my amazon linux server, it uses the * route in my router instead of going to the correct url path.
here is what I have in server.js
app.use('/api/leads', leadRoute );

app.get('/', function (req, res) {
  res.sendFile(__dirname + 'static/index.html')
});

app.get('/static/bundle.js', (req, res) => {
  return res.sendFile(__dirname + '/dist/bundle.js');
});

app.use('*', function (req, res) {
  res.sendFile(__dirname + '/static/index.html')
});

A: The reason was that you are updating server-side code, and not restarting the server after the change.


text:
Q: Get max subject to conditions from another dataset's variable Here's a reproducible example:
year <- as.vector(c(rep(1949,5), rep(1950,5), rep(1951,5), rep(1952,5)))
bracket <- as.vector(c(rep(c(10,20,30,40,50),4)))

datasmall <- as.data.frame(cbind(year,bracket))

yearbig <- as.vector(c(rep(1949,10), rep(1950,10), rep(1951,10), rep(1952,11)))
earnings <- as.vector(runif(41, 10, 60))

databig <- as.data.frame(cbind(yearbig,earnings))

I want to create a new variable in the big database (let's call it maxbracket) that has the maximum bracket value from "datasmall" in a common given year (brackets values can change each year) among those only bracket values below the value of each given earnings observation.
I tried this:
databig$maxbracket <- NA
for (i in 1949:1952) {
databig$maxbracket[databig$yearbig==i] <- max(datasmall$bracket[datasmall$year==i &
(datasmall$bracket < databig$earnings[databig$yearbig==i])], na.rm = T)}

But it gives me an error. Any help welcome! Thanks!!

A: If I understand your question correctly, then with base R you may do
databig$maxbracket <- mapply(function(y, e)
  with(datasmall, max(bracket[year == y & bracket < e])), databig$yearbig, databig$earnings)
head(databig, 3)
#   yearbig earnings maxbracket
# 1    1949 12.32897         10
# 2    1949 10.87209         10
# 3    1949 50.04304         50

which is similar to your approach, just using mapply. In particular, there is no good reason to do any grouping by year here. So, we have a two-variate anonymous function taking a year and earnings, to which we provide the two columns of databig and apply them row by row. Given a specific pair (y,e) of databig, we look for a maximum bracket in datasmall such that year == y & bracket < e.

A: Assuming rate is not needed in datasmall:
library(tidyverse)

databig %>%
  left_join(datasmall, by = c("yearbig" = "year")) %>%
  group_by(yearbig) %>%
  filter(bracket < earnings) %>%
  filter(max(bracket) == bracket)
#> # A tibble: 9 x 3
#> # Groups:   yearbig [4]
#>   yearbig earnings bracket
#>     <dbl>    <dbl>   <dbl>
#> 1    1949     47.7      40
#> 2    1949     43.8      40
#> 3    1949     46.6      40
#> 4    1950     55.4      50
#> 5    1950     59.1      50
#> 6    1950     55.1      50
#> 7    1951     50.0      50
#> 8    1952     51.6      50
#> 9    1952     52.8      50


text:
Q: Multiple iterations of requests saved for future processing My problem, I have a multistep process that requests data from API and then run another API over each response from first API. Problem is with correct saving and retrieving this information between APIs
My Flow:

*

*Request data from first API (100 rows 6 columns)

*Save to df

*Run each row of the df through second API

*Save to another df

*Data processing and cleaning

My issue is with step no.4
#Request data from second API
try:
        response_users = requests.post('https://deep-index.moralis.io/api/v2/0xFFE811714ab35360b67eE195acE7C10D93f89D8C/function', headers=headers, params=params, json=json_data)
            response_data = response_users.json()
            response_data["walletaddress"] = address
            response_data["block_number"] = updated_df.loc[updated_df['buddy'] == address, 'block_number'].iloc[0]
            response_data["updatedAt"] = updated_df.loc[updated_df['buddy'] == address, 'updatedAt'].iloc[0]
            dct = {k:[v] for k,v in response_data.items()}
            df2 = pd.DataFrame(dct)
            return(df2)

#get data for each row
with tqdm(total=len(updated_df)) as pbar:
              for i in range(len(updated_df)) :
                team_info(updated_df.loc[i, 'buddy_str'])
                time.sleep(0.1)
                pbar.update(1)

Right now I can only get first iteration and should be 100 as this the number of rows After First API and in first df.
First DF