text:
Q: Copying the styling results of one dataframe to another I have two dataframes of identical size, df_a and df_b. df_a only contains numbers and is styled using a colormap (either using xlsxwriter or pandas styling). df_b contains mixed values. Is it possible to copy the resulting style from one dataframe to the other such that the background color of df_b[i,j] equals the background color of df_a[i,j]?
In the example below the first element of df_b should be red, the second yellow, and so on.

Formatting code for df_a (based on the xlsxwriter example)
# Create a Pandas dataframe from some data.
df_a = pd.DataFrame({'col_a': [10, 20, 30, 20, 15, 30, 45]})
df_b = pd.DataFrame({'col_b': ['a', 'a', 'c', 'd', 'e', 'f', 'g']})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df_a.to_excel(writer, sheet_name='Sheet1')

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Apply a conditional format to the cell range.
worksheet.conditional_format('B2:C8', {'type': '3_color_scale'})

# Close the Pandas Excel writer and output the Excel file.
writer.save()

A: Let's use Pandas' style to format the data:
# This will color every column into 3-category color
def style(df):
    s = {}
    for c1, c2 in zip(df.columns, df_a.columns):
        s[c1] = pd.cut(df_a[c2], bins=3,
                          labels=[f'background-color:{c}' for c in ['red','blue','green']])
    return pd.DataFrame(s)

writer = pd.ExcelWriter(output_file)
df_a.style.apply(style, axis=None).to_excel(writer, sheet_name='df_a', index=False)
df_b.style.apply(style, axis=None).to_excel(writer, sheet_name='df_b', index=False)
writer.save()

A: This solution expands the accepted solution to more than one column and uses a color map instead of a predefined limited set of colors.
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib

np.random.seed(24)
df_a = pd.DataFrame(10*np.random.randn(10, 4), columns=list('ABCD'))
df_b= pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))

cm = sns.color_palette("Spectral", as_cmap=True)

def style(df):
    data = df_a.values
    data_normalized = (data - np.min(data)) / (np.max(data) - np.min(data))
    bg_colors = cm(data_normalized)
    bg_colors = np.apply_along_axis(matplotlib.colors.to_hex, 2, bg_colors)
    s = pd.DataFrame(bg_colors, columns=df.columns)
    for col in s.columns:
        s[col] = s[col].apply(lambda c: f'background-color:{c}')
    return s

writer = pd.ExcelWriter('temp.xlsx')
df_a.style.apply(style, axis=None).to_excel(writer, sheet_name='df_a', index=False)
df_b.style.apply(style, axis=None).to_excel(writer, sheet_name='df_b', index=False)
writer.save()

This results in the following:


text:
Q: Simulate keyboard press in javascript I would like to ask, if there is a possibility to simulate more keypresses at once using javascript.
My problem is, that I have a window which is blocked to be closed, but for administration purposes I need to close it sometimes using some kind of hack, unfortunately chrome disables javascript to close current tab if it wasn't created by javascript.
So one thing came to my mind and it is to simulate pressing CTRL+W in javascript which will close current tab and I will be able to leave chrome.
I am using --kiosk to keep user without any other options to close the window.
So my idea was to have an input which in case that I will put e.g. 123 inside it will simulate the action of keyboard.
Is this even possible, or do any of you guys have any better solution?
Thanks in advance!
Jakub

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to work with select input with data coming from a simple relational db model I'm using Angularjs plugged into a API which retrieves data from a mysqlk normal relational db.
Let's say I have this simple data model in my bdd:
table car:
  id,
  type_id

table type:
  id,
  label

I have a API which retrieves the data from DB to have the list of cars and the static labels from db:
http://myapi/car/
response :
   {[{id:1, type_id:2}, {id:2, type_id:3}]}

http://myapi/carstaticlabel/
response :
   {[{id:1, label:convertible}, {id:2, label:limousine}, {id:3, label:pickup}]}

My aim is first to display a list of cars with the type label and then, open a dialog and being able to show a form with preloaded values of the selected car:
rendered list of cars :
1 convertible
2 pickup

rendered form for edited car whose id is 1:
select the type of car:
<select>
  <option value="1">convertible</option>
  <option value="2" selected="selected">limousine</option>
  <option value="3">pickup</option>
</select>

I have tried different approaches but none is elegant
Solution 1
for the list of cars
change my API and make the join directly between car and type to get the list with label:
http://myapi/car/
response :
   {[{id:1, type_id:2, type:{[id:2, label:limousine]}}, {id:2, type_id:3, type:{[id:3, label:pickup]}}]}

then I just assign in the form : car.id and car['type']['label']
ISSUE: each car will contain repeated information (label) >> bloated info
for the edit form:
I pass the json of selected car to the form and set default values:

type: <select ng-model="car.type"  ng-options="type.label for type in type_list" required></select>

MY ISSUE with that:
when I submit the form, I don't get the type_id directly, I get the car.type object instead, so I need to painfully translate it into an id to post into the database.
To convert I have to go into the car.type object and retrieve the object inside and then retrieve its id... very unelegant.

Solution 2
make the "join" inside angular by working with arrays.
ISSUE: very hard to default values in the form later on

I'm lost, what is usually the best practice to achieve that simple task?

A: You should use select as label for value in array syntax for array data sources. Your example have complex data structure which is array of objects. So you need something like this:
<select ng-model="selectedId"
        ng-options="x.id as x.label for x in response">
</select>

I created little example here to demonstrate proposed solution.


text:
Q: Starting of windows service in child process with elevation of privileges with UAC OFF There is a C# program. It's started under non-admin user in Windows 7. UAC is ON.
This program runs child process:
  webClientProcess.StartInfo.CreateNoWindow = true;
  webClientProcess.StartInfo.FileName = @".\StartWebClient.exe";
  webClientProcess.StartInfo.UseShellExecute = true;
  webClientProcess.Start();

app.manifest of child process has following setting:
 <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

StartWebClient.exe just starts WebClient windows service and return.
If UAC is ON we have pop-up prompt for admin password and everything is OK.
If UAC is OFF (user is not admin!) we have no prompt, of course, and then when we start WebClient service:
var sc = new ServiceController("WebClient");
if (sc.Status != ServiceControllerStatus.Running)
{
    sc.Start();
}

we have an error: Cannot open WebClient service on computer '.'.
It's due to there was no admin password pop up window.
Question: Is there any way to start service in this case?
I couldn't find solution here or in MSDN. If this situation is "wrong use case" in Microsoft opinion, may be somebody know a link to appropriate MSDN article? I have no goal to start service with some hacks, if it is forbidden - OK, but I couldn't find confirmation in MSDN.


text:
Q: Is ftp connections and actions are logged in REDHAT 7? I am using a REDHAT 7 server through a VPN connection (with some other users). I want to know if FTP connections and operations are logged somewhere. I tried to look around /var/log but nothing seemed clear to me.

A: If there are ftp connections, you must have an ftp server (daemon, ftpd).  You should check its configuration: has logging been enabled, and whereto?


text:
Q: Python returning object "placement" instead of float I'm creating a web scraper that will be used to value stocks. The problem I got is that my code returns a object "placement" (Not sure what it should be called) instead of the value.
import requests

class Guru():

    MedianPE = 0.0

    def __init__(self, ticket):

        self.ticket = ticket

        try:

            url = ("https://www.gurufocus.com/term/pettm/"+ticket+"/PE-Ratio-TTM/")

            response = requests.get(url)
            htmlText = response.text
            firstSplit = htmlText
            secondSplit = firstSplit.split("And the median was ")[1]
            thirdSplit = secondSplit.split("")[0]

            lastSplit = float(thirdSplit)

            try:
                Guru.MedianPE = lastSplit
            except:
                print(ticket + ": Median PE N/A")
        except:
            print(ticket + ": Median PE N/A")

    def getMedianPE(self):
        return float(Guru.getMedianPE)

g1 = Guru("AAPL")
g1.getMedianPE
print("Median + " + str(g1))

If I print the lastSplit inside the __init__ it returns the value I want 15.53 but  when I try to get it by  the function getMedianPE I just get Median + <__main__.Guru object at 0x0000016B0760D288>
Thanks a lot for your time!

A: Looks like you are trying to cast a function object to a float.  Simply change return float(Guru.getMedianPE) to return float(Guru.MedianPE)

A: getMedianPE is a function (also called object method when part of a class), so you need to call it with parentheses. If you call it without parentheses, you get the method/function itself rather than the result of calling the method/function.
The other problem is that getMedianPE returns the function Guru.getMedianPE rather than the value Guru.MedianPE. I don't think you want MedianPE to be a class variable - you probably just want to set it as a default of 0 in init so that each object has its own median_PE value.
Also, it is not a good idea to include all of the scraping code in your init method. That should be moved to a scrape() method (or some other name) that you call after instantiating the object.
Finally, if you are going to print an object, it is useful to have a str method, so I added a basic one here.
So putting all of those comments together, here is a recommended refactor of your code.
import requests

class Guru():
    def __init__(self, ticket, median_PE=0):
        self.ticket = ticket
        self.median_PE = median_PE

    def __str__(self):
        return f'{self.ticket} {self.median_PE}'

    def scrape(self):
        try:
            url = f"https://www.gurufocus.com/term/pettm/{self.ticket}/PE-Ratio-TTM/"
            response = requests.get(url)
            htmlText = response.text
            firstSplit = htmlText
            secondSplit = firstSplit.split("And the median was ")[1]
            thirdSplit = secondSplit.split("")[0]
            lastSplit = float(thirdSplit)
            self.median_PE = lastSplit
        except ValueError:
            print(f"{self.ticket}: Median PE N/A")

Then you run the code
>>>g1 = Guru("AAPL")
...g1.scrape()
...print(g1)
AAPL 15.53


text:
Q: How to add strings from file to Observable list for combobox JavaFX I have a controller class that loads in a text file and gets the contents of that file. I want to get a string token from each line in the text file then add it to an Observablelist so I can use it in a combobox later on. I keep getting a "Exception in thread "JavaFX Application Thread" java.lang.RuntimeException" error when trying to put the string into the list.
Simplified code:
public class FXMLDocumentController implements Initializable {

@FXML
private ComboBox<String> combobox;

private ObservableList<String> list;

public void LoadIceCream() throws IOException
{
    File iceCreamFile;
    iceCreamFile = new File("IceCream.txt");
    String line;
    String tokens[];
    int iTemp;
    String strTemp;
    double dTemp;
    int i2Temp;
    String str2Temp;
    IceCream icTemp;
    int i =0;
    try {
        Scanner inputIceCream=new Scanner(iceCreamFile);
        while (inputIceCream.hasNextLine())
        {
            line=inputIceCream.nextLine();
            tokens=line.split(",");
            iTemp=Integer.parseInt(tokens[0]);
            strTemp=tokens[1]; //String for the list, other tokens are used for other things just ignore
            dTemp=Double.parseDouble(tokens[2]);
            str2Temp=tokens[3];
            i2Temp=Integer.parseInt(tokens[4]);

            icTemp=new IceCream(iTemp,strTemp,dTemp,str2Temp, i2Temp);
            iceCreamList.add(icTemp);
            list.add(strTemp); //ObservableList that is needed for Combo

        }

    } catch (FileNotFoundException ex) {
        Logger.getLogger(MenuManagement.class.getName()).log(Level.SEVERE, null, ex);
    }

}
@Override
public void initialize(URL location, ResourceBundle resources) {

}

Error
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.control.MenuItem.fire(MenuItem.java:462)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.doSelect(ContextMenuContent.java:1405)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.lambda$createChildren$343(ContextMenuContent.java:1358)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:352)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:275)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$355(GlassViewEventHandler.java:388)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:387)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$149(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771)
... 43 more
Caused by: java.lang.NullPointerException
at javafxapplication1.FXMLDocumentController.LoadIceCream(FXMLDocumentController.java:226)
... 53 more


text:
Q: Making all functions false I am trying to add a menu to my game. But for that i need to make the code below false. do i need to make every function false or can i use an extra main function to do this? If there is an alternative i would be happy to hear it. Thanks if u leave a comment. :)
package
{
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.filters.GlowFilter;
    import flash.utils.getTimer;
    import flash.events.TimerEvent;
    public class Docter extends MovieClip
    {
        private var nieuwX:Number = 0;
        private var nieuwY:Number = 0;

        private var snelheid:Number;

        private var snelheidX:Number;
        private var snelheidY:Number;

        private var totaleAfstand:Number;
        private var vorigeAfstand:Number;
        private var momenteleAfstand:Number;

        public var heeftSieraad:Boolean = false;

        private var deltaTime = 0;
        private var currentTime = 0;

        public var startGame:Boolean;

        public function startGame{

            public function Docter()
            {

                this.addEventListener(Event.ADDED_TO_STAGE, Setup);
                this.addEventListener(MouseEvent.CLICK, docEenClick);
            }
            public function AddSieraad():void
            {
                AddGlow();
                heeftSieraad = true;
            }
            private function AddGlow():void
            {
                var glow:GlowFilter = new GlowFilter(0xFFFF00,1);
                this.filters = [glow];
            }
            public function RemoveSieraad():void
            {
                heeftSieraad = false;
                this.filters = [];
            }
            private function docEenClick(evt:MouseEvent)
            {

                dispatchEvent(new Event(Main.ADD_SCORE_EVENT));

            }

            private function positie(){

                this.nieuwX = this.randomXPositie();
                this.nieuwY = this.randomYPositie();

                this.totaleAfstand = this.krijgAfstand();

                var tijd:Number = this.totaleAfstand / this.snelheid;

                snelheidX = (nieuwX - this.x)/tijd;
                snelheidY = (nieuwY - this.y)/tijd;
            }

            private function Setup(evt:Event){
                this.x = this.randomXPositie();
                this.y = this.randomYPositie();

                snelheid = 70;

                this.addEventListener(Event.ENTER_FRAME, verplaatsDocEen);
            }

            private function randomXPositie():Number{

                return Math.floor(Math.random() * (1+ (stage.stageWidth + this.width) + this.width) - this.width);
            }

            private function randomYPositie():Number{

                return Math.floor(Math.random() * (1+ (stage.stageHeight + this.height) + this.height) - this.height);
            }

            private function krijgAfstand():Number{

                return Math.sqrt(Math.pow(this.x - this.nieuwX,2) + Math.pow(this.y - this.nieuwY,2));
            }

            private function verplaatsDocEen(evt:Event)
            {
                deltaTime = getTimer()/1000 - currentTime;
                currentTime = getTimer()/1000;

                this.vorigeAfstand = this.momenteleAfstand;
                this.momenteleAfstand =this.krijgAfstand();

                if (this.momenteleAfstand < this.vorigeAfstand)
                {

                    this.x += this.snelheidX * deltaTime;
                    this.y += this.snelheidY * deltaTime;
                }

                else
                {
                    this.positie();
                }
            }
            public function dispose()
            {
                this.removeEventListener(Event.ENTER_FRAME, verplaatsDocEen);
                this.removeEventListener(Event.ADDED_TO_STAGE, Setup);
                this.removeEventListener(MouseEvent.CLICK, docEenClick);
            }
        }

    }

}


text:
Q: How to get python to tolerate UTF-8 encoding errors I have a set of UTF-8 texts I have scraped from web pages. I am trying to extract keywords from these files like so:
import os
import json
from rake_nltk import Rake
rake_nltk_var = Rake()
directory = 'files'
results = {}
for filename in os.scandir(directory):
    if filename.is_file():
        with open("files/" + filename.name, encoding="utf-8", mode = 'r') as infile:
            text = infile.read()
        rake_nltk_var.extract_keywords_from_text(text)
        keyword_extracted = rake_nltk_var.get_ranked_phrases()
        results[filename.name] = keyword_extracted
with open("extracted-keywords.json", "w") as outfile:
    json.dump(results, outfile)

One of the files I've managed to process so far is throwing the following error on read:
Traceback (most recent call last):
  File "extract-keywords.py", line 11, in <module>
    text = infile.read()
  File "c:\python36\lib\codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 66: invalid start byte

0x92 is a right single quotation mark, but the 66th char of the file is a "u" so IDK where this error is coming from. Regardless, is there some way to make the codec tolerate such encoding errors? For example, Perl simply substitutes a question mark for any character it can't decode. Is there some way to get Python to do the same? I have a lot of files and can't afford to stop and debug every encoding error they might contain.

A:
I have a set of UTF-8 texts I have scraped from web pages

If they can't be read with the script you've shown, then these are not actually UTF-8 encoded files.
We have to know about the code which wrote the files in the first place to tell the correct way to decode.  However, the ' character is 0x92 byte in code page 1252, so try using that encoding instead, i.e.:
with open("files/" + filename.name, encoding="cp1252") as infile:
    text = infile.read()

Ignoring decoding errors corrupts the data, so it's best to use the correct decoder when possible, so try and do that first! However, about this part of the question:

Regardless, is there some way to make the codec tolerate such encoding errors? For example, Perl simply substitutes a question mark for any character it can't decode. Is there some way to get Python to do the same?

Yes, you can specify errors="replace"
>>> with open("/tmp/f.txt", "w", encoding="cp1252") as f:
...     f.write('this is a right quote: \N{RIGHT SINGLE QUOTATION MARK}')
...

>>> with open("/tmp/f.txt", encoding="cp1252") as f:
...     print(f.read())  # using correct encoding
...
this is a right quote: '

>>> with open("/tmp/f.txt", encoding="utf-8", errors="replace") as f:
...     print(f.read())  # using incorrect encoding and replacing errors
this is a right quote: �


text:
Q: Is there a way to automatically control orphaned words in an HTML document? I was wondering if there's a way to automatically control orphaned words in an HTML file, possibly by using CSS and/or Javascript (or something else, if anyone has an alternative suggestion).
By 'orphaned words', I mean singular words that appear on a new line at the end of a paragraph.  For example:
"This paragraph ends with an undesirable orphaned
word."
Instead, it would be preferable to have the paragraph break as follows:
"This paragraph no longer ends with an undesirable
orphaned word."
While I know that I could manually correct this by placing an HTML non-breaking space ( ) between the final two words, I'm wondering if there's a way to automate the process, since manual adjustments like this can quickly become tedious for large blocks of text across multiple files.
Incidentally, the CSS2.1 properties orphans (and widows) only apply to entire lines of text, and even then only for the printing of HTML pages (not to mention the fact that these properties are largely unsupported by most major browsers).
Many professional page layout applications, such as Adobe InDesign, can automate the removal of orphans by automatically adding non-breaking spaces where orphans occur;  is there any sort of equivalent solution for HTML?

A: I know you wanted a javascript solution, but in case someone found this page a solution but for emails (where Javascript isn't an option), I decided to post my solution.
Use CSS white-space: nowrap. So what I do is surround the last two or three words (or wherever I want the "break" to be) in a span, add an inline CSS (remember, I deal with email, make a class as needed):

    I don't want orphaned words.

In a fluid/responsive layout, if you do it right, the last few words will break to a second line until there is room for those words to appear on one line.
Read more about about the white-space property on this link: http://www.w3schools.com/cssref/pr_text_white-space.asp
EDIT: 12/19/2015 - Since this isn't supported in Outlook, I've been adding a non-breaking space   between the last two words in a sentence. It's less code, and supported everywhere.
EDIT: 2/20/2018 - I've discovered that the Outlook App (iOS and Android) doesn't support the   entity, so I've had to combine both solutions: e.g.:

    I don't want orphaned words.

A: In short, no. This is something that has driven print designers crazy for years, but HTML does not provide this level of control.
If you absolutely positively want this, and understand the speed implications, you can try the suggestion here:
detecting line-breaks with jQuery?
That is the best solution I can imagine, but that does not make it a good solution.

A: You can avoid orphaned words by replacing the space between the last two words in a sentence with a non-breaking space ( ).
There are plugins out there that does this, for example jqWidon't or this jquery snippet.
There are also plugins for popular frameworks (such as typogrify for django and widon't for wordpress) that essentially does the same thing.

A: I see there are 3rd party plugins suggested, but it's simpler to do it yourself. if all you want to do is replace the last space character with a non-breaking space, it's almost trivial:
    const unorphanize = (str) => {
        let iLast = str.lastIndexOf(' ');
        let stArr = str.split('');
        stArr[iLast] = ' ';
        return stArr.join('')
}

I suppose this may miss some unique cases but it's worked for all my use cases. the caveat is that you can't just plug the output in where text would go, you have to set innerHTML = unorphanize(text) or otherwise parse it

A: If you want to handle it yourself, without jQuery, you can write a javascript snippet to replace the text, if you're willing to make a couple assumptions:

*

*A sentence always ends with a period.

*You always want to replace the whitespace before the last word with

Assuming you have this html (which is styled to break right before "end" in my browser...monkey with the width if needed):

    This is some text with one word on its own line at the end.

    This is some text with one word on its own line at the end.

You can create this javascript and put it at the end of your page:

The regex simply finds all instances (using the g flag) of a whitespace character (\S) followed by any number of non-whitespace characters (\s) followed by a period.  It creates a back-reference to the non-white-space that you can use in the replace text.
You can use a similar regex to include other end punctuation marks.

A: If third-party JavaScript is an option, one can use typogr.js, a JavaScript "typogrify" implementation. This particular filter is called, unsurprisingly, Widont.


text:
Q: For loop syntax and running a script twice Okay, I think this might have a simple answer / solution but I'm drawing a blank. Maybe I don't understand something fundamental that I should. If I have a script in R that does literally anything, and want to have it run twice, couldn't I just slap a for loop around it like this:
for(i in 1:2){
    R script goes here
}

I know that usually the for loops I write have the i variable changing with every iteration (and that i variable is inside the loop too). So if this isn't working, could part of the problem be that I don't have anything inside the loop that is using i?
EDIT: I don't think my question was clearly written. Let me say it this way as well. If I had a for loop that simply counted 1 to 100, I could write it like this.
for (i in 1:100){
    print(i)
}

However, I could also make the loop like this:
for (i in 1:100){
    print(2)
}

Which would, instead of counting, print the number 2, 100 times.
Now I have a much more complicated script that executes a batch file, then connects to SQL server to drop data into several databases. I don't see why it would make a difference to simply replace print(2) with my script.
The script works perfectly without the for loop, but once that is included it breaks. Perhaps this is more complex than simply how the loop is implemented and I should post a different question going into further detail.


text:
Q: Generating a Nakagami Random Variable Assuming the only tool for generating random numbers I have available is generating a uniformly distributed variable u on U(0,1). I want to generate a Nakagami Random Variable from it.
I know I could just plug u into the inverse CDF of the Nakagami distribution, but unfortunately, the inverse CDF isn't trivial to compute.

A: Which difficulties do you have computing the CDF?  Special functions gamma and \Gamma are availble in scientific computing libraries.
If the CDF-based method will not do, you can generate Nagakami distributed numbers based on Gamma distributed numbers or Chi distributed numbers.  The methods are described in Wikipedia:
http://en.wikipedia.org/wiki/Nakagami_distribution


text:
Q: PyODBC SQL type error when reading query in Pandas Looking for some help with a specific error when I write out from a pyodbc connection. How do I fix the error:

ODBC SQL type -360 is not yet supported. column-index=1 type=-360', 'HY106' error from PYODBC

Here is my code:
import pyodbc
import pandas as pd
import sqlparse

## Function created to read SQL Query
def create_query_string(sql_full_path):
    with open(sql_full_path, 'r') as f_in:
        lines = f_in.read()

    # remove any common leading whitespace from every line
    query_string = textwrap.dedent("""{}""".format(lines))
    ## remove comments from SQL Code
    query_string = sqlparse.format(query_string, strip_comments=True)

    return query_string

query_string = create_query_string("Bad Code from R.sql")

## initializes the connection string
curs = conn.cursor()

df=pd.read_sql(query_string,conn)

df.to_csv("TestSql.csv",index=None)

We are using the following SQL code in query string:
SELECT loss_yr_qtr_cd,
       CASE
         WHEN loss_qtr_cd <= 2 THEN loss_yr_num
         ELSE loss_yr_num + 1
       END                    AS LOSS_YR_ENDING,
       snap_yr_qtr_cd,
       CASE
         WHEN snap_qtr_cd <= 2 THEN snap_yr_num
         ELSE snap_yr_num + 1
       END                    AS CAL_YR_ENDING,
       cur_ctstrph_loss_ind,
       clm_symb_grp_cd,
       adbfdb_pol_form_nm,
       risk_st_nm,
       wrt_co_nm,
       wrt_co_part_cd,
       src_of_bus_cd,
       rt_zip_dlv_ofc_cd,
       cur_rst_rt_terr_cd,
       Sum(xtra_cntrc_py_amt) AS XTRA_CNTRC_PY_AMT
FROM   (SELECT DT.loss_yr_qtr_cd,
               DT.loss_qtr_cd,
               DT.loss_yr_num,
               SNAP.snap_yr_qtr_cd,
               SNAP.snap_qtr_cd,
               SNAP.snap_yr_num,
               CLM.cur_ctstrph_loss_ind,
               CLM.clm_symb_grp_cd,
               POL_SLCT.adbfdb_pol_form_nm,
               POL_SLCT.adbfdb_pol_form_cd,
               CVR.bsic_cvr_ind,
               POL_SLCT.priv_pass_ind,
               POL_SLCT.risk_st_nm,
               POL_SLCT.wrt_co_nm,
               POL_SLCT.wrt_co_part_cd,
               POL_SLCT.src_of_bus_cd,
               TERR.rt_zip_dlv_ofc_cd,
               TERR.cur_rst_rt_terr_cd,
               LOSS.xtra_cntrc_py_amt
        FROM   ahshdm1d.vmaloss_day_dt_dim DT,
               ahshdm1d.vmasnap_yr_mo_dim SNAP,
               ahshdm1d.tmaaclm_dim CLM,
               ahshdm1d.tmaapol_slct_dim POL_SLCT,
               ahshdm1d.tmaacvr_dim CVR,
               ahshdm1d.tmaart_terr_dim TERR,
               ahshdm1d.tmaaloss_fct LOSS,
               ahshdm1d.tmaaprod_bus_dim BUS
        WHERE  SNAP.snap_yr_qtr_cd BETWEEN '20083' AND '20182'
               AND TRIM(POL_SLCT.adbfdb_lob_cd) = 'A'
               AND CVR.bsic_cvr_ind = 'Y'
               AND POL_SLCT.priv_pass_ind = 'Y'
               AND POL_SLCT.adbfdb_pol_form_cd = 'V'
               AND POL_SLCT.src_of_bus_cd NOT IN ( 'ITC', 'INV' )
               AND LOSS.xtra_cntrc_py_amt > 0
               AND LOSS.loss_day_dt_id = DT.loss_day_dt_dim_id
               AND LOSS.cvr_dim_id = CVR.cvr_dim_id
               AND LOSS.pol_slct_dim_id = POL_SLCT.pol_slct_dim_id
               AND LOSS.rt_terr_dim_id = TERR.rt_terr_dim_id
               AND LOSS.prod_bus_dim_id = BUS.prod_bus_dim_id
               AND LOSS.clm_dim_id = CLM.clm_dim_id
               AND LOSS.snap_yr_mo_dt_id = SNAP.snap_yr_mo_dt_id) AS TABLE1
GROUP  BY loss_yr_qtr_cd,
          loss_qtr_cd,
          loss_yr_num,
          snap_yr_qtr_cd,
          snap_qtr_cd,
          snap_yr_num,
          cur_ctstrph_loss_ind,
          clm_symb_grp_cd,
          adbfdb_pol_form_nm,
          risk_st_nm,
          wrt_co_nm,
          wrt_co_part_cd,
          src_of_bus_cd,
          rt_zip_dlv_ofc_cd,
          cur_rst_rt_terr_cd
FOR FETCH only

Just looking how to properly write out the database.
Thanks,
Justin


text:
Q: Use sed without the need to write on file I'm looking for a way to bypass the read write on file.
Is it possible to directly use sed on results of a command?
#!/bin/sh is used, as I used NetBSD, sed -i is not working so I have to use sed -e then redirect results to a file.
results of command disklabel xbd0
netbsd# disklabel xbd0 >/file ;
# /dev/rxbd0d:
type: unknown
disk: xbd0
label:
flags:
bytes/sector: 512
sectors/track: 2048
tracks/cylinder: 1
sectors/cylinder: 2048
cylinders: 1000
total sectors: 2048000
rpm: 3600
interleave: 1
trackskew: 0
cylinderskew: 0
headswitch: 0           # microseconds
track-to-track seek: 0  # microseconds
drivedata: 0

16 partitions:
#        size    offset     fstype [fsize bsize cpg/sgs]
 a:   2048000         0     4.2BSD   1024  8192     0  # (Cyl.      0 -    999)
 c:   2048000         0     unused      0     0        # (Cyl.      0 -    999)
 d:   2048000         0     unused      0     0        # (Cyl.      0 -    999)

netbsd# disklabel xbd0 | sed -e "s/match1/replace/" \
-e "s/match2/replace/" \
-e "s/match3/replace/" /file > /file.1 ;

how to send the results inside another command?
$ new_command -add $(results)

A: You're already successfully piping the result of disklabel to sed.  So why don't you just pipe the results of sed to whatever new_command is?
disklabel xbd0 | sed -e "s/match/replace/" | new_command

For example, pipe the output of sed to sort and then pipe the output of that to grep.

A:
How to send the results inside another command? As $ new_command -add $(results)

If this is really what you mean, you can achieve this with the xarg command:
disklabel xbd0 | sed -e "s/match/replace/" | xargs new_command -add

Note that xargs will break your input at spaces, if you want juste one big argument, you can use xargs -0.
Most probably it is best to design new_command so that it takes its input from stdin and pass this input through a supplementary pipe.

A: In your code, you're trying to redirect output of the commands to /file, you'll get "permission denied" , unless you're doing it as superuser.
For sending results of one command to another command, do this:
command2 `command1` #if command2 needs output of command1 as an argument

or
command2 $(command1)  #if command2 needs output of command1 as an argument


text:
Q: 2015 Macbook Won't Turn On - Shows no sign of life I recently bought a 2015 Macbook from a friend, and after only a day of use, it won't turn on...
I shut down the Macbook with around 15% charge left on it, so initially I thought this to be a lack-of-charge issue, however I've had it plugged in for over 8 hours and still it doesn't turn on.
I've tried the Shift+Control+Power 10 second restart, along with the CMD+R+Power reset, but no signs of life.
The trackpad clicker doesn't click, and the caps lock button doesn't light up. The problem with this 'modern mac' is that it has no moving parts, so you can't hear it turn on!
Is there anything I can try before I take it into the Apple store?
Thanks


text:
Q: R.Neighbors with large neighborhoods I'm working on the same theme as User 32882, and I'm new here.
I have the same problem, and update his question with more details.
Old question: "I'm running into problems running the r.neighbors GRASS command in QGIS. Although it will run for small neighborhoods as soon as I increase my neighborhood above a certain number it becomes unbearably slow. I don't understand why Focal Statistics on ArcMap will do this in the blink of an eye while R.Neighbors takes ages?"
Link of Old question:
R.Neighbors with large neighborhoods?
Details:
We are exploring a circular neighborhood of ~200 pixels.
And trying to compute Maximum or Minimum statistics.
Moreover, Maximum computation seems OK, but Minimum often presents 0 results.
Why is so slow in QGIS?
What can I do to make it run faster?

A: WHen you mention 200 pixels, do you mean a neighborhood of 200 pixels width? or a neighborhood that contains 200 pixels? The GRASS r.neighborhood command takes a "size" parameters which is the width of the window. So for the second case, a circular window containing 200 pixels then the width will be about:
2 x sqrt(area/pi) or ~17.

I tried some tests as follows:
In GRASS 7.0 I created a 20 million cell raster of random values. Then I tried r.neighbors with two size parameters: 201 and 17. And for both sizes I used both the minimum and maximum methods to calculate the new rasters.
Using the very large 200 pixel neighborhood, both processes took nearly the same time, 31 minutes. This neighborhood contains about:
pi x (100^2) or 31,417 cells

Using the size parameter 17 (a neighborhood containing about 200 pixels) then each process finished in about 15 seconds. And I got values for both min and max r.neighborhood output rasters.
So I can not verify your claim that method=minimum gives zero result (maybe within your 200 pixel windows there is always at least one cell with value 0??)
Also, as to runtime, I don't know if 30 minutes is "takes ages".
Regarding ArcGIS, note that the width parameter for FocalStatistics is radius, not the same as size in GRASS. And you can specify in Arc that the radius is map units. Can you verify what parameters you are using in Arc?
I'm sure someone can offer a better explanation if you can :

*

*explain what size of neighborhood you mean

*what are your GRASS region settings?

*What are the data in the original raster like?

*and what exactly are the functions you are running in GRASS vs ArcGIS?


text:
Q: IOS image sizes for asset catalogs I am really confused about the required image sizes to be used with interface builder. I am using an asset catalog and there are spaces for 1x, 2x and 3x images.
For a full screen texture for the iPhone 6 plus. I am setting the size to 1242 x 2208 and naming it myimage@3x.jpg and placing in the 3x slot in the asset catalog.
The same image for the iPhone 6 I am setting to 1334 x 750, naming it myimage@2x.jpg and placing it in the 2x slot in the asset catalog.
I then set my UIImage in interface builder to be myimage. I understand xcode will now automatically display the 3@x image on the iPhone 6 plus and the @2x on the iPhone 6. I assume the 1x slot is for non retina phones (3gs, 4, etc)
My question is how do I get a 1136 x 640 image to be displayed on the iPhone 5s. Will the 5s continue to use the 1334 x 720 image thats for the iPhone 6 or can I somehow create a 1136 x 640 the will be automatically selected by xcode when the app is running on an iPhone 5s.


text:
Q: Convert string[] to int I have an array of integers in string form.
string [] TriangleSideLengths

In this array there is going to be 3 int values which represent side length of a triangle. Is there a way from which I can extract individual all 3 values from my array TriangleSideLengths into three int objects like int intSideLengthOne,intSideLengthTwo and intSideLengthThree.
I want to be able to test if these three values actually form a valid triangle?
For instance, entering lengths 10, 10, 100000 wouldn't make it a valid isosceles triangle.
I wanna be able to do this check with the three values stored in my array TriangleSideLengths.
a + b > c
a + c > b
b + c > a

Any help is greatly appreciated.
Thanks a lot!! :)

A: You can use LINQ to parse the numbers from the string, like this:
var threeSides = TriangleSideLengths.Select(int.Parse).ToArray();

Here is a demo on ideone.
To do the check, sort the numbers in ascending order, then check that the sum of the first two is strictly greater than the third one:
Array.Sort(threeSides);
if (threeSides[0]+threeSides[1] > threeSides[2]) {
    ...
}

Note that it is not a sufficient condition for the numbers to define a triangle: you must also check that the numbers are strictly positive.

A: Try this
string [] TriangleSideLengths = new string[3];
int[] lengths = new int[3];
for(int i = 0; i<=2;i++)
{
 lengths[i]=Convert.ToInt32(TriangleSideLengths[i]);
}
if(lengths[0]+lengths[1]>lengths[2])
   //go crazy

A: string[] TriangleSideLengths = { "10", "20", "300"};

int[] sides = new int[TriangleSideLengths.Length];

for (int i = 0; i < TriangleSideLengths.Length; i++)
{
    sides[i] = int.Parse(TriangleSideLengths[i]);
}

A: int[] sides = new int[TriangleSideLengths.Length];
int counter=0;
foreach(var str in TriangleSideLengths)
{
   int.TryParse(str, out sides[counter++]);
}
if(sides[0] + sides[1] > sides[2]){...}

A: public int toInt(string text)
{
    int tonumber = int.Parse(text);
    return tonumber;
}


text:
Q: How to find the Null Space of a matrix in Python using numpy? As the title says, how can I find the null space of a matrix
i.e. the nontrivial solution to the equation ax=0.
I've tried to use np.linalg.solve(a,b), which solves the equation ax=b. So setting b equal to an array of zeros with the same dimensions as matrix a, I only get the trivial solution i.e. x=0.

A: From SciPy Cookbook:
import numpy as np
from numpy.linalg import svd

def nullspace(A, atol=1e-13, rtol=0):
    A = np.atleast_2d(A)
    u, s, vh = svd(A)
    tol = max(atol, rtol * s[0])
    nnz = (s >= tol).sum()
    ns = vh[nnz:].conj().T
    return ns

Computes an approximate basis for the nullspace of A.
The algorithm used by this function is based on the singular value decomposition of A.
Parameters:
A : ndarray
A should be at most 2-D.  A 1-D array with length k will be treated as a 2-D with shape (1, k)
atol : float
The absolute tolerance for a zero singular value.  Singular values smaller than atol are considered to be zero.
rtol : float
The relative tolerance.  Singular values less than rtol*smax are considered to be zero, where smax is the largest singular value.
If both atol and rtol are positive, the combined tolerance is the maximum of the two; that is:
tol = max(atol, rtol * smax)

Singular values smaller than tol are considered to be zero.
Return value:
ns : ndarray
If A is an array with shape (m, k), then ns will be an array with shape (k, n), where n is the estimated dimension of the nullspace of A.  The columns of ns are a basis for the nullspace; each element in numpy.dot(A, ns) will be approximately zero.

A: you can diagonalize your matrix:
eigen_vects, eigen_vals = np.linalg.eig(a)

you then just have to pick the eigen vectors that correspond to 0 eigenvalues (possibly accounting for numerical precision).
Example:
np.linalg.eig(np.ones((3,3)))

(array([ -2.22044605e-16,   3.00000000e+00,   0.00000000e+00]),
 array([[-0.81649658,  0.57735027,  0.        ],
        [ 0.40824829,  0.57735027, -0.70710678],
        [ 0.40824829,  0.57735027,  0.70710678]]))

Here the 1st and 3rd vectors are your non trivial solutions.


text:
Q: Solve sum for theta Is there any way to solve the following sum of trigonometric functions for theta without using a solver?
$$25\sin(\theta)-1.5\cos(\theta)=20$$

A: $$
25\sin\theta-1.5\cos\theta = \sqrt{25^2+1.5^2}\left( \frac{25}{\sqrt{25^2+1.5^2}}\sin\theta - \frac{1.5}{\sqrt{25^2+1.5^2}}\cos\theta  \right)
$$
$$
= \sqrt{25^2+1.5^2}(\cos\varphi\sin\theta-\sin\varphi\cos\theta) = \sqrt{25^2+1.5^2} \sin(\varphi-\theta).
$$
So you want
$$
\sin(\varphi-\theta)=\frac{20}{\sqrt{25^2+1.5^2}}.
$$
Take arcsines.

A: If you're okay with a numeric solution, define a function
$$
f\left(\theta\right) = 25 \sin \theta - 1.5 \cos \theta - 20 = 0
$$
and use a root finding algorithm.

A: The solution to $A\sin(t) + B\cos(t) = C$ is $t = 2\left(\pi n + \arctan{(\frac{A \pm \sqrt{A^2+B^2-C^2}}{B+C})}\right)$


text:
Q: Is there a way to tell Autofixture to only set properties with a specific attribute? I use Unity for dependency injection, and in a few places I use property injection (with the [Dependency] attribute) rather than constructor injection.
I'd like to use AutoFixture as a mocking container for my unit tests, but by default it sets all public properties on the system under test. I know I can explicitly exclude specific properties, but is there a way to include only properties that have the [Dependency] attribute?

A: This works:
public class PropertyBuilder : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
        var pi = request as PropertyInfo;
        if (pi != null)
        {
            if (pi.IsDefined(typeof (DependencyAttribute)))
                return context.Resolve(pi.PropertyType);

            //"hey, don't set this property"
            return new OmitSpecimen();
        }

        //"i don't know how to handle this request - go ask some other ISpecimenBuilder"
        return new NoSpecimen(request);
    }
}

fixture.Customizations.Add(new PropertyBuilder());

Test case:
public class DependencyAttribute : Attribute
{
}

public class TestClass
{
    [Dependency]
    public string With { get; set; }

    public string Without { get; set; }
}

[Fact]
public void OnlyPropertiesWithDependencyAttributeAreResolved()
{
    // Fixture setup
    var fixture = new Fixture
    {
        Customizations = {new PropertyBuilder()}
    };
    // Exercise system
    var sut = fixture.Create<TestClass>();
    // Verify outcome
    Assert.NotNull(sut.With);
    Assert.Null(sut.Without);
}


text:
Q: How can I store input values even after reloading the page? So I'm on a JavaScript LAB mission where we should take user input and use it as dimensions for a canvas.
My problem is that we are given HTML to stick with (can't be modified) which contains a submit button that reloads the page after the user submits its dimensions.
My question is how can I store the input value even after reloading the page?
HTML code:

<!DOCTYPE html>

  <title>Pixel Art Maker!</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Monoton">
  <link rel="stylesheet" href="styles.css">

Lab: Pixel Art Maker

Choose Grid Size

  <form id="sizePicker">
    Grid Height:
    <input type="number" id="inputHeight" name="height" min="1" value="1"> Grid Width:
    <input type="number" id="inputWidth" name="width" min="1" value="1">
    <input type="submit">
  </form>

Pick A Color

  <input type="color" id="colorPicker">

Design Canvas

A: You can use various local storage mechanisms to store this data in the browser such as Web Storage, IndexedDB, WebSQL (deprecated) and File API (deprecated and only available in Chrome) (and UserData with IE).
The simplest and most widely supported is WebStorage where you have persistent storage (localStorage) or session based (sessionStorage) which is in memory until you close the browser. Both share the same API.
You can for example (simplified) do something like this when the page is about to reload:
window.onbeforeunload = function() {
    localStorage.setItem("height", $('#inputHeight').val());
    localStorage.setItem("width", $('#inputWidth').val());
    // ...
}

Web Storage works synchronously so this may work here. Optionally you can store the data for each blur event on the elements where the data is entered.
At page load you can check:
window.onload = function() {

    var height= localStorage.getItem("height");
    if (height!== null) $('#inputHeight').val("height");

    // ...
}

getItem returns null if the data does not exist.

A: Use Local Storage to store the values. Local Storage has methods to retrieve and store data. Typically you'll use localStorage.getItem() on reload and localStorage.setItem() when saving datas.

A:

document.getElementById("inputWidth").value = savedValue("inputHeight");
document.getElementById("inputWidth").value = savedValue("inputWidth");

function getValue(t){
    var id = t.id;
    var inputValue = t.value;
    localStorage.setItem(id, inputValue);
}

function savedValue(t){
    if (!localStorage.getItem(t)) {
        return "";
    }

    return localStorage.getItem(t);
}
<input type="number" id="inputHeight" name="height" min="1" value="1" onkeyup="getValue(this)"> Grid Width:
<input type="number" id="inputWidth" name="width" min="1" value="1" onkeyup="getValue(this)">


text:
Q: How to convert tabular to longtable? Typical suggestions don't work I've seen similar questions, and answers typically say I only need to do three things: (i) remove begin and end table, (ii) replace begin and end tabular with begin and end longtable, (iii) load the longtable package.
When I apply these 3 steps to the code below, it still does not work? Is there any other adjustment I need to make?
%%% 01. LOADING PACKAGES
\documentclass[a4paper, 8pt]{article}
\usepackage{geometry}
\usepackage{array}
\usepackage{fancyhdr}
\usepackage{amsmath, amsthm, amssymb}
\usepackage{graphicx}
\usepackage{hyperref}
\usepackage{indentfirst}
\usepackage{pdflscape}
\usepackage{rotating}
\usepackage[utf8]{inputenc}
\usepackage{enumitem}
%\usepackage{euler}
\usepackage{bm}
\usepackage{econometrics}
\usepackage{booktabs}
\usepackage{amsfonts, empheq, mathrsfs}
\usepackage[dvipsnames]{xcolor}
\usepackage{extsizes}

%%% 02. CUSTOMISING FORMAT
\renewcommand{\baselinestretch}{1.3}
\setlength{\parskip}{1em}
\setlength{\skip\footins}{2cm}
\setlength{\footnotesep}{0.5cm}

%%% 03. POPULATING TEXT FIELDS
\title{S140 Behavioural Economics}
\author{}
\date{}

%%% 04. PRODUCING PERSONALIZED COMMANDS
\newcommand{\xb}[1]{\pmb{#1}}
\newcommand{\xbh}[1]{\pmb{\hat{#1}}}
\newcommand{\xbi}[1]{\pmb{{#1}^{-1}}}
\newcommand{\xbt}[1]{\pmb{{#1}^{'}}}
\newcommand{\tabitem}{~~\llap{\textbullet}~~}
\newcommand{\fconcepts}[1]{\textcolor{blue}{#1}}
\newcommand{\fquestions}[1]{\textcolor{red}{#1}}

%%% 05. TYPESETTING DOCUMENT
\begin{document}

        \newgeometry{top=0.5cm, bottom=0.5cm, left=0.5cm, right=0.5cm, asymmetric}
        \begin{landscape}

        \begin{table}[h!]
            \section{Overview of papers}

            \resizebox{\columnwidth}{!}{
                \begin{tabular}{|m{3.5cm}|m{9cm}|m{9cm}|m{17cm}|m{7cm}|}
                    \hline
                    \textbf{Paper}&\textbf{Objective}&\textbf{Methodology}&\textbf{Findings}&\textbf{Caveats}\\
                    \hline

                    \textbf{01. Roth et al. (1991):}

                    Bargaining and Market Behavior, An Experimental Study
                    %OBJECTIVE
                    &
                    \begin{itemize}
                        \item The three main goals were (i) to compare behaviour in related bargaining and market environments, (ii) to compare behavior in very different subject pools, and (iii) to use such differences to study out-of-equilibrium behaviour.
                        \item Another important methodological goal was to learn how to deal with experimental design problems associated with multinational experiments, such that factors like language or currency could be controlled for, and cultural differences can be analyzed.
                    \end{itemize}
                    %METHODOLOGY
                    &
                    \begin{itemize}
                        \item Bargaining: Ultimatum game, two players, one makes a proposed division of the sum, the other can accept (and earn the proposed share) or reject (and both get zero). Ten sessions.
                        \item Market: Buyers submit offer to single seller, for object worth same amount to every buyer, and nothing to seller. Seller can either accept the highest price offered (receiving that amount, with buyer receiving the object's value minus that amount, and others receiving zero) or reject it (all get zero). Ten markets.
                        \item Authors controlled for experimenter (ran experiences in Pittsburgh), language (translator national of relevant country), and currency (tokens as currency) effects.
                    \end{itemize}
                    %FINDINGS
                    &
                    \begin{enumerate}
                        \item Theoretical equilibrium: one player receives all the wealth (in the bargaining, the player who proposes the division; in the market, the seller).
                        \item Market environment: the observed market outcomes converge quickly to the perfect equilibrium, and do not deviate once reached, with no payoff-relevant differences observed between countries.
                        \item Bargaining environment: the observed bargaining outcomes are significantly different from the equilibrium predictions, with substantial differences between countries.
                        \item Offer and probability of acceptance: within every country these two variables were inversely related (low offers rejected more frequently than high offers), but the same does not hold across countries (higher disagreement not observed in countries with lower offers).
                        \item Role of experience in between-country differences: as subjects gained experience, between-country differences in market outcomes became smaller, while in bargaining outcomes they grew larger. This supports the view that differences in bargaining behaviour are not due to differences in languages, currencies, or experimenters, but other causes.
                        \item Role of culture: culture is offered as a source of observed subject-pool differences, and authors suggest laboratory experimentation as a path for future research.
                    \end{enumerate}

                    \fconcepts{\underline{Key concepts:}
                    \begin{itemize}
                        \item -
                    \end{itemize}}
                    %CAVEATS
                    &
                    \begin{enumerate}
                        \item Much higher percentage of army veterans in Israel and Yugoslavia than US or Japan.
                        \item Subjects were economics/business/psychology students, so sample is arguably contaminated.
                        \item Relatively small sample sizes.
                    \end{enumerate}

                    \fquestions{\underline{Questions:}
                    \begin{itemize}
                    \item What are the implications of changing the experiment from $10 to $30? Why would this change how subjects behave?
                    \end{itemize}}
                    \\

                \hline

            \end{tabular}
            }
        \end{table}
        \end{landscape}

\end{document}

A: In addition to changing the nested table/tabular environments to a single longtable environment, you must also -- as already pointed out by @DavidCarlisle -- get rid of the \resisebox wrapper in order to (a) page breaks to occur if and when needed and (b) avoid typesetting the material at a microscopic font size. Remember: The basic document font size is 8pt -- you really don't want to go much smaller than that, unless you simply despise your readers and wish to make their enjoyment of your paper worse than zero...
Next, do replace the outlandishly large column widths -- 17cm, really?! -- with more sensible choices. In addition, since your code loads the enumitem package anyway, you might as well make use of that package's \newlist and \setlist directives to create variants of the enumerate and itemize environments that are much more compact than the default ones. (See the code below for some specific suggestions.) Finally, do consider giving the table a much open "look" by getting rid of all vertical lines and using the macros of the booktabs package instead of \hline.

\documentclass[a4paper, 8pt]{extarticle}
\usepackage{geometry}
\usepackage{array}
\usepackage{fancyhdr}
\usepackage{amsmath, amsthm, amssymb}
%%\usepackage{graphicx} % 'rotating' loads 'graphicx' automatically
\usepackage{indentfirst}
\usepackage{pdflscape}
\usepackage{rotating}
\usepackage[utf8]{inputenc}
\usepackage{enumitem}
%\usepackage{euler}
\usepackage{bm}
\usepackage{econometrics}
\usepackage{booktabs}
\usepackage{%%amsfonts, % 'amssymb' loads 'amsfonts' automatically
    empheq, mathrsfs}
\usepackage[dvipsnames]{xcolor}
%%\usepackage{extsizes} % load 'extarticle' document class instead
\usepackage{hyperref}

%%% 02. CUSTOMISE FORMAT
%%\renewcommand{\baselinestretch}{1.3} % don't manipulate '\baselinestretch' directly
\usepackage[nodisplayskipstretch]{setspace}
\setstretch{1.3}

\setlength{\parskip}{1em}
\setlength{\skip\footins}{1cm}
\setlength{\footnotesep}{0.5cm}

%%% 03. POPULATE TEXT FIELDS
\title{S140 Behavioural Economics}
\author{}
\date{}

%%% 04. PRODUCE PERSONALIZED COMMANDS
\newcommand{\xb}[1]{\pmb{#1}}
\newcommand{\xbh}[1]{\pmb{\hat{#1}}}
\newcommand{\xbi}[1]{\pmb{{#1}^{-1}}}
\newcommand{\xbt}[1]{\pmb{{#1}^{'}}}
\newcommand{\tabitem}{~~\llap{\textbullet}~~}
\newcommand{\fconcepts}[1]{\textcolor{blue}{#1}}
\newcommand{\fquestions}[1]{\textcolor{red}{#1}}

%%% new code
\usepackage[normalem]{ulem} % for \uline macro
\usepackage{longtable,ragged2e}
\newlist{myitemize}{itemize}{1}
\setlist[myitemize,1]{label=\textbullet, leftmargin=*, nosep,
          before={\begin{minipage}[t]{\hsize}},
          after={\end{minipage}}}
\newlist{myenumerate}{enumerate}{1}
\setlist[myenumerate,1]{label=\arabic*., leftmargin=*, nosep,
          before={\begin{minipage}[t]{\hsize}},
          after={\end{minipage}}}
\newcolumntype{P}[1]{>{\RaggedRight}p{#1}}

%%% 05. TYPESET DOCUMENT

\begin{document}

\newgeometry{margin=5mm, asymmetric}

\begin{landscape}
\section{Overview of papers}

\begingroup
\setstretch{1.0} % revert to single-spacing
\begin{longtable}{P{3cm}P{5cm}P{5cm}P{8cm}P{5cm}}

\toprule
\textbf{Paper}&\textbf{Objective}&\textbf{Methodology}&\textbf{Findings}&\textbf{Caveats}\\
\midrule
\endhead

\midrule
\multicolumn{5}{r@{}}{\small\em continued on following page}
\endfoot

\bottomrule
\endlastfoot

%% Body of table

01.\ Roth et al.\ (1991)

Bargaining and Market Behavior, An Experimental Study &

%OBJECTIVE
\begin{myitemize}
\item The three main goals were (i) to compare behaviour in related bargaining and market environments, (ii) to compare behavior in very different subject pools, and (iii)~to use such differences to study out-of-equilibrium behaviour.
\item Another important methodological goal was to learn how to deal with experimental design problems associated with multinational experiments, such that factors like language or currency could be controlled for, and cultural differences can be analyzed.
\end{myitemize} &

%METHODOLOGY
\begin{myitemize}
\item Bargaining: Ultimatum game, two players, one makes a proposed division of the sum, the other can accept (and earn the proposed share) or reject (and both get zero).

Ten sessions.
\item Market: Buyers submit offer to single seller, for object worth same amount to every buyer, and nothing to seller. Seller can either accept the highest price offered (receiving that amount, with buyer receiving the object's value minus that amount, and others receiving zero) or reject it (all get zero).

Ten markets.
\item Authors controlled for experimenter (ran experiences in Pittsburgh), language (translator national of relevant country), and currency (tokens as currency) effects.
\end{myitemize} &

%FINDINGS
\begin{myenumerate}
\item Theoretical equilibrium: one player receives all the wealth (in the bargaining, the player who proposes the division; in the market, the seller).
\item Market environment: the observed market outcomes converge quickly to the perfect equilibrium, and do not deviate once reached, with no payoff-relevant differences observed between countries.
\item Bargaining environment: the observed bargaining outcomes are significantly different from the equilibrium predictions, with substantial differences between countries.
\item Offer and probability of acceptance: within every country these two variables were inversely related (low offers rejected more frequently than high offers), but the same does not hold across countries (higher disagreement not observed in countries with lower offers).
\item Role of experience in between-country differences: as subjects gained experience, between-country differences in market outcomes became smaller, while in bargaining outcomes they grew larger. This supports the view that differences in bargaining behaviour are not due to differences in languages, currencies, or experimenters, but other causes.
\item Role of culture: culture is offered as a source of observed subject-pool differences, and authors suggest laboratory experimentation as a path for future research.
\end{myenumerate}

\bigskip
\fconcepts{\uline{Key concepts}}
\begin{myitemize} \color{blue}
\item --
\end{myitemize}  &

%CAVEATS
\begin{myenumerate}
\item Much higher percentage of army veterans in Israel and Yugoslavia than US or Japan.
\item Subjects were economics\slash business\slash psychology students, so sample is arguably contaminated.
\item Relatively small sample sizes.
\end{myenumerate}

\bigskip
\fquestions{\uline{Questions}}
\begin{myitemize} \color{red}
\item What are the implications of changing the experiment from $10$ to $30$? Why would this change how subjects behave?
\end{myitemize}
\\

\end{longtable}
\endgroup

\end{landscape}

\end{document}

A: A supplement to nice @Mico answer (+1). With use of tabularray package amd litle bit diiferent deginition commands \fconcepts and \fquestions.
In preamble are considered only stuff related to table.
\documentclass[a4paper, 8pt]{extarticle}
\usepackage{geometry}
\usepackage{pdflscape}
\usepackage[nodisplayskipstretch]{setspace}
\setstretch{1.3}

\usepackage{bm}
\usepackage{microtype}  % new

\usepackage{enumitem}
\newlist{tabitem}{itemize}{1}
\setlist[tabitem,1]{nosep,
                    parsep=0.5ex, % added
                    label=\textbullet,
                    leftmargin=*,
                    before=\begin{minipage}[t]{\linewidth},
                    after =\end{minipage}
                    }
\newlist{tabenum}{enumerate}{1}
\setlist[tabenum,1]{nosep,
                    parsep=0.5ex, % added
                    label=\arabic*.,
                    leftmargin=*,
                    before=\begin{minipage}[t]{\hsize},
                    after =\end{minipage}
                    }
\usepackage{econometrics}
\usepackage[normalem]{ulem} % for \uline macro
\newcommand{\fconcepts}[2]{\color{blue}{#1}\par #2} % changed
\newcommand{\fquestions}[2]{\color{red}{#1}\par #2} % changed

\usepackage[dvipsnames]{xcolor}
\usepackage{tabularray}
\UseTblrLibrary{booktabs, varwidth}

\begin{document}
\newgeometry{margin=5mm, asymmetric}
\begin{landscape}
\setstretch{1.0} % revert to single-spacing
    \begin{longtblr}[
caption = {Overview of papers},
  label = {tab:papers}
                    ]{colspec = {@{} X[0.6,j] X[j] X[j] X[1.6,j]  X [j] },
                       row{1} = {font=\bfseries, c},
                      measure = vbox,
                     }
    \toprule
Paper
    &   Objective
        &   Methodology
            &   Findings
                &   Caveats             \\
    \midrule
%% Body of table
01.\ Roth et al.\ (1991)

Bargaining and Market Behavior, An Experimental Study
    &   %OBJECTIVE
        \begin{tabitem}
    \item   The three main goals were (i) to compare behaviour in related bargaining and market environments, (ii) to compare behavior in very different subject pools, and (iii)~to use such differences to study out-of-equilibrium behaviour.
    \item   Another important methodological goal was to learn how to deal with experimental design problems associated with multinational experiments, such that factors like language or currency could be controlled for, and cultural differences can be analyzed.
        \end{tabitem}
        &   %METHODOLOGY
            \begin{tabitem}
        \item Bargaining: Ultimatum game, two players, one makes a proposed division of the sum, the other can accept (and earn the proposed share) or reject (and both get zero).

            \emph{Ten sessions.}
        \item Market: Buyers submit offer to single seller, for object worth same amount to every buyer, and nothing to seller. Seller can either accept the highest price offered (receiving that amount, with buyer receiving the object's value minus that amount, and others receiving zero) or reject it (all get zero).

            \emph{Ten markets.}
        \item Authors controlled for experimenter (ran experiences in Pittsburgh), language (translator national of relevant country), and currency (tokens as currency) effects.
            \end{tabitem}
            &   %FINDINGS
                \begin{tabenum}
            \item Theoretical equilibrium: one player receives all the wealth (in the bargaining, the player who proposes the division; in the market, the seller).
            \item Market environment: the observed market outcomes converge quickly to the perfect equilibrium, and do not deviate once reached, with no payoff-relevant differences observed between countries.
            \item Bargaining environment: the observed bargaining outcomes are significantly different from the equilibrium predictions, with substantial differences between countries.
            \item Offer and probability of acceptance: within every country these two variables were inversely related (low offers rejected more frequently than high offers), but the same does not hold across countries (higher disagreement not observed in countries with lower offers).
            \item Role of experience in between-country differences: as subjects gained experience, between-country differences in market outcomes became smaller, while in bargaining outcomes they grew larger. This supports the view that differences in bargaining behaviour are not due to differences in languages, currencies, or experimenters, but other causes.
            \item Role of culture: culture is offered as a source of observed subject-pool differences, and authors suggest laboratory experimentation as a path for future research.
                \end{tabenum}
            \bigskip
            \fconcepts{\uline{Key concepts}}%
                      {
                \begin{tabitem}
            \item --
                \end{tabitem}
                      }
                &   %CAVEATS
                    \begin{tabenum}
                \item Much higher percentage of army veterans in Israel and Yugoslavia than US or Japan.
                \item Subjects were economics\slash business\slash psychology students, so sample is arguably contaminated.
                \item Relatively small sample sizes.
                    \end{tabenum}
            \bigskip
            \fquestions{\uline{Questions}}
                       {
                \begin{tabitem}
            \item What are the implications of changing the experiment from $10$ to $30$? Why would this change how subjects behave?
                \end{tabitem}
                        }   \\
    \midrule
    \end{longtblr}
\end{landscape}
\restoregeometry
\end{document}


text:
Q: When `char` type is represented on 64 bits how can it keep its range from limits.h It is possible to find architectures where the char data type is represented on 8 bytes, so 64 bits, the same as long long and in the same time the Standard requires the CHAR_MIN and CHAR_MAX to be bound -- see 5.2.4.2.1  Sizes of integer types <limits.h> from the Standard ISO 9899.
I cannot figure out why these architectures chose to represent the char so and how does it represent char values on so a large space.  So how char values are represented in such a case ?
sizeof(char)=1 all the time.  My question is, what is the value of sizeof(long long) and sizeof(int) on such an architecture ?

A:
It is possible to find architectures where the char data type is represented on 8 bytes

No. That's because a char is defined to be a byte *). But a byte doesn't necessarily have 8 bits. That's why the term octet is sometimes used to refer to a unit of 8 bits. There are architectures using more than 8 bits in a byte, but I doubt there's one with a 64bit byte, although this would be theoretically possible.
Another thing to consider is that char (as opposed to many other integer types) isn't allowed to have padding bits, so if you ever found an architecture with 64bit chars, that would mean CHAR_MIN and CHAR_MAX would be "very large" ;)

*) In fact, a byte is defined to be the unit of memory used to represent an encoded character, which is normally also the smallest addressable unit of the system. 8 bits are common, The wikipedia article mentions byte sizes up to 48 bits were used. This might not be the best source, but still, finding a 64bit byte is very unlikely.

A:
It is possible to find architectures where the char data type is represented on 8 bytes,

I don't know any. BTW, it is not only a matter of architecture, but also of ABI. BTW, you don't define what is a byte, and the bit size of char-s matters much more.
(IIRC, someone coded a weird implementation of C in Common Lisp on Linux/x86-64 which has 32 bits char-s; of course its ABI is not the usual Linux one!)

sizeof(char)=1 all the time. My question is, what is the value of sizeof(long long) and sizeof(int)  on such an architecture ?

It probably would be also 1 (assuming char, int, long long all have 64 bits) unless long long is e.g. 128 bits (which is possible but unusual).
Notice that the C standard imposes minimal bounds and bit sizes (read n1570). E.g. long long could be wider than 64 bits. I never heard of such C implementations (and I hope that when 128 bits processors become common, C will be dead).
But your question is theoretical. I know no practical C implementation with 64 bits char-s or wider than 64 bits long long. In practice assuming that char-s are 8 bits (but they could be signed or unsigned, and both exist) is a reasonable, but non universal, assumption.
Notice that C is not a universal programming language. You won't be able to code a C compiler for a ternary machine like Setun.


text:
Q: PDO can I reuse the same Statement Handle for multiple queries? I am using PDO to access my data base and am looping using two while loops with fetch at the same time, seen below:
$DBH = new PDO('mysql:host=localhost;dbname=database;charset=utf8',$dblogin,$dbpass);
$sql = 'SELECT * FROM table';
$STH = $DBH->prepare($sql);
$STH->execute();

while ($bm_table = $STH->fetch(PDO::FETCH_ASSOC))
{
    // SQL Query
    $sql1 = 'QUERY HERE';
    $STH1 = $DBH->prepare($sql1);
    $STH1->execute();

    // Loops through using different handle, but what if I used STH again?
    while ($row = $STH1->fetch(PDO::FETCH_ASSOC))
    {
        SomeFunction($bm_table,$row);
    }
}

As you can see above I am using a different statement handle ($STH, $STH1 etc.) Is this necessary? Or can I use just one statement handle for everything. The reason I have used multiple handles is as the $bm_table value that uses $STH, will still be in use while I am fetching $row wouldn't that change the value of $bm_table or stop the fetch from working? How does the handles with PDO work? Especially when in this case I have two simultaneous fetch loops running at the same time using the same PDO connection.
So the main thing I am looking for here is if I have two statements that are running simultaneously is it important that I use different handles when I continue to use the same connection?

A: $STH and STH1 are not statement handles, they're just PHP variables. You can reassign a variable if you no longer need its old value. But in the case of this code, you still need the old value.
If you assign $STH inside the outer loop to the handle returned by the second prepare() call, then when it gets back to the top of the loop and re-executes the $STH->fetch() test, it will try to fetch from the second query, not the first one. This will immediately end the outer loop because all those rows have been read.
You can reuse a statement handle for repetitions of the same query. This is very useful when the query has parameters:
$stmt = $DBH->prepare("SELECT * FROM tablename WHERE id = :id");
$stmt->bindParam(':id', $id);
foreach ($id_array as $id) {
    $stmt->execute();
    $row = $stmt->fetch();
    // do stuff with $row
}

A: If I understand you correctly what you want is dynamic query?... just put a parameter on your method then...
something like this. call it as much as you want with difference parameters though.
Class SampleClass{

 public function GetAll($tablename)
 {
     $sth = $this->prepare("SELECT * FROM $tablename");
     $sth->execute();
     return $sth->fetchAll();
 }

}


text:
Q: Sorting of Field having special characters in SoLR i am new at SoLR indexing.
I want to sort location field which have different values.it also contains values which starts with 'sAmerica, #'Japan, %India and etc.
Now when i sort this field i do want to consider special characters like 's,'#,!,~ and etc.
i want sorting which will ignore this chars and returns results like
America at 1st position,  %India at 2nd   and   #'Japan at 3rd position..
How to make it possbile? i am using PatternReplaceFilterFactory,but don't know about this.

  <analyzer type="query">
    <tokenizer class="solr.KeywordTokenizerFactory"/>
    <filter class="solr.LowerCaseFilterFactory" />
    <filter class="solr.WordDelimiterFilterFactory" catenateWords="1"  />
    <filter class="solr.PatternReplaceFilterFactory" pattern="'s" replacement="" replace="all" />
  </analyzer>
</fieldType>

A: IF you want to ignore the special characters, try using the following field type.
This would lower case the words and catenate the words excluding all special chars.
    <fieldType name="string_sort" class="solr.TextField" positionIncrementGap="1">
        <analyzer type="index">
            <tokenizer class="solr.KeywordTokenizerFactory" />
            <filter class="solr.LowerCaseFilterFactory" />
            <filter class="solr.WordDelimiterFilterFactory" catenateWords="1" />
        </analyzer>
    </fieldType>

However, this would not work for 'sAmerica as s is not a special character.
<filter class="solr.PatternReplaceFilterFactory" pattern="'s" replacement="" replace="all" />

If this is fixed pattern you need to replace it before the word delimiter with above.
Edit -- Are you using this config ?
<fieldType name="string_sort" class="solr.TextField" positionIncrementGap="1">
    <analyzer type="index">
        <tokenizer class="solr.KeywordTokenizerFactory" />
        <filter class="solr.LowerCaseFilterFactory" />
        <filter class="solr.PatternReplaceFilterFactory" pattern="'s" replacement="" replace="all" />
        <filter class="solr.WordDelimiterFilterFactory" catenateWords="1" />
    </analyzer>
</fieldType>

Have tested the following through analysis and it produces the following tokens -
KT - 'sAlgarve
LCF - 'salgarve
PRF - algarve
WDF - algarve
Can you check through the analysis.


text:
Q: JavaScript global not keeping scope? creating an autocomplete webservice json object Hi I am trying to autocomplete a list of cities, but the json object returned is not formatted for use in autocomplete that requires a field called "label":"cityname" to display the autocomplete, so i am trying to reformat the json object using an ajax call and writting it to a global variable, the issue is that once the ajax call returns, my jsData is [] an empty array... What am I doing wrong? and why doesn't the global variable keep a value?
http://www.andymatthews.net/read/2012/03/27/jQuery-Mobile-Autocomplete-now-available
<script>
        $("#nec").bind("pageshow", function(e) {
            var jsData = [];

            $.ajax({
                   url: "http://localhost:8084/REST/resources/cities",
                   data:{},
                   type: 'GET',
                   crossDomain: true,
                   dataType: 'jsonp',
                   jsonp: 'jsonp',
                   jsonpCallback: 'jsoncallback',
                   error: function(error){
                       console.log(error);
                   },
                   success: function(result) {
                       for (i = 0; i < result.length; i++){
                             jsData.push({label:result[i].name, value:result[i]});
                        }
                        console.log(JSON.stringify(jsData));
                       },
                });

            $("#textinput").autocomplete({
                target: $('#suggestions'),
                source: jsData,
                minLength: 1
            });

});
    </script>

I am a little fresh on the JS front, so there are a few things that I still have not got a hang of

A: You have to put
 $("#textinput").autocomplete({
     target: $('#suggestions'),
     source: jsData,
     minLength: 1
 });

within your success() function.
Because, jsData becomes update within success(). Execution of pageshow event's anonymous function is faster than execution of success(). So, within that function jsData remain empty.
You can retrieve data through autocomplete itself. See here

A: The problem is that jsData isn't global, but scoped inside the anonymous function.
    var jsData = [];   // make that here.

    $("#nec").bind("pageshow", function(e) {

        $.ajax({
               url: "http://localhost:8084/REST/resources/cities",
               data:{},
               type: 'GET',
               crossDomain: true,
               dataType: 'jsonp',
               jsonp: 'jsonp',
               jsonpCallback: 'jsoncallback',
               error: function(error){
                   console.log(error);
               },
               success: function(result) {
                   for (i = 0; i < result.length; i++){
                         jsData.push({label:result[i].name, value:result[i]});
                    }
                    console.log(JSON.stringify(jsData));
                   },
            });

        $("#textinput").autocomplete({
            target: $('#suggestions'),
            source: jsData,
            minLength: 1
        });

Although, i wouldn't advise a global variable. But, if it works for you, it's your wish.


text:
Q: Get the property of an object in an array by checking another property of that object This is my JSON from an API:
{
    "status": 200,
    "data": [
        {
            "location": "Random",
            "hostname": "hostname1",
            "port_range": "20001 - 37960"
        },
{
            "location": "Germany",
            "hostname": "hostname2",
            "port_range": "21201 - 21299"
        }
    ]
}

I want to write a function which will return the associated hostname when I pass the location as parameter.
For example, if I enter Germany I will get "hostname2" as a string.
If I enter Random, I will get "hostname1" as a string.


text:
Q: How to detect when a file has been downloaded? How in NodeJS can I detect when file has been downloaded?
I'm using fs.watch method, but callback is called too many times
    fs.watch(`./${IMAGES_FOLDER}/${filename}`, () => {
      if (!isDownloaded) {
        const output = fs.createWriteStream(`${DOWNLOAD_FOLDER}/${filename}.zip`)
        const archive = archiver('zip')

        archive.pipe(output)
        archive.directory(`images/${filename}`, false)
        archive.on('error', err => {throw err})
        archive.finalize()

        output.on('close', () => {
          resp.download(downloadUrl)
        })

        archive.on('error', (err) => {
          throw err
        })
      }

      isDownloaded = true
  })


text:
Q: Powershell, DataTable, ExecuteReader, zero rows returned by a query I use the following PowerShell function to run an arbitrary SQL query against an SQL Server instance, then return whatever data is there:
Function ExecSQLReader([string] $sqlText) {
    $cn = New-Object System.Data.SqlClient.SqlConnection
    $cn.ConnectionString = "Data Source={0};Initial Catalog={1};Integrated Security=SSPI;" -f $fc.server,$fc.database
    $cn.Open()
    $cmd = $cn.CreateCommand()
    $cmd.CommandText = $sqlText
    $cmd.CommandTimeout = 60
    $resTable = New-Object("System.Data.DataTable")
    try {
        $result = $cmd.ExecuteReader()
        $resTable.Load($result)
        $result.Close()
        $cn.Close()
    } catch {
        "=======ERROR in ExecSQLReader========" | DoLog
        "Message: {0}" -f $_.Exception.Message | DoLog
        "SQL: {0}" -f $sqlText | DoLog
       "=======/ERROR in ExecSQLReader=======" | DoLog
    }
    return($resTable)
}

The function works fine when there is data returned by the query.
However, the function does not return any column-related info when there is no data returned by the query.
I need to know column names / types / order etc even if there is no data rows.
I can see that the returned value is different based on resulting record count (which makes things even more complicated):

*

*an empty result for 0 records

*a [DataRow] object for a single record

*a Collection of [DataRow] objects for more than 1 record

So, the question is: how to make sure that the returned object is always of a "System.Data.DataTable" type?
Or, at least, how to make sure that columns-related information (names, types, order) is always available in function results, regardless of the number of rows returned by the query?
Any hints?

A: This is a common gotcha when returning a collection from a PowerShell function. As a workaround, add a comma before the return value:
return(,$resTable)

If no rows are returned by the query, the DataTable will contain the source query schema but with zero rows.


text:
Q: Javascript - Loop through select options clicking each one I am trying to go through a select list with 200+ entries and click on each one. When an element is clicked on it executes a function selectCountry() which adds a line to a table. I want to have it create a table with every option selected. The page of interest is at: http://www.world-statistics.org/result.php?code=ST.INT.ARVL?name=International%20tourism,%20number%20of%20arrivals.
So far I have the following, but it doesn't seem to work:
var sel = document.getElementById('selcountry');
var opts = sel.options;
for(var opt, j = 0; opt = opts[j]; j++) {selectCountry(opt.value)}

I am trying to do this in the console in Chrome.

A: One of the most useful features of dev tools is that when you write the name of a function, you get back its source code. Here's the source code for the selectCountry function:
function selectCountry(select) {
        if (select.value == "000") return;
        var option = select.options[select.selectedIndex];
        var ul = select.parentNode.getElementsByTagName('ul')[0];
        var choices = ul.getElementsByTagName('input');
        for (var i = 0; i < choices.length; i++)
            if (choices[i].value == option.value) {
                $("#selcountry:selected").removeAttr("selected");
                $('#selcountry').val('[]');
                return;
            }
        var li = document.createElement('li');
        var input = document.createElement('input');
        var text = document.createTextNode(option.firstChild.data);
        input.type = 'hidden';
        input.name = 'countries[]';
        input.value = option.value;
        li.appendChild(input);
        li.appendChild(text);
        li.onclick = delCountry;
        ul.appendChild(li);
        addCountry(option.firstChild.data, option.value);
        $("#selcountry:selected").removeAttr("selected");
        $('#selcountry').val('');
    }

Your flaw is now obvious. selectCountry accepts the entire select element as an argument as opposed to the select's value (which is a terrible design but meh). Instead of passing the value of the element, change its index:
var sel = document.getElementById('selcountry');
var opts = sel.options;
for(var i = 0; i < opts.length; i++) {
    sel.selectedIndex = i
    selectCountry(sel)
}


text:
Q: How to create a Procedure with a specific WITH clause in Oracle? I have a problem by creating a Procdure with a specific WITH clause. I use an Oracle database. I need a temp table for mapping specific values during time of execution.
In addition I have the following Oracle procedure. This Procedure will be created and executed by bringing into database:
How can I create this kind of Oracle SQL Procedure? Many thanks for helping me!

A: Use your WITH clause in a cursor FOR loop in your procedure:
DECLARE
  PROCEDURE myProcedure(pinSchema IN VARCHAR2) AS
  BEGIN
    FOR aRow IN (WITH t AS (SELECT 'myFirstOldSchema'  AS OLD_SCHEMA,
                                   'myFirstNewSchema'  AS NEW_SCHEMA
                              FROM DUAL UNION ALL
                            SELECT 'mySecondOldSchema' AS OLD_SCHEMA,
                                   'mySecondNewSchema' AS NEW_SCHEMA
                              FROM DUAL UNION ALL
                            SELECT 'myThirdOldSchema'  AS OLD_SCHEMA,
                                   'myThirdNewSchema'  AS NEW_SCHEMA
                              FROM DUAL)
                  SELECT t.*
                   FROM t
                   WHERE t.OLD_SCHEMA = pinSchema)
    LOOP
      -- Here a specific value from column "OLD_SCHEMA" must be inserted

      EXECUTE IMMEDIATE 'INSERT INTO ' || aRow.OLD_SCHEMA ||
                          '.myTable(column_1, column_2, column_3)
                           (SELECT extern_column_1,
                                   extern_column_2,
                                   extern_column_3
                             FROM ' || aRow.NEW_SCHEMA || '.myExternTable)';
    END LOOP;
  END myProcedure;

BEGIN
  FOR S IN (SELECT * FROM ROOT_SCHEMA.myTableWithSchema)
  LOOP
    -- First  loop S.mySchemata represent the value 'myFirstOldSchema'
    -- Second loop S.mySchemata represent the value 'mySecondOldSchema'
    -- Third  loop S.mySchemata represent the value 'myThirdOldSchema'
    myProcedure(S.mySchemata);
  END LOOP

  COMMIT;
END;

Not tested on animals - you'll be first!


text:
Q: Scaling and overlapping ImageViews I am a bit of an android noob, and have been struggling with this problem for far too long.
What I'm aiming for:
Two ImageViews. The first will be the width of the screen, and drawn to match the proportions of its src image (so far so easy). The second ImageView needs to be scaled, so that its width is a fixed multiple (between 0 and 1) of the first image.
I will ultimately then need to be able to touch-drag the second smaller image around on top of the first, fixed image, although this part is not the point of this question.
This will all generally be done programmatically, as the src images and the scale multiple are not known until runtime.
What I've tried: I can overlay two ImageViews in a RelativeLayout, using alignParentTop and so on. This works fine, but I can't see how to scale the images in this case.
I can alternatively scale the two ImageViews using a LinearLayout, by setting their layout_weights to 1 and the scale multiple respectively. In this case I can't get the images overlapping however (not strictly true - I have managed this with negative margins, but it is a very hacky solution and will make it almost impossible to implement the movement of the top image later).
So my question is: is there a way to fix either of the two solutions I have tried to implement? Or is there perhaps a better way to approach the problem?
(I'm not necessarily looking for an answer in code, just the approach I should take)

A: Well with what I understand,
You can use a Constraint Layout
Place 1st ImageView on your desired place
with constraints to your parent
Place Second ImageView on your desired place
with constraints to the parent (NOT WITH ANY OTHER CHILD VIEW)
The Approach is if you put a SubView In ConstraintLayout with Constraints to Parent, you can manipulate (Scale / translate) without any effect on other views.
to change the position of the View in runtime you can use
view.setTranslationX() and view.setTranslationY();
you can also create a view programmatically with Constraints to the parent
(my personal preference)
you can use this to overlay different Views in ConstraintLayout
<ImageView
        android:id="imageID1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:src="yourImageStable"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter"

// put your own constraints-
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </ImageView>

    <ImageView
        android:id="imageID2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:src="yourImageUnStable"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter"

        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

Note: This two constraint value will draw an ImageView from the Top-Left
corner of the Parent View (on Position x=0, y=0)

Remember: the View which you want to overlay should be written next to the other,
like here ImageID2 can overlay ImageID1.

    </ImageView>


text:
Q: PHP array_map() unable to parse csv data properly I am using PHP array_map function to parse a csv. This is my upload.php file:
$csv = array_map('str_getcsv', file($target_file));
    $arrlength = count($csv);
    for ($row = 0; $row < $arrlength; $row++) {
      echo "
Customer # $row
";
      echo "
";
      for ($col = 0; $col < 6; $col++) {
        echo "
".$csv[$row][$col]."
";

      }
      echo "
";
    }

The output I am getting is like this:

Now I want to use all the values in Email Template Placeholders and send them individually to each and every client using email services like sendgrid/mailchimp.
But unfortunately, I am entirely stuck of how to move forward. I am not getting an idea of how can I parse all info for a particular customer, put them into email placeholders and then shoot them email.
**I know it's a very broad topic question, but a little help/guidance will be highly appreciated. **


text:
Q: ADB command-line options when debugging from Eclipse? I am using Eclipse to debug an Android application on a device. I would like to keep the application data between debug sessions. I should be able to do this from the command line with something like this:
adb uninstall -k com.package.myprogram
adb install -r MyProgram.apk

But then, I have to debug on the command-line -- Eclipse is much nicer! Is there anyway to set these options for when I am debugging with Eclipse?? Or somehow set these options through an ADB shell, but then still use Eclipse for catching Breakpoints?

A: Eclipse does not do any black magic! for all matters ends up accessing adb.exe to talk to the device. by just typing adb on your command line, you will get host of options with which you can do a lot of things. Apart from adb, there are other tools too which can help debug. Research a bit on which suits you best.

A: Just create a launch configuration for your Android project in Eclipse (in the Run menu). If you modify your application code and run the launch configuration again, Eclipse will install the new version of your application on the device without touching any of its data. There is absolutely no need to uninstall the old version first.


text:
Q: Hide Image in Custom ListView In Android I am designing a Android Application For A Social Networking Site.
i want to display the posts which users friend Posted,
There can be 2 types of post, a photo post or a text only post,
i created a Custom listview which gets the data in JSON format. the structure of Custom List view is
Friend Name  (textView )
Posted Picture  (ImageView )
Posted Date & Time
Now The Issue is , i am not able to hide the Imageview Control For the Text only post as there is no need of image here.
when i try to hide the image for textonly posts, all the images for all the posts gets invisible.
Please help me to achieve this.
Here Is The Code
@Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View itemView = convertView;
            if ( itemView == null)
            {
                itemView = getLayoutInflater().inflate(R.layout.postlistview, parent,false);
            }
            Posts CurrentPost = myPosts.get(position);
            // myPosts Is the List Of Posts, (Usermane, Posttext, PostImage, IsPhotoPost)

            //Retrieving The User Name
            TextView userName = (TextView) itemView.findViewById(R.id.post_username);
            userName.setText(CurrentPost.getUserName());

            // Retrieving Whether the Post Is TextOnly Or Photo Post and Photo AssignMent
            ImageView imgView =(ImageView) itemView.findViewById(R.id.post_photo);
            if ( CurrentPost.IsPhotoPost() ) // If True
                {
                    URL url = null;
                    Bitmap bmp = null;
                    try {
                        url = new URL(CurrentPost.getPostPhoto());
                        bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
                    } catch (MalformedURLException e) {

                    }catch (IOException e) {

                    }
                    imgView.setImageBitmap(bmp);
                }
            else
            {
                imgView.setVisibility(View.INVISIBLE);
            }
}

When I execute it, all the post pictures gets invisible

A: You need to set the ImageView to visible when you want to display items otherwise it will always stay invisible:
ImageView imgView =(ImageView) itemView.findViewById(R.id.post_photo);
if ( CurrentPost.IsPhotoPost() ) // If True
    {
        URL url = null;
        Bitmap bmp = null;
        try {
            url = new URL(CurrentPost.getPostPhoto());
            bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
        } catch (MalformedURLException e) {

        }catch (IOException e) {

        }
        imgView.setImageBitmap(bmp);
        imgView.setVisibility(View.VISIBLE);
    }
else
{
    imgView.setVisibility(View.INVISIBLE);


text:
Q: onLocationChanged data send from activity to fragment In my activity page have onLocationChanged() for get current location.
Also this activity have ViewPager and one of viewpager have fragment which show map. this map marker also changed by onLocationChanged lat long.
My question is how send activity onLocationChanged() data to map fragment page.

A: U can create interface or save location on static LatLng and access in fragment

A: There can be several ways for communicating between Activity & Fragment. Here is simplest one.
get Fragment instance from Activity. Then set data by calling any method of Fragment.
YourFragment fragment = (YourFragment) getFragmentManager().findFragmentById(R.id.example_fragment);

Or
YourFragment fragment = (YourFragment) getFragmentManager().findFragmentByTag("tag");
fragment.setLocation(passLocation);

A: You can use local broadcast.When you receive callback on activity in onLocationChanged().Then broadcast latlng and receive data in fragment.


text:
Q: How to arrange model items in a grid How do I organize my items in a table
so that my row has lets say 4 columns, in my
  foreach(var item in Model.Data)
  {
   item.name
  }

How do I have item.name[i], item.name[i+1] so that I can fill out my column for the row?

A: I'm not clear on exactly what you're asking or what version of MVC or View Engine, but the general pattern of a table displaying a collection of objects is

            Name
            Description
            Hair Color

        <% foreach (var item in Model) { %>

            <%= Html.Encode(item.Name) %>
            <%= Html.Encode(item.Description) %>
            <%= Html.Encode(item.HairColor) %>

        <% } %>