text:
Q: Format a date in C++ I have a series of date strings in the format: "30-05-2001"
string date1 = "30-05-2001";

I would like to parse the date into Day, Month, Year. Now an easy way
of doing this would be just to call the function sscanf. But I'd like to
explore other possiblilties and from searching the web the following
function from time.h was recommended:
char *strptime(const char *buf, const char *format, struct tm *tm);

Does any anyone have experience using this function? Some short example would be
very helpful.
Thanks!

A: std::istringstream buffer("30-05-2001");
int day = 0;
int month = 0;
int year = 0;
char dummy = 0;

buffer >> day >> dummy >> month >> dummy >> year;
// TODO: validate values here

You can perform different reads on the data if you want to also validate that the dummy equals '-'.

A: Source:
#include <time.h>
...

struct tm tm;
time_t t;

if (strptime("6 Dec 2001 12:33:45", "%d %b %Y %H:%M:%S", &tm) == NULL)
    /* Handle error */;

printf("year: %d; month: %d; day: %d;\n",
        tm.tm_year, tm.tm_mon, tm.tm_mday);
printf("hour: %d; minute: %d; second: %d\n",
        tm.tm_hour, tm.tm_min, tm.tm_sec);
printf("week day: %d; year day: %d\n", tm.tm_wday, tm.tm_yday);

tm.tm_isdst = -1;      /* Not set by strptime(); tells mktime()
                          to determine whether daylight saving time
                          is in effect */
t = mktime(&tm);
if (t == -1)
    /* Handle error */;
printf("seconds since the Epoch: %ld\n", (long) t);"

A: See here for an example. Also good explanation how to use the conversion specifiers etc.
Edit: KMan was faster :)
Edit2: Link leads to a desctiption of
char *strptime(const char *restrict buf, const char *restrict format, struct tm *restrict tm);

and also a short example on how to use.
The Site is provided by

The Open Group Base Specifications
  Issue 6 IEEE Std 1003.1, 2004 Edition

A: Just in case you want to understand how it works (no blackbox) or
if you need the stuff to fly (no function calls) then here are a
few tips for you:
//             0123456789
char date[] = "30-05-2001"; // DD-MM-YYYY
int day, month, year;

day = (date[0] - '0') * 10 + (date[1] - '0');
month = (date[3] - '0') * 10 + (date[4] - '0');
year = (date[6] - '0') * 1000 + (date[7] - '0') * 100 + (date[8] - '0') * 10 + (date[9] - '0');

This (untested) code is clother to the right way to do what you
wanted to do as it only does what you need to do (not more, not
less). Safe, small, simple, FAST.
If you are unsure of the date (user input) then you will have to
check for its validity (or accept the idea to live with invalid
dates in your application).


text:
Q: AttributeError: 'bytes' object has no attribute 'find_all' I am trying to web scrape cricket score webiste to get a scorecard.
But i am getting this attribute error:
Traceback (most recent call last):
  **File "J:/Python Programs/Web Scraper/ESPN Cric Info.py", line 6, in
soup = BeautifulSoup.find(page.content, 'html.parser')

File "J:\Python Programs\Web Scraper\venv\lib\site-packages\bs4\element.py", line 1282, in find
    l = self.find_all(name, attrs, recursive, text, 1, ****kwargs**)
**
AttributeError: 'bytes' object has no attribute 'find_all'****
My Code Is:
import requests
from bs4 import BeautifulSoup

page = requests.get('https://www.espncricinfo.com/series/19430/scorecard/1187016/india-vs-bangladesh-1st-test-icc-world-test-championship-2019-2021')
soup = BeautifulSoup.find(page.content, 'html.parser')
scorecard = soup.find(id='gp-inning-01')

print(scorecard)

It Would Be A Great Help If You Reolve This.

A: import requests
from bs4 import BeautifulSoup

page = requests.get('https://www.espncricinfo.com/series/19430/scorecard/1187016/india-vs-bangladesh-1st-test-icc-world-test-championship-2019-2021')
soup = BeautifulSoup(page.content, 'html.parser')
scorecard = soup.find_all('gp-inning-01')

print(scorecard)

Try this

A: You made two small mistakes, but your code was almost correct:

*

*you need to remove .find after BeautifulSoup, as this line is made just for creating the soup but not searching anything

*you need to use .text instead of .content when retrieving the request, as BeautifulSoup works with strings rather than bytes.

Here is the final code:
import requests
from bs4 import BeautifulSoup

page = requests.get('https://www.espncricinfo.com/series/19430/scorecard/1187016/india-vs-bangladesh-1st-test-icc-world-test-championship-2019-2021')
soup = BeautifulSoup(page.text, 'html.parser')
scorecard = soup.find(id='gp-inning-01')

print(scorecard)

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to save session using firebase? I have implemented user registration in my application using
firebase.auth().SignInWithEmailAndPassword (email, password)

And I need that when a user comes to the site, his profile will be synchronized as logged in, even the page will be reloaded or closed and opened again
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      email: " ",
      password: " ",
      hasAccount: false,
    }
  }
  componentDidMount() {
    const db = firebase.database();
    console.log(db)
  }

  handleChange = ({ target: { value, id } }) => {
       this.setState({ [id] : value })
  }

  createAccount = () => {
    const { email, password } = this.state;

        firebase.auth().signInWithEmailAndPassword( email, password)
          .then(Response => {
            console.log(Response)
            this.setState({ hasAccount: true })
          })
        .catch(error => console.log(error))

        const auth = firebase.app().auth();
        auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL)
  }

A: In many environments Firebase already persists the user's authentication credentials, and you don't need to explicitly enabled that with auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL).
But to pick up the restored authentication state when the app is restarted/page reloaded, you need to use an onAuthStateChanged handler, as shown in the fist snippet in the documentation on getting the current user:
firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
    this.setState({ hasAccount: true })
  } else {
    // No user is signed in.
  }
});

You'll typically put this code in the constructor of your component, so that it starts monitoring authentication state right away.

A: componentDidMount() {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
    // User is signed in.
      this.setState({ hasAccount: true })
    }
  });


text:
Q: How to show a bottom navigation drawer when clicking navigation icon on BottomAppBar? So, I made a memo Android app, and I've used the new material BottomAppBar with a FAB, and I want to show a bottom navigation drawer when I press on the hamburger item (R.id.home) on my BottomAppBar, but I all what I've found on the Internet was regular Navigation drawers (that expand from the side).
Also, the BottomAppBar allows me to choose only a still icon for the navigation icon using app:navigationIcon attribute, while I want to have the same animated hamburger icon that converts to an arrow.
Here's my main activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

        <ListView
            android:id="@+id/noteList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:listitem="@layout/note_view" />

    </androidx.core.widget.NestedScrollView>

    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        app:backgroundTint="@color/colorPrimary"
        app:fabAlignmentMode="center"
        app:fabAnimationMode="slide"
        app:fabCradleRoundedCornerRadius="40dp"
        app:hideOnScroll="true"
        app:navigationIcon="@drawable/ic_menu_24dp" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_create_24dp"
        app:backgroundTint="@color/colorAccent"
        app:layout_anchor="@id/bar"
        app:rippleColor="@color/rippleColor" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Note: I'm trying to make an app like Reply (a Material design study) that's available on material.io.


text:
Q: OBD2Kit Swift example can't typecast, keep getting nil Since there was no example code for using OBD2Kit and Swift I forked it into https://github.com/YannisDC/OBD2Kit and used it as a pod.
I translated some OBJ-C example code but can't seem to downcast the FLWiFiScanTool into the ELM327 type. Why do I keep getting nil?
import UIKit
import OBD2Kit

class ViewController: UIViewController, FLScanToolDelegate {

    @IBOutlet weak var hostIpAddress: UITextField!

    var scanTool: ELM327!

    @IBOutlet weak var statusLabel: UILabel!
    @IBOutlet weak var scanToolLabel: UILabel!
    @IBOutlet weak var rpmLabel: UILabel!
    @IBOutlet weak var speedLabel: UILabel!
    @IBOutlet weak var tempLabel: UILabel!
    var scanning = false

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.hostIpAddress.text = "192.168.0.10"
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func scanButton(sender: UIButton) {
        if !scanning {
            startScan()
        } else {
            stopScan()
        }
    }

    func startScan() {
        if let scanTool = ELM327(host: self.hostIpAddress.text!, andPort: 35000) {
            self.statusLabel.text = "Initializing..."
            scanTool.useLocation = true
            scanTool.delegate = self
            scanTool.startScanWithSensors({() -> [AnyObject] in
                dispatch_async(dispatch_get_main_queue(), {() -> Void in
                    self.statusLabel.text = "Scanning..."
                    self.scanToolLabel.text = scanTool.scanToolName
                })

//                let sensors: [AnyObject] = [    OBD2Sensor.SensorEngineRPM as! AnyObject,
//                                                OBD2Sensor.SensorVehicleSpeed as! AnyObject,
//                                                OBD2Sensor.SensorOxygenSensorsPresent as! AnyObject    ]

                let sensors: [AnyObject] = [    0x0C,
                                                0x0D,
                                                0x13    ]
                return sensors
            })
            self.scanTool = scanTool
            print("So far succesfull")
            scanning = !scanning
        } else {
            self.statusLabel.text = "Not working"
        }
    }

    func stopScan() {
        statusLabel.text = "Stopped"
        let scanTool: ELM327 = self.scanTool
        scanTool.cancelScan()
        scanTool.sensorScanTargets = nil
        scanTool.delegate = nil
        scanning = !scanning
    }

    // MARK: - FLScanToolDelegate

    func scanTool(scanTool: FLScanTool, sensor: FLECUSensor) {
        var sensorLabel: UILabel? = nil
        switch sensor.pid {

        case OBD2Sensor.SensorEngineRPM:
            sensorLabel = self.rpmLabel

        case OBD2Sensor.SensorVehicleSpeed:
            sensorLabel = self.speedLabel

        default:
            sensorLabel = self.tempLabel
        }

        self.showSensorValue(sensor, onLabel: sensorLabel!)
    }

    func showSensorValue(sensor: FLECUSensor, onLabel label: UILabel) {
        let sensorValue: String = "\(sensor.valueStringForMeasurement1(false)) \(sensor.imperialUnitString)"
        dispatch_async(dispatch_get_main_queue(), {() -> Void in
            label.text = sensorValue
        })
    }

}

Edit 1:
I can already scan for the tool now since ELM327 is a FLWiFiScanTool and not the other way around. I can get the toolname so it's connecting but can't seem to get the sensors output.

A: I managed to figure it out. The expected sensors array should be one of NSNumbers so I casted the sensors UInt's to NSNumbers.
And I also missed the didUpdateSensor part in the scanTool function.
Make sure to use the metric system, this is somehow way more reliable in my case. (My car is using the metric system as well, maybe that's why.)
import UIKit
import OBD2Kit

class ViewController: UIViewController, FLScanToolDelegate {
    var scanTool: ELM327!

    @IBOutlet weak var statusLabel: UILabel!
    @IBOutlet weak var scanToolLabel: UILabel!
    @IBOutlet weak var rpmLabel: UILabel!
    @IBOutlet weak var speedLabel: UILabel!
    @IBOutlet weak var tempLabel: UILabel!
    var scanning = false

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func scanButton(sender: UIButton) {
        if !scanning {
            startScan()
        } else {
            stopScan()
        }
    }

    func startScan() {
        if let scanTool = ELM327(host: "192.168.0.10", andPort: 35000) {
            self.statusLabel.text = "Initializing..."
            scanTool.useLocation = true
            scanTool.delegate = self
            scanTool.startScanWithSensors({() -> [AnyObject] in
                dispatch_async(dispatch_get_main_queue(), {() -> Void in
                    self.statusLabel.text = "Scanning..."
                    self.scanToolLabel.text = scanTool.scanToolName
                })

                let sensors: [AnyObject] = [ OBD2Sensor.SensorEngineRPM as NSNumber, OBD2Sensor.SensorVehicleSpeed as NSNumber, OBD2Sensor.SensorOxygenSensorsPresent as NSNumber ]

                return sensors
            })
            self.scanTool = scanTool
            print("So far succesfull")
            scanning = !scanning
        } else {
            self.statusLabel.text = "Not working"
        }
    }

    func stopScan() {
        statusLabel.text = "Stopped"
        let scanTool: ELM327 = self.scanTool
        scanTool.cancelScan()
        scanTool.sensorScanTargets = nil
        scanTool.delegate = nil
        scanning = !scanning
    }

    // MARK: - FLScanToolDelegate

    func scanTool(scanTool: FLScanTool!, didUpdateSensor sensor: FLECUSensor!) {
        var sensorLabel: UILabel? = nil
        switch sensor.pid {

        case OBD2Sensor.SensorEngineRPM:
            sensorLabel = self.rpmLabel

        case OBD2Sensor.SensorVehicleSpeed:
            sensorLabel = self.speedLabel

        default:
            sensorLabel = self.tempLabel
        }

        self.showSensorValue(sensor, onLabel: sensorLabel!)
    }

    func showSensorValue(sensor: FLECUSensor, onLabel label: UILabel) {
        let sensorValue: String = "\(sensor.valueStringForMeasurement1(true)) \(sensor.metricUnitString)"
        dispatch_async(dispatch_get_main_queue(), {() -> Void in
            label.text = sensorValue
        })
    }

}


text:
Q: the meaning of "rather than not at all" I'm glad that Paul Torday took up writing in his 60s (rather than not at all).
Can you tell me what is meant by the phrase "rather than not at all". The literal meaning does not make any sense and the possible idiomatic one I am not able to find on the internet.

A: You can understand this phrase, rather than not at all, literally, in the context, like this:

rather than = instead of
not at all = not taking up writing (in other words, never start writing)


text:
Q: replace.if startswith('CERTAIN STRING') and then returning a list, horrible a titles example = ['1 Hey this is the first (1) level.\n', '2 This is what we call a second level.\n','','3 This is the third (3) level, deal with it.']
example = [i.rstrip() for i in example]

dictHeaders =   [['1 ','One'],
                ['2 ','Two'],
                ['3 ','Three'],
                ['4 ','Four'],
                ['5 ','Five'],
                ['6 ','Six']]

example = [eachLine.replace(old,new,1) if eachLine.startswith(old) for eachLine in article for old, newFront in dictHeaders]

I need it to return...
example = ['One Hey this is the first (1) level.', 'Two This is what we call a second level.','','Three This is the third (3) level, deal with it.']

I have created dictHeaders as a list of lists for a reason to add move values into each key for each instance. For example, if eachLine.startswith(old) then append One to the beginning and possible another string to the end of the line. If I can do the above with a dict, I'd rather go that route.. I'm new to Python.
I thought this is the route to go instead of...
def changeCode(example,dictHeaders):
    for old, newFront in dictHeaders:
        for eachLine in example:
            if eachLine.startswith(old):
            return eachLine.replace(old,newFront,1)

Every time I run the above it only returns the top line, but I need it to return the entire list example modified..

A: The best approach would be to use regex and replace the numbers intelligently:
import re

examples = [
  '1 Hey this is the first (1) level.\n',
  '2 This is what we call a second level.\n',
  '3 This is the third (3) level, deal with it.',
  '56 This is the third (3) level, deal with it.'
]

class NumberReplacer(object):
  def __init__(self):
    self.ones = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
    self.teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
    self.tens = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']

  def convert(self, number):
    if number == 0:
      return 'zero'
    elif number < 10:
      return self.ones[number - 1]
    elif number <= 19:
      return self.teens[number % 10]
    else:
      tens = self.tens[number // 10 - 2]
      ones = number % 10 - 1

      if ones == -1:
        return tens
      else:
        return ' '.join([tens, self.ones[ones]])

  def __call__(self, match):
    number = int(match.group(0))

    return self.convert(number).title()

replacer_regex = re.compile('^\s*(\d+)')
replacer = NumberReplacer()

for example in examples:
  print replacer_regex.sub(replacer, example)

A: You are close. You shouldn't return from inside the for loops. Instead you can create a list as the return value and append each result to it
def changeCode(example,dictHeaders):
    retval = []
    for eachLine in example:
        for old, newFront in dictHeaders:
            if eachLine.startswith(old):
                retval.append(eachLine.replace(old,newFront,1))
                break
        else:
            retval.append(eachLine)
    return retval


text:
Q: How to efficiently render a dynamic list of subelements in Vaadin Given a Vaadin application where a user can add and remove elements of a list that is also rendered in the browser, I am wondering what the most efficient way of handling such manipulations would be. Currently, I am simply using the add and remove methods.
I am only experienced with Apache Wicket where one should avoid to manipulate the component tree for performance reasons. In the documentation, I only found a section on how to handle repeated elements in Polymer but nothing on how this can be done using the "simple" API.
Am I choosing the right approach?

A: The Vaadin UI code runs on the server, so the add/remove operations don't affect the DOM directly. When a response is sent back to the browser, Vaadin will look at the difference between the previous UI state and the current and send appropriate instructions to the browser client to update the DOM. In this case, the instruction would be something like "remove the following components:...". The actual DOM manipulation is handled by Vaadin, and is not something you can affect yourself.
If you run into performance issues, help us out by filing an issue ticket on GitHub, so we can take a look at it https://github.com/vaadin/flow/issues


text:
Q: Meat is sold at the butchers' or meat is sold at butchers? I'm not an English speaker. Could you tell me what is wrong with the sentence below?
Meat is sold at butchers.
The correction says meat is sold at the butchers'. I have no idea why need to have the before butcher'.

A: I am assuming for this purpose that the apostrophe in your title is incorrectly placed - and should be before the s. Otherwise it would be Meat is sold at (all) butchers' (shops).
Meat is sold at the butcher's is an idiomatic expression. It can be referring to a specific butcher's shop. Or it can refer to any and all butchers, in the same way people say I love swimming in the sea. The latter doesn't refer to any particular sea, even though the definite article is used. Similarly: I love the fresh air, I enjoy the sense of achievement. These uses permit the definite article to describe something in general.
Meat is sold at butchers This is equally idiomatic and could mean Meat is sold in butchers' (shops), with the word shops elided. If you intended butchers to refer to individuals rather than shops it would be idiomatic to say meat is sold by butchers.

A: Oftentimes, in standard English (in the US), we would include the definite article ("the"), and we would say:

You can buy meat at the butcher's.

(which is a shorter way of saying, "You can buy meat at the butcher's shop")
-or-

You can buy meat at the butchers'.

(which is just a shorter way of saying, "You can buy meat at the butchers' shop" or "You can buy meat at the butchers' shops").

For most purposes, the meaning of both of these is the same.
However, there could be a slight difference in nuance between the two.
"The butcher's," with the apostrophe before the s, could be used to imply that there is one particular shop being discussed, especially if there is one main butcher at that shop or if there is a single owner of the shop.
"The butchers'," with the apostrophe after the s, could be used to imply that there are several butchers working at a single shop, or that there is a group of owners of the shop. Or it could be used if the speaker/writer is making a general statement about many different butcher shops (for example: "Fresh sausage is available at the butchers' throughout Vienna").

Oxford's Learner's Dictionary says that the singular for a shop that sells meat has an apostrophe -s while the plural does not:

2 butcher's (pl. butchers) a shop/store that sells meat

Following that rule, a very general statement could be made by leaving out the definite article and the apostrophe:

Meat is sold at butchers.

Some examples:

Variations on cured pork ... are signature flavorings for Roman dishes, found at butchers like Viola....

^ Fodor's Rome, with The Best City-Walks and City Day Trips, 2013

Instead, you want to purchase lard that is refrigerated, which you can find at butchers, Mexican markets, or at a farmers' market.

^ The Homsesick Texan Cookbook, by Lisa Fain, 2011

Hog casings seem to be pretty available at butchers shops if you just ask, or you can find them easily online.

^ Serious Eats, 2013

In supermarkets and specialty food shops, endless varieties of cheese and sausage can now be found much more readily: mascarpone and goat cheeses from Italy; cow's milk cheeses from France and Spain; chorizo, andouille and boudin sausages at butchers with customers attuned to Latin American and European cuisines.

^ an article in New York Times, 1997

Note that dry-cleaners' shops are treated a little differently. (Dry-cleaners clean clothes. "Cleaners" is the shortened form, and it is used much more often nowadays than the more formal "dry-cleaners.")

I will stop by the cleaners to pick up my suits.

or

Don't forget to take your claim ticket whenever you leave your clothes at the cleaners.

The definite article is almost always used for "cleaners" (in other words, it's almost always "the cleaners"), and usually no apostrophe is used.


text:
Q: shell script doesn't run correctly in cron I want to call a shell script I wrote from a cron. The shell script uses the program Linkchecker. If I run the shell script from the terminal it works just fine. However, when cron runs I get the following errors:

File
  "/Users/keith/etc/cron/linkchecker",
  line 40, in
      from linkcheck.director import console, check_urls, get_aggregate
  File
  "/opt/local/lib/python2.5/site-packages/linkcheck/director/init.py",
  line 25, in
      from . import aggregator, console   File
  "/opt/local/lib/python2.5/site-packages/linkcheck/director/aggregator.py",
  line 25, in
      from . import logger, status, checker, cleanup   File
  "/opt/local/lib/python2.5/site-packages/linkcheck/director/status.py",
  line 20, in
      from . import task   File "/opt/local/lib/python2.5/site-packages/linkcheck/director/task.py", line 20, in
      from . import console   File "/opt/local/lib/python2.5/site-packages/linkcheck/director/console.py",
  line 27, in
      stderr = codecs.getwriter(i18n.default_encoding)(sys.stderr,
  errors="ignore")   File
  "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/codecs.py",
  line 930, in getwriter
      return lookup(encoding).streamwriter
  LookupError: unknown encoding:
  Traceback (most recent call last):
  File
  "/Users/keith/etc/cron/linkchecker",
  line 40, in
      from linkcheck.director import console, check_urls, get_aggregate
  File
  "/opt/local/lib/python2.5/site-packages/linkcheck/director/init.py",
  line 25, in
      from . import aggregator, console   File
  "/opt/local/lib/python2.5/site-packages/linkcheck/director/aggregator.py",
  line 25, in
      from . import logger, status, checker, cleanup   File
  "/opt/local/lib/python2.5/site-packages/linkcheck/director/status.py",
  line 20, in
      from . import task   File "/opt/local/lib/python2.5/site-packages/linkcheck/director/task.py", line 20, in
      from . import console   File "/opt/local/lib/python2.5/site-packages/linkcheck/director/console.py",
  line 27, in
      stderr = codecs.getwriter(i18n.default_encoding)(sys.stderr,
  errors="ignore")   File
  "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/codecs.py",
  line 930, in getwriter
      return lookup(encoding).streamwriter
  LookupError: unknown encoding:
  Traceback (most recent call last):
  File
  "/Users/keith/etc/cron/linkchecker",
  line 40, in
      from linkcheck.director import console, check_urls, get_aggregate
  File
  "/opt/local/lib/python2.5/site-packages/linkcheck/director/init.py",
  line 25, in
      from . import aggregator, console   File
  "/opt/local/lib/python2.5/site-packages/linkcheck/director/aggregator.py",
  line 25, in
      from . import logger, status, checker, cleanup   File
  "/opt/local/lib/python2.5/site-packages/linkcheck/director/status.py",
  line 20, in
      from . import task   File "/opt/local/lib/python2.5/site-packages/linkcheck/director/task.py", line 20, in
      from . import console   File "/opt/local/lib/python2.5/site-packages/linkcheck/director/console.py",
  line 27, in
      stderr = codecs.getwriter(i18n.default_encoding)(sys.stderr,
  errors="ignore")   File
  "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/codecs.py",
  line 930, in getwriter
      return lookup(encoding).streamwriter
  LookupError: unknown encoding:
  Traceback (most recent call last):
  File
  "/Users/keith/etc/cron/linkchecker",
  line 40, in
      from linkcheck.director import console, check_urls, get_aggregate
  File
  "/opt/local/lib/python2.5/site-packages/linkcheck/director/init.py",
  line 25, in
      from . import aggregator, console   File
  "/opt/local/lib/python2.5/site-packages/linkcheck/director/aggregator.py",
  line 25, in
      from . import logger, status, checker, cleanup   File
  "/opt/local/lib/python2.5/site-packages/linkcheck/director/status.py",
  line 20, in
      from . import task   File "/opt/local/lib/python2.5/site-packages/linkcheck/director/task.py", line 20, in
      from . import console   File "/opt/local/lib/python2.5/site-packages/linkcheck/director/console.py",
  line 27, in
      stderr = codecs.getwriter(i18n.default_encoding)(sys.stderr,
  errors="ignore")   File
  "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/codecs.py",
  line 930, in getwriter
      return lookup(encoding).streamwriter
  LookupError: unknown encoding:
  Traceback (most recent call last):
  File
  "/Users/keith/etc/cron/linkchecker",
  line 40, in
      from linkcheck.director import console, check_urls, get_aggregate
  File
  "/opt/local/lib/python2.5/site-packages/linkcheck/director/init.py",
  line 25, in
      from . import aggregator, console   File
  "/opt/local/lib/python2.5/site-packages/linkcheck/director/aggregator.py",
  line 25, in
      from . import logger, status, checker, cleanup   File
  "/opt/local/lib/python2.5/site-packages/linkcheck/director/status.py",
  line 20, in
      from . import task   File "/opt/local/lib/python2.5/site-packages/linkcheck/director/task.py", line 20, in
      from . import console   File "/opt/local/lib/python2.5/site-packages/linkcheck/director/console.py",
  line 27, in
      stderr = codecs.getwriter(i18n.default_encoding)(sys.stderr,
  errors="ignore")   File
  "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/codecs.py",
  line 930, in getwriter
      return lookup(encoding).streamwriter
  LookupError: unknown encoding:
  Traceback (most recent call last):
  File
  "/Users/keith/etc/cron/linkchecker",
  line 40, in
      from linkcheck.director import console, check_urls, get_aggregate
  File
  "/opt/local/lib/python2.5/site-packages/linkcheck/director/init.py",
  line 25, in
      from . import aggregator, console   File
  "/opt/local/lib/python2.5/site-packages/linkcheck/director/aggregator.py",
  line 25, in
      from . import logger, status, checker, cleanup   File
  "/opt/local/lib/python2.5/site-packages/linkcheck/director/status.py",
  line 20, in
      from . import task   File "/opt/local/lib/python2.5/site-packages/linkcheck/director/task.py", line 20, in
      from . import console   File "/opt/local/lib/python2.5/site-packages/linkcheck/director/console.py",
  line 27, in
      stderr = codecs.getwriter(i18n.default_encoding)(sys.stderr,
  errors="ignore")   File
  "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/codecs.py",
  line 930, in getwriter
      return lookup(encoding).streamwriter
  LookupError: unknown encoding:

I have chmod 777 the linkchecker file. I have moved the linkchecker file to my current home directory. I added the cron by saying
crontab -e

I put in
38       12      *       *       5      /Users/keith/etc/cron/linkchecker.sh

The first line of my shell script is #!/bin/sh
So the only thing I can think of is I'm missing some environment variables when cron runs. When I add env at the top of my script and compare the variables from when cron runs versus from the terminal there is a difference. According to https://stackoverflow.com/questions/1694942/environment-variable-used-in-shell-script-appear-blank-in-log-file-when-run-by-cr I can add . /etc/profile and that should put in the correct environment variables. This does not appear to be sucking in the variables because the variables are still the same when I use env.
I am on a Mac if that makes any difference. Also I pasted in the working variables at the top of my script that worked when I run from terminal and cron still didn't work.

A: How are you getting the traceback?  The cron entry you've posted doesn't seem to be redirecting output to a file.
Are you using a different version of Python when you run the script interactively?  This can happen if you're using, e.g., MacPorts and you've got a newer version of Python there than is installed by OS X.  If that traceback comes from your cron job, it appears to be running 2.5.  Is this what you end up with when you type python interactively?
Can you show us the script?


text:
Q: Get Data from SAS Macro (list of values) to SAS table (column) I am trying to create a SAS table from Macro variable using PROC SQL:
I have a list of value saved in a macro variable :
%let l=1,2,3;
I want to create a SAS table with a column containing the values of the macro variable :
1
2
3
Thank you very much for your help.
Sincerely,
Abdeljalil

A: you should so some effort to solving this yourself.
Put the values into a string, parse the string and output the values you would like.
%let l=1,2,3;

data want;
str = "&l";
do i=1 to countw(str,',');
   value = input(scan(str,i,","),best.);
   output;
end;

/*drop other variables if you want*/
drop str i;
run;

A: Something like this?
%let age=%str(12,13,15);
proc sql;
    select * from sashelp.class where age in (&age);
quit;

A: You have a data set that contains a list of names and you want to place these names into a macro variable for later use. That will work as long as the macro variable does not go beyond the 64K limit.
If the value hits this limit, then you can use macro processing to retrieve the names from the data set. Since a macro definition does not have the 64K restriction, it can be used to create the list for you.
In the sample code on the Full Code tab, we have a list of names that we want to use on an INPUT statement along with a given informat. This sample demonstrates how to create the list without having to use a macro variable.
data one;
   input name $;
   datalines;
abc
def
ghi
;
run;

%macro test;
  %let dsid=%sysfunc(open(one));
  %let cnt=%sysfunc(attrn(&dsid,nobs));
    %do i=1 %to &cnt;
      %let rc=%sysfunc(fetchobs(&dsid,&i));
      %cmpres(%sysfunc(getvarc(&dsid,%sysfunc(varnum(&dsid,name))))) $4.
    %end;
  %let rc=%sysfunc(close(&dsid));
%mend test;

/** Using %PUT to see outcome **/
/** %test could be used on an INPUT statement **/
%put %test;

source: http://support.sas.com/kb/39/605.html


text:
Q: Property Lists: How to use it to provide easy exchangeable default data to the user? I want to ship some default data with my app. This data can be stored perfectly in a property list. The strucure is simple:
Root
    0
        animalType = cat
        animalName = Tom
    1
        animalType = dog
        animalName = Rambo

I thought: When I use a property list rather than hard-coding it somewhere, then I could easily provide more defaults to choose from after the app is distributed already. If I would hard-code it, I would have to provide heavy upgrades every time, and Apple would take weeks to let them pass.
But there's one thing I don't get. I make that property list manually in Xcode and put that in my Resources group. As far as I know, Xcode would compile it into some binary format. In my app I would use NSPropertyListSerialization to create a NSDictionary out of it. But this property list would not get placed into the documents directory of the sandbox, right? So if the application would download an update of that property list some time in the future, the update would have to go into documents dir, but the app would still look at the old plist in the root, right? Where to put it? Must I copy it to documents, just like an sqlite database?
And the other thing: When I edit the plist and provide the whole thing as an XML for download/update from a server, then of course that thing would not be "compiled" into some binary format. How would that work? Would NSPropertyListSerialization have trouble reading it? Must I compile that thing every time with XCode and let the app download some binary stuff?

A: There are two commonly used property list formats: proprientary binary format and xml format (DTD). You can use either of them, and NSPropertyListSerialization will detect automatically, which one is used for your data when de-seralizing.
XML format is more verbose, but it's simple to generate. If you're publishing data from server, you might consider generating xml plist, and compress it with gzip or something.
Now to your first question about where to store the data. To make application payload smaller you might first check documents directory for updated plist, and if it is not present - load default plist from your application bundle.

A: One general approach used is to always copy plists or other updated elements into the application documents directory - then you just always load from there, and replace when there is an update.
Or you could pre-load the data into a database, download plist updates and refresh the database entries at that time.


text:
Q: Write a total, terminating Haskell function given a type Given a type, determine if you can write a total, terminating Haskell function.
For a type like Int -> Int, we know that the finite-precision integer type Int covers at least the range [-2^29, 2^29-1] so there are finitely many possible mappings we can have from Int to Int so we can write a total, terminating function.
For example, given the following type: (a -> b) -> (b -> c) -> (a -> c), how can I determine if we can write a total terminating function for using that type as the function signature? Or this type (a -> c) -> ((a, b) -> c).
Would greatly appreciate guidance through this problem! This is a homework question so I am only seeking guidance.

A: Given:
(a -> b) -> (b -> c) -> (a -> c)

We know that this is not necessarily partial by the Curry–Howard correspondence—interpreting -> as logical implication, product types as AND, and sum types as OR—we find it forms a tautology. But in order to find an implementation and know that it is total, we need to actually find the proof:
   (a → b) → (b → c) → a → c
-- ~~~~~~~~~~~~~~~~~~~~~~~~~
-- currying
-- ~~~~~~~~~~~~~~~~~~~~~~~~~
   (a → b) ∧ (b → c) → a → c
--           ~~~~~~~~~~~~~~~
-- currying
--           ~~~~~~~~~~~~~~~
   (a → b) ∧ (b → c) ∧ a → c
-- ~~~~~~~~~~~~~~~~~
-- commutativity of AND
-- ~~~~~~~~~~~~~~~~~
   (b → c) ∧ (a → b) ∧ a → c
--           ~~~~~~~~~~~
-- modus ponens
--           ~
   (b → c) ∧ b → c
-- ~~~~~~~~~~~
-- modus ponens
-- ~
   c → c
-- ~~~~~
-- reflexivity of implication
-- ~
   1

(This is a hypothetical syllogism.)
We can use this proof to arrive at an implementation—skipping the currying steps here, and with modus ponens corresponding to function application:
f ab bc a = bc (ab a)

The argument is similar for (a -> c) -> ((a, b) -> c) interpreting (a, b) as a ∧ b (logical AND).

A: A partial answer:
For finite data types, such as Int you mention, or Bool (all the Bounded could be included I guess). Then yes, you can provide a complete function:
if you have the time to cover all the cases for Int:
negative :: Int -> Int
negative 0 = 0
negative 1 = -1
negative 2 = -2
negative 3 = -3
...............
...............
negative -1 = 1
negative -2 = 2
...
...
...

until you cover all the cases... It's just an example.
With Bool is a little more obvious you can:
negative :: Bool -> Bool
negative False = True
negative True  = False

but, for functions, that takes functions, they are called Uncontable set, so you can provide all the posible combination of functions, so it will never ends, you will always find another "level" of function of functions, it's a "bigger infinite" than Nats set.
The main question:

How to determine if one can write a total, terminating Haskell function given a type?

(a -> b) -> (b -> c) -> (a -> c) and (a -> c) -> ((a, b) -> c) maybe you can provide one.
But what about:
(a -> b -> c -> d -> e) -> (b -> c) -> (a -> c) -> (d -> e)

I just can say for sure that you cannot guarantee that you will find at least one for all the combinations of all the types at least one. But how to is very well answered by @Jon Purdy


text:
Q: I am getting SFHFKeychainUtilsErrorDomain error - 25299 I am trying to store the values into keychain by using SFHFKeyChain. But i am getting below error (This error is pop only in iOS 8.1 ).

can any one know about this error. Why this error is showing. Please help me.
Thanks in advance.


text:
Q: How to correctly associate the relationship between lessons, roles and teachers(postgres)? I am trying to set up the database model for lessons(session) and teachers(user), and I have the following sql right now, which assumes lessons and teachers in a many-to-many relationship:
DROP TABLE IF EXISTS "user";
CREATE TABLE "user" (
    id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
    name VARCHAR(255) NOT NULL,
    email CITEXT UNIQUE CONSTRAINT email_length CHECK (char_length(email) <= 254),
    password VARCHAR(255) NOT NULL
);

DROP TABLE IF EXISTS "session";
CREATE TABLE "session" (
    id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
    name VARCHAR(255),
    event_id INT NOT NULL
);

DROP TABLE IF EXISTS "session_user";
CREATE TABLE "session_user" (
    id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
    user_id INT NOT NULL REFERENCES "user"(id),
    session_id INT NOT NULL REFERENCES "session"(id),
    UNIQUE (user_id, session_id)
);

Now I need to implement a new functionality of role, which every user may have different role in a session. For example, in session A user X is the host and user Y is the assistant, whereas in session B user X is the assistant and user Y is the host. How can I model this relationship?
EDIT
Is the structure the right way to do what I want?


text:
Q: How does the CRM Email router set the RegardingObjectId on incoming emails We have a system setup where complaints from a website form are emailed to an address and subsequently picked up by the email router and placed in a queue. Users then create a case from these emails (custom code create the case and populates it based on the email content and the queue it arrived into)
Some of the emails are coming in and the regarding object is set to an existing case even though the email and the case are not related. My guess is that this is something to do with the fact that the emails are coming into the queue from the same web address (complaints@abc.com)
Can somebody explain to me the criteria the email router uses for setting the regarding object of an incoming email
Thanks,
Neil

A: Looks like you are another "victim" of a feature called Smart Matching. For info on what that is and how to disable it, look here.


text:
Q: None of my React Components are loading inside of my html.erb files I have this error in my browser dev tools "Calling Element.createShadowRoot() for an element which already hosts a shadow root is deprecated," which I suspect may be the issue. I also suspect that installing babel may have messed up my react-rendering, or possible the fact that I removed all my npm packages. Inside of the body tags on the browser, I have

, but nothing shows up on the page. I'm using react-rails gem.
Inside my root html.erb file
< %= react_component ('Home') % >
My Home Component
class Home extends React.Component {
render() {
return()

  Hello

}
Inside my application.js
//= require jquery
//= require jquery_ujs
//= require react
//= require react_ujs
//= require components
//= require_tree .
Inside my components.js
//= require_tree ./components

A: your return statement isn't correct, try:
  render() {
    return (

Hello

    )
  }

Don't forget to delete the space in your html tags right after "<".

A: There is problem in your render code. It must look like this :-
return ( the tags and html part will come here );

So after correction it will look like this :- (dont forget ; too)
render()
{
        return(

 Hello

        );
}


text:
Q: Issues with creating a stream in Python I'm attempting to create a stream for the .docx file returned from the user upload. I tried using .seek(0), .read(), and .stream() but each returned an error. Is there something I am missing? The .docx is sucessfully returned as a <class 'werkzeug.datastructures.FileStorage'> object but I'm having trouble making it into a stream for the aspose.words module to read.
@app.route('/home', methods=['GET','POST'])
def home():
    if request.method == 'POST':
        document = request.files['document']
        stream = io.FileIO(document.read())
        doc = aw.Document(stream)

A: You should use either io.BytesIO(document.read()) or io.BufferedReader(document) instead of io.FileIO(document.read()).
io.FileIO expects file name as an input parameter.


text:
Q: Using ZonedDateTime with datetimeoffset in SQLServer I have an application that uses a SQLServer database with datetimeoffset columns. Preferably, I would like to use ZonedDateTime as my JPA entity object type like so:
@Column(name = "CreateTimestamp", nullable = false)
ZonedDateTime createTimestamp;

However, the timezone is not being properly saved. No matter what I set the ZoneId to in the ZonedDateTime, the value will always be in GMT in the database.
Looking at Microsoft's JDBC mapping diagram, the recommended class to use is microsoft.sql.DateTimeOffset which is not what I would prefer.
I've explored using a @Converter to map between the two, but having to provide special knowledge like this seems like a red flag that I'm doing something wrong - especially since I need this to work inside of an integration test using H2.
What is the best way to use datetimeoffset and ZonedDateTime in a vendor agnostic way?

A: A bit of a gotchya here.
The data time ZoneDateTime contains more information than an OffsetDateTime.
The zone.
Mind you, a zone is not the same as an offset. It is more.
Two zones could, at a given moment, have the same offset, but months later, one zone "springs forward" the other zone does not.
Or, they spring forward on different days.
In converting a string from an OffsetDateTime to a ZoneDateTime, you are introducing a zone where one did not exist before.

A: I hate to answer my own question but I want to make sure the solution is documented.
The solution is to use a @Converter to transform a ZonedDateTime into a String. Hibernate will pass this down to SQLServer as a VARCHAR and the database itself will implicitly convert the value into a datetimeoffset - the same way it converts a hardcoded date when you execute a standalone query.
The following converter worked for my circumstances:
@Converter(autoApply = true)
public class ZonedDateTimeConverter implements AttributeConverter<ZonedDateTime, String>
{
    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSSSSSS xxx";

    @Override
    public String convertToDatabaseColumn(ZonedDateTime zonedDateTime)
    {
        return DateTimeFormatter.ofPattern(DATE_FORMAT).format(zonedDateTime);
    }

    @Override
    public ZonedDateTime convertToEntityAttribute(String dateAsString)
    {
        return ZonedDateTime.parse(dateAsString, DateTimeFormatter.ofPattern(DATE_FORMAT));
    }
}

Additionally, this also works in H2 so it can be used inside of an integration test without having to do any vendor-specific logic.


text:
Q: Show that f(M) is a compact space I am studying set theory and I have a problem I would like help with. I have tried setting it up but have not progressed with it. I usually progress and that's why it bothers me.
So here goes:
Show that if $M$ and $N$ are metric spaces, $M$ is compact and $f: M \rightarrow N$ is a continuous function that $f(M)$ is a compact subspace of $N$.
The definition of compactness is if the space satisfies either (hence both) equivalent conditions that:
a. Every sequence has a convergent subsequence.
b. Every infinite set has a limit point.
So I guess that $f: M \rightarrow N$ carries all of the points to $N$, and so $f(M) ⊆ N$ also contains these points (especially the limit points). And therefore it is compact. But surely this is completely wrong.
Any help is appreciated.
J.

A: Any sequence in $f(M)$ can be written as $f(x_1),f(x_2),\ldots$.
By compactness of $M$, the sequence $x_1,x_2,\ldots$ has a convergence subsequence $x_{k_1},x_{k_2},\ldots$. By continuity of $f$, the sequence $f(x_{k_1}),f(x_{k_2}),\ldots$ also converges.

A: This works even in a more general setting, using the most general definitions of continuity and compactness. Concretely:

*

*$f$ is continuous if and only if $f^{-1}(V)$ is open for every open set $V$

*$M$ is compact if every open cover admits a finite sub-cover.
If now you are given an open cover of $f(M)$, the preimages will form an open cover of $M$, and thus have a finite sub-cover. Then you can push the finite sub-cover to $f(M)$ to obtain a finite sub-cover of the original cover.

A: Let's stick to definition a.  Our proof should then be structured as follows: it should start with

Let $(y_n)_{n=1}^\infty$ be a sequence in $f(M)$.

We should somehow end this proof by demonstrating that $(y_n)$ has a convergent subsequence.  Here's what my proof would look like (I'll leave it to you to fill in the blanks):

Let $(y_n)_{n=1}^\infty$ be a sequence in $f(M)$.  By definition of $f(M)$, there is a sequence $(x_n)_{n=1}^\infty$ such that $f(x_n) = y_n$ for each $n \in \Bbb N$.  $(x_n)$ has a convergent sequence $(x_{n_k})_{k=1}^\infty$ (why is this true?)  We can then conclude that the sequence $(y_{n_k}) = (f(x_{n_k}))$ is convergent (why?).  Note that this is a subsequence of $(y_n)$.  Thus, an arbitrary sequence $(y_n) \subset f(M)$  must have a convergent subsequence.

A: Given a sequence of points $y_i\in f(M)$, it suffices to show it has a convergent subsequence. For each $i$, choose a point $x_i \in M$ with $f(x_i)=y_i$; this forms a sequence in $M$. Since $M$ is compact, there is a convergent subsequence $x_{i_k}\to x\in M$. By continuity, $y_{i_k}=f(x_{i_k})\to f(x)\in f(M)$.


text:
Q: Not using index even if it exists I have next simple query: SELECT * FROM table LEFT JOIN table2 ON table2.id=table.id WHERE table.id=1 having an index in table.id and table2.id
When I check how it works with EXPLAIN it shows that it's not using the index, and going through ALL the rows. I check the same with another another exact table with the same structure, and in this case index is being used.
Even more strange, if I have another more complex query like
SELECT * FROM table LEFT JOIN table2 ON table2.id=table.id LEFT JOIN table3 ON table3.id=table.id WHERE table.id=1 the index works perfect in both tables, even in the problematic table2
I'm completely sure that is my mistake, but I really don't know why sometimes index is being used, and sometimes not... Anyone expert in MySQL who can help me? Thank you very much!


text:
Q: Why are my DIVs clearing left? I don't usually post a link to my site when asking questions, though I don't see another way around it. I apologize in advance.
I'm having difficulties with a specific page. The page consists of Team Members, where each member is its own DIV (also each team member is coincidentally a separate post in Wordpress).
For some reason, the DIVs wrapping each post are clearing left, but no clearing attributes are assigned!
The page is located here: http://engineercreativity.com/samples/comsense/?page_id=15
Please, if you can help, I'd love to hear any input.
Thanks a lot!
Amit

A: Divs are floating on horizontal axis and not vertically, What you are essentially looking for is a Masonry Plugin, its for jquery and should easily solve your problem.
http://desandro.com/resources/jquery-masonry/
edit:
your divs are not clearing on left, please see the computed layout

the whitespace is not because of divs clearing left, the whitespace is because of line height. When you are having two floating elements in a row, then the row will take height equal to the bigger element, so essentially each row will have white space below the smaller div. This is similar to a HTML Table.

A: Akinator's fix didn't work for me in FF on Win XP.  If you change your float on the "team-member" class to float: left it will fix it.  It is being caused by your static image being float left and the rest of the divs around it being float right.

A: If I understood your question correctly, you have a margin-bottom of 15px in the class .team-member, this gives and extra white space.
It should be set to 0 (or not set)
Is this what you ment?


text:
Q: Print Terminal Output Python Is there a way to assign the terminal output to a varibale then print it to the screen, using os.popen()
For example:
import os
output = os.popen("dir")
print(output)

Is this possible?

A: Yes it is possible but you should do it like this:
import os
output = os.popen("dir")
preprocessed = output.read()
print(preprocessed)


text:
Q: Using WhooshAlchemy with joined table inheritance I currently have something along the lines of this (taken from the SQLAlchemy documentation):
class Employee(Base):
    __tablename__ = 'employee'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    type = Column(String(50))

    __mapper_args__ = {
        'polymorphic_identity':'employee',
        'polymorphic_on':type
    }

class Engineer(Employee):
    __tablename__ = 'engineer'
    id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
    engineer_name = Column(String(30))

    __mapper_args__ = {
        'polymorphic_identity':'engineer',
    }

class Manager(Employee):
    __tablename__ = 'manager'
    id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
    manager_name = Column(String(30))

    __mapper_args__ = {
        'polymorphic_identity':'manager',
    }

Using WhooshAlchemy, I'd like to make the name column searchable, but also engineer_name and manager_name for the Engineer and Manager class respectively.
I've tried putting a separate __searchable__ list containing their columns into each class, but that gives me the following error:
whoosh.fields.UnknownFieldError: No field named 'name' in <Schema: ['id', 'engineer_name']>

I've also tried putting a __searchable__ list into each one that only contains the columns defined on that specific class, but that gives me no results at all when I use whoosh_search on a query, despite having valid search terms that should return at least 1 result.
What's the easiest way to do this?

A: You have to explicitly define a schema that can handle all of them.
You would override the searchable fields on the inherited classes.
class Employee(Base):
    __tablename__ = 'employee'
    __searchable__ = ['name']
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    type = Column(String(50))

    __mapper_args__ = {
        'polymorphic_identity':'employee',
        'polymorphic_on':type
    }

class Engineer(Employee):
    __tablename__ = 'engineer'
    __searchable__ = ['name', 'engineer_name']
    id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
    engineer_name = Column(String(30))

    __mapper_args__ = {
        'polymorphic_identity':'engineer',
    }

class Manager(Employee):
    __tablename__ = 'manager'
    __searchable__ = ['name', 'manager_name ']
    id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
    manager_name = Column(String(30))

    __mapper_args__ = {
        'polymorphic_identity':'manager',
    }

Then when you build your index:
from whooshalchemy import IndexService
from whoosh.fields import Schema, TEXT

# However your app initializes it
index_service = IndexService(config=app.config, session=db.session)

my_schema = Schema(name=TEXT, engineer_name=TEXT, manager_name=TEXT)
index = index_service.index_for_model_class(model)

with index.writer() as writer:

    for engineer in Engineer.query.all():
        index_attrs = {}
        for field in Engineer.__searchable__:
            index_attrs[field] = str(getattr(engineer, field))

        index_attrs["id"] = engineer.id

        writer.add_document(**index_attrs)

    for manager in Manager.query.all():
        index_attrs = {}
        for field in Manager.__searchable__:
            index_attrs[field] = str(getattr(manager, field))

        index_attrs["id"] = manager.id

        writer.add_document(**index_attrs)

And later when searching:
engineer_search_results = Engineer.search_query("SomeText").all()
manager_search_results = Manager.search_query("SomeText").all()

A: the flask-whooshalchemy dosen't
if you use flask too, you can try my fork of flask_whooshalchemy named Flask-WhooshAlchemyPlus which can index inherited model
you can add searchable of its own field names to each model
I'll just paste the code here
def _get_whoosh_schema_and_primary_key(model, analyzer):
    schema = {}
    primary = None
    searchable = set(model.__searchable__)

    for field in model.__table__.columns:
        if field.primary_key:
            schema[field.name] = whoosh.fields.ID(stored=True, unique=True)
            primary = field.name

        if field.name in searchable and isinstance(field.type,
                                               (sqlalchemy.types.Text,
                                                sqlalchemy.types.String,
                                                sqlalchemy.types.Unicode)):
            schema[field.name] = whoosh.fields.TEXT(
                analyzer=analyzer, vector=True)

    for parent_class in model.__bases__:
        if hasattr(parent_class, "_sa_class_manager"):
            if parent_class.__searchable__:
                for i in set(parent_class.__searchable__):
                    if hasattr(parent_class, i):
                        schema[i] = whoosh.fields.TEXT(
                            analyzer=analyzer, vector=True)

    return Schema(**schema), primary


text:
Q: Hide all rows that do not match driverNo.Text I want to hide all rows in datagrid which do not match the text in driverNo.Text, but when driverNo.Text is null, I'd like all the rows in datagrid to appear. How would I accomplish this?
    private void driverNo_KeyUp(object sender, KeyEventArgs e)
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.Cells[1].Value.ToString() == driverNo.Text)
            {

            }
            else if (row.Cells[1].Value.ToString() == null)
            {

            }
        }
    }

A: This should solve the problem:
CurrencyManager manager = (CurrencyManager)BindingContext[dataGridView1.DataSource];
manager.SuspendBinding();
bool shouldNotFilter = string.IsNullOrEmpty(driverNo.Text);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (shouldNotFilter)
    {
        row.Visible = true;
    }
    else
    {
        if (!string.Equals(row.Cells[1].Value.ToString(), driverNo.Text, StringComparison.OrdinalIgnoreCase))
        {
            row.Visible = false;
        }
        else
        {
            row.Visible = true;
        }
    }
}
manager.ResumeBinding();

This approach is straight forward but slow, I'd suggest you take a look at DataView and its RowFilter property. Here is a good example.

A: This may not be exactly what you need, but something along these lines?
private void driverNo_KeyUp(object sender, KeyEventArgs e)
{
    // Set all rows.Visible = false in design
    if (driverNo.Text = "")
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            row.Visible = true;
        }
    }
    else
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.Cells[1].Value.ToString() == driverNo.Text)
            {
                row.Visible = true;
            }
        }
    }
}

This will make all rows visible if the driverNo.Text is null and only show the rows with what is contained in driverNo.Text otherwise.
NOTE: The rows need to not be visible to start, or you can make them visible to start and just change the if statement to != driverNo.Text and set to false


text:
Q: how to check if a string of a number has 10 characters in php I am struggeling at implementing a check on a textbox.
I want to check if the phone number has a length of 10 characters, contains my country base number and if it is actually a numerical value.
i only know how to check if it is a number.
                    if(ctype_digit($telefon) && ctype_digit($telefon)=="10"){
                          ...

                    } else {
                        echo "Invalid phone number";
                    }

A: Using PHP's 'strlen($string)' function would count every character including any format notations
https://www.w3schools.com/PHP/func_string_strlen.asp


text:
Q: What does a positive or a negative TD-Error mean (in DQN)? When training a DQN, for example on board games, the sign of the TD-error varies. Sometimes, it's:

*

*always positive

*always negative

*varying during the training of the algorithm

For example, on the graph below, we see this third behavior:

Does this mean something? E.g can we give this an interpretation that relates to how the agent is behaving/learning? (for example interpretations about the "surprise" of the network since the td-error is the Bellman equation approximation error)


text:
Q: C# TCP Client listening for data I would like to connect to a specific barcode reader at my work but currently I'm facing some problems to understand how TCP stream reading works with C#.
I've looked for many code samples on stackoverflow and as I can see, people oftenly open a connection, send a command and then ask for the reply.
The point is, the barcode reader just accept a TCP connection and then send the data with my data.
I would like find the most efficient way to use TcpClient or NetworkStream to read in a continuous way the data. I mean, I would like to listen for the data when it's incoming but also process many other things at the same time I'm listening.
I was wonderning if simple TCP libraries exists like a one with a Connect function, and an event firing when you receive data (with a delimiter or with a length).
Thanks

A: I finally found a simple TCP library called SimpleTCP. I'm able to connect to my network barcode reader with the following line of code: g_Client.Connect(ip, port);
Then there is an event available called DataReceived (g_Client.DataReceived += l_Client_DataReceived;) which allow me to do exactly what I want.
This library also gives access to the TcpClient it's using and I'm currently searching for the possibility to see the special characters such as < STX >(currently returning me a special char in ASCII) but I will have to do another thread for this I think.

A: TCP doesn't sound right, but if it is it might be acting as a http server.If it is then you'd use a HttpClient. If it is just TCP, you would do something like:Async Client Socket


text:
Q: Attempting to delete my post So I have this destroy controller:
def destroy
    Post.find(params[:id]).destroy
    flash[:success] = "Post Deleted."
    redirect_to users_url
  end

And this view:
<% @posts.each do |i| %>

This post was created at: <%= i.created_at %>

Contents of the post: <%= i.content %>
<%= link_to "Delete this post", @post, method: :delete, class: "black", data: { confirm: "You sure?" } %>

<% end %>
<% end %>

Now when I make a delete, it just redirects me to the page i made it to in the controller, and thats it. In the server logs i get this:
Started DELETE "/users/17" for 127.0.0.1 at 2013-12-16 22:49:31 +0200
Processing by UsersController#destroy as HTML
  Parameters: {"authenticity_token"=>"iT08NreZv83WtImK6V9/jXZOpgtzwSLjlxB7T/wn0E4=", "id"=>"17"}
  User Load (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."remember_token" = '473b76458ca425d9bb927550e7a11eb292393d84' LIMIT 1
Redirected to http://localhost:3000/
Filter chain halted as :admin_user rendered or redirected
Completed 302 Found in 2ms (ActiveRecord: 0.0ms)

Started GET "/" for 127.0.0.1 at 2013-12-16 22:49:31 +0200
Processing by FormController#home as HTML
  Rendered form/home.html.erb within layouts/application (0.0ms)
  User Load (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."remember_token" = '473b76458ca425d9bb927550e7a11eb292393d84' LIMIT 1
  Rendered layouts/_menu.html.erb (2.0ms)
  Rendered layouts/_footer.html.erb (0.0ms)
Completed 200 OK in 9ms (Views: 9.0ms | ActiveRecord: 0.0ms)

What am I missing in here?

A: You have a before filter that is checking if your current user is an admin_user. Your logs show that your current user isn't so you are being redirected before you hit the destroy action.
Also you should send the flash message with the redirect. See this post for more info
 redirect_to users_url, success: "Post Deleted."


text:
Q: Null data retrieved when using Listener for Single Value in Firebase and Geofire My data is currently structured as:
Users •
      userId -
           eyeColour: Blue

userId •
    - geoLocation stuff

I'm trying to load data associated with the geolocation node. So say if user A sets location and user B is near user A's set location, he/she can see the attributes of user A (eyeColour). so onKeyEntered(), I'm trying to load the user's information.
Every user has their own unique id. When a user sets a location, the child name will be their unique id. (geofire.setLocation(myUniqueId, myLocation);)
So what I've tried before was using the addListenerForSingleValueEvent since I only need to load the information once.
mDatabase.child("users").child(key).addListenerForSingleValueEvent(
                    new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            // Get user value
                            String test = dataSnapshot.getValue(String.class);
                            // ...
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });

I thought this would load the profile/information of the user. But instead, the String 'test' returns null. What am I doing wrong? Should I change my listener?


text:
Q: Media Stream and Capture API for creating mp4 from canvas elements I have a serverless Vue SPA which creates GIF files completely client side. I wish to use the Media Stream and Capture API to create an mp4 instead. I am not sure how to setup the Media Stream ,along with frames per second and output filename, to accept my canvas elements one by one and how to export the resulting viedo file using createObjectURL. I currently addFrame once a map is rendered and a canvas element is drawn, but I am not sure how to connect this to the ondataavailable of a MediaRecorder. Can someone explain to me how this works please?
async createGIFHandler ( layer , addAllTitles , quality , delay , range ) {
    ...
    var tempGIF = new GIF({
        workers: 4,
        quality: quality,
        height: this.mapHeight + this.infoCanvas.height,
        width: this.mapWidth,
        workerScript: 'gif.worker.js'
    });
    let progressCounter = 1;
    for ( let i = range[0] ; i < range[1] ; i++, progressCounter++ ) {
        this.setDateTime( driver , driverDA[i] );
        for ( let j = 0 ; j < visibleLayers.length ; j++ ) {
            if ( visibleLayers[j].get('layerName') !== layer.Name  ) {
                var tempDA = visibleLayers[j].get('layerDateArray');
                for ( let k = 0 ; k < tempDA.length ; k++ ) {
                    if ( driverDA[i].getTime() === tempDA[k].getTime() ) {
                        this.setDateTime( visibleLayers[j] , tempDA[k] );
                    }
                }
            }
        }
        await new Promise(resolve => this.map.once('rendercomplete', resolve));
        await this.composeCanvas( tempGIF , driverDA[i] , visibleLayers , delay , widths )
        this.$store.dispatch('Layers/setGIFPercent', Math.round(((progressCounter / gifLength) * 100)))
    }

    tempGIF.on('finished', (blob) => {
        const tempURL = URL.createObjectURL( blob )
        this.$store.dispatch( 'Layers/setGIFURL' , tempURL )
        console.log('GIF Finished');
    });
    tempGIF.render();
},
async composeCanvas( gif , timeStep , visibleLayers , delayInput , widths ) {
    const mapCnv = this.getMapCanvas();
    await this.updateInfoCanvas( timeStep , widths )
    const composedCnv = await this.stitchCanvases( mapCnv , visibleLayers.length );
    await new Promise((resolve) => {
        gif.addFrame(composedCnv, { delay: delayInput });
        resolve();
    })
},


text:
Q: Set difference of an open set and a closed set Suppose $A$ is an open set and $B$ a closed set. Is it necessarily true that $A \backslash  B$ open? I have thought about a few counter examples but could not come up with any, so I am inclined to say it is true. For example, $\mathbb{R} \backslash \phi$ is both open and closed but this does not impose any problem.
If $A \subset B$ then $A \backslash B = \phi$ which is open. If $A$ and $B$ do not intersect each other then $A \backslash B = A$ which is of course open. The only edge case is when $B \subset A$, which again I think should make $A \backslash  B$ open. Am I right?

A: ANSEWR ACCORDING COMMENT:
Take $A=(-2,2)$ and $C_n=[-1+1/n,1-1/n]$.
Then $B=\bigcup C_n=(-1,1)$ and $A\setminus B=(-2,-1]\cup[1,2)$.
FIRST ANSWER:
You're not right. You missed the genereal case when $A\cap B\ne\varnothing$ but neither $A\subset B$ nor $B\subset A$.
A better approach:
Recall that $A\setminus B=A\cap B^c$ and take into account that intersection of finite number of open set is always open.


text:
Q: Advice needed about Facebook's dialog feed, sharer and like buttons I'm totally confused about Facebook's dialog feed, sharer and like buttons (I'm a noob to Facebook and its jargon)
On my website, I would like the following

*

*to have a button at the top of the page where people can share my site to their wall

*to have a button on the the page where users can share their main homepage on my site to their wall

*to have a button where users can share individual items of theirs (events) to their wall

I've read the sharer button is being phased out in preference to the Like button but I see a problem with the Like button. I think something can only be liked once. A user's event might want to be shared several times (to remind their Fb users of the event)
I've seen the BBC use the dialog feed button to post items to a wall and that looks okay but I couldn't get the popup to work.
my requirements are to have different links for each of the three scenarios I've mentioned, with a different description for each scenario but sharing my site's logo.
I've read so much that I'm now totally confused plus all the APIs that Fb has. It's just crazy (or that's how it seems to me)
If someone could help clear the fog with sound recommendations and some sample code for each button, I would be very grateful.
Thank you.
.

A: For what your talking about you would want to use the feed dialog. It's flexible enough that you just need to setup your links and pass in some variables.  I don't see the feed dialog being phased out as you mentioned they serve different purposes.  I think they push the like as it's easier to use and not as likely to be abused.
You'll need to register an application and make sure to initialize the Facebook javascript SDK before you call the below function.  If you're having issues with your popup it's probably due to the fact your FB init process is having issues.  I've added a second function I use to init Facebook.  Both functions use jQuery so you might have to modify if you don't use it.
You can create a pretty generic function like this:
$.shareMe = function(myName, myLink, myPicture, myCaption ) {

FB.ui(
  {
    method: 'feed',
    name: myName,
    link: myLink,
    picture: myPicture,
    caption: myCaption

  },
  function(response) {
    if (response && response.post_id) {
      alert('Thanks for Sharing.');
    } else {
      alert('Post was not published.');
    }
  }
);

}

and for Facebook initialization:
$.initFacebook = function(options){

$('#fb-root').remove();

$('body').append('

');

var settings = {

  'appId'       :   null,
  'callback'    :   null,
  'channelUrl'  :   null,
  'status'      :   true,
  'cookie'      :   true,
  'xfbml'       :   true

};

if ( options ) {
    $.extend( settings, options );
}

if( typeof( xc_app_id ) == 'undefined' ) { window.xc_app_id = settings.appId; }

window.fbAsyncInit = function() {

    if(settings.channelUrl==null) {

        FB.init({appId: settings.appId, status: settings.status, cookie: settings.cookie, xfbml: settings.xfbml, oauth: true, authResponse: true });

    } else {

        settings.channelUrl=location.protocol+'//'+settings.channelUrl;

        FB.init({appId: settings.appId, status: settings.status, cookie: settings.cookie, xfbml: settings.xfbml, oauth: true, authResponse: true, channelUrl: settings.channelUrl });
    }

    if(typeof settings.callback == 'function'){ settings.callback.call(this); }

};

(function() {
var e = document.createElement('script');
e.async = true;
e.src = '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());

}

and to call it you just use $.initFacebook({appId,'yourAppId'}); There are other options there you can lookup in the docs if you need them.


text:
Q: Cocoa binding with @sum value of child I'm trying to have a table column to display the sum of child values using the IB. I'm not sure if this is doable though.
So I have my Core Data bind to a table and a column of "total sales amount" that should be a total of the sales of the parent object.
I'm trying to do it like this:
"departments.@distinctUnionOfSets.sales.@sum.amount" in the "Model Key Path" of the Table Column Binding in IB.
Is there any example or tutorial on how to do this.


text:
Q: Best Practices for 3 Tier Development Does anyone know of any documentation by MS or someone else that lays out the best practices for developing a 3 tier architecture in ASP.NET.  I am in the process of trying to convince my boss that the current architecture needs rethought and reworked to provide a flexible and reusable system.  I have found a lot of generic documentation that tells you at a high level the best practices as far as how to do this but little showing how you actually implement them.  I need to show him documentation as far as the advantages to using business objects versus data sets and things to that level of detail.  Any help would be appreciated.

A: Microsoft's Patterns & Practices group has published various whitepapers and documents in the form of "architectural guidance" that can be helpful. They recently published a number of "pocket guides" as well. Even if you don't follow them to the letter, they're likely to be a great starting point for discussing your particular needs.
That they come from Microsoft may also help add credibility in the discussion with your boss. There's one on Web Application Architecture, in particular, that sounds like it may be relevant.

A: I would highly recommend looking into ASP.NET MVC.  It's a far better option for n-tier appliactions as it allows for a greater degree of Seperation Of Concerns.  This leads to a more testable and maintanable application that can be achieved with ASP.NET


text:
Q: What happens to docker images pulled / run in gitlab CI? I'm experiencing strange problem with gitlab CI build.
My script looks like that:
 - docker pull myrepo:myimage
 - docker tag myrepo:myimage myimage
 - docker run --name myimage myimage

It was working for a few times, but afterwards I've started getting errors:

docker: Error response from daemon: Conflict. The container name
  "/myimage" is already in use by container ....

I've logged on the particular machine where that step was executed, and docker ps -a has shown, that the image was left on the build machine...
I've expected that gitlab CI build steps are fully separated from external environment via running them in docker containers... so that a build would not 'spoil' the environment for other builds. So I've expected all images and containers created by CI build to simply perish... which is not the case...
Is my gitlab somehow misconfigured, or this is expected behaviour, that docker images / containers exists in context of host machine and not within docker image?
In my build, I use image docker:latest

A: No, your Gitlab is not misconfigured. Gitlab does clean its runners and executors (the docker image you run your commands in).
Since you are using DinD (Docker-in-Docker) any container you start or build is actually build on the same host and runs besides your job executor container, not 'inside' it.
Therefore you should clean up, Gitlab has no knowledge of what you do inside of your job so its not responsible for it.
I run various pipelines with the same situation you described so some suggestions:
 job:
   script:
   - docker pull myrepo:myimage
   - docker tag myrepo:myimage myimage
   - docker run --name myimage myimage
   after_script:
   # Stop any running containers, if they are not running anymore (since its not a run -d), ignore errors about that.
   - docker rm -f myrepo:myimage myimage || true
   # Remove pulled images
   - docker rmi -f myrepo:myimage image

Also (and I don't know your exact job of course) this could be shorter:
 job:
   script:
   # Only pull if you want to 'refresh' any images that would be left behind
   - docker pull myrepo:myimage
   - docker run --name myimage myrepo:myimage
   after_script:
   # Stop any running containers, if they are not running anymore (since its not a run -d), ignore errors about that.
   - docker rm -f myrepo:myimage || true
   # Remove pulled image
   - docker rmi -f myrepo:myimage

A: The problem was, /var/run/docker.sock was mapped as volume, which caused all docker commands to be invoked on host, not inside image. It's not a misconfiguration per se, but the alternative is to use dind service: https://docs.gitlab.com/ce/ci/docker/using_docker_build.html#use-docker-in-docker-executor
It required 3 things to be done:

*

*Add following section to gitlab ci config:

services:
 - docker:dind

*Define variable DOCKER_DRIVER: overlay2 either in ci config, or globally in config.toml

*Load kernel module overlay (/etc/modules)


text:
Q: SceneKit server-client non-rendering scene I'm working on a server-client based networked game in Scene Kit. Since the server and the client essentially have duplicate copies of the game, I'm currently loading the same scenes into an SCNScene on the client side and SCNScene on the server. However, I have yet to find a way to actually run the physics simulation on the server's copy of the SCNScene without rendering it in an SCNView. How can I set up a (custom SCNRenderer?) that drives the simulation without actually rasterizing any frames?

A: Inherit the SCNRenderer, overrides all methods {void}


text:
Q: C++: using std::wstring in API function I'm using the SHGetSpecialFolderLocation API function. My application is set to "Use Unicode Character Set".
Here's what I have so far:
int main ( int, char ** )
{
    LPITEMIDLIST pidl;
    HRESULT hr = SHGetSpecialFolderLocation(NULL, CSIDL_PERSONAL, &pidl);

    /* Confused at this point */
    wstring wstrPath;

    wstrPath.resize ( _MAX_PATH );
    BOOL f = SHGetPathFromIDList(pidl, wstrPath.c_str () );
    /* End confusion */

The error I'm getting is:
error C2664: 'SHGetPathFromIDListW' : cannot convert parameter 2 from 'const wchar_t *' to 'LPWSTR'

Can someone help? What's the proper C++ way to do this?
Thanks!

A: The second parameter is an out parameter, so you can't just pass c_str (which is const) directly.  It would probably be simplest just to do:
wchar_t wstrPath[MAX_PATH];
BOOL f = SHGetPathFromIDList(pidl, wstrPath);

MAX_PATH is currently 260 characters.

A: std::basic_string::c_str() returns a constant buffer to it's memory. If you want to modify the string, you'd have to do something like this:
wstring wstrPath;
wstrPath.resize( MAX_PATH );
BOOL f = SHGetPathFromIDList(pidl, &wstrPath[0]);
wstrPath.erase(
   std::find(wstrPath.begin(), wstrPath.end(), L'\0'), wstrPath.end()
); //Throw away unused buffer space

EDIT: This should also work if you're not afraid of C libraries (though I've not tested it like I've tested the implementation above):
wstring wstrPath;
wstrPath.resize( MAX_PATH );
BOOL f = SHGetPathFromIDList(pidl, &wstrPath[0]);
wstrPath.resize(wcslen(wstrPath.c_str()));

A: wstring::c_str() returns const wchar_t* and is read only. LPWSTR is not a const type, and that parameter is an out parameter. You will need to allocate the buffer yourself. You could do something like this:
wchar_t buf[MAX_PATH] = {0};
BOOL f = SHGetPathFromIDList( pidl, buf );
wstring wstrPath = buf;

A: You can get address of 1st array item in basic_string as pointer to writable string data. Although C++ standard does not guarantee that this block of memory must be continuous this is safe in all known implementations (How bad is code using std::basic_string as a contiguous buffer).
std::wstring path(_MAX_PATH, L'\0');
BOOL f = SHGetPathFromIDList(pidl, &path[0]);

A: wstring::c_str() does not let you modify its internal buffer in this way. Your easiest workaround is to create a wchar_t buffer yourself, and the pass that to the wstring constructor:
wchar_t buf[MAX_PATH];
BOOL f = SHGetPathFromIDList(pidl, buf );
wstring wstrPath(buf);


text:
Q: QComboBox display default I have created a QComboBox using the following:
Drop = QtGui.QComboBox()
[Drop.addItem(i) for i in [cat,dog,mouse, llama]]

I want the QComboBox to display 'mouse' instead of 'cat' when I start the GUI without changing the order in the list. 'mouse' should be my default option and I want my user to know that.

A: The following line does the trick:
Drop.setCurrentIndex(2)


text:
Q: Why is ASP not finding anything in my database? Initially my problem was that my posts were duplicating. I believe this was because I didn't link my tables in the SQL statement. Now that I have done that I am getting a "No Data Found" printed after my if info.eof statement.
I'm sure that there is information in the database as I have checked manually, however no success.
Here is my code:
<% option explicit %>
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="normalize.css">

<%

    dim sql, info

'                               0                 1      2        3         4                5
 SQL = "select projectName, UserName, Category, Created, url, Projectstable.description "&_
        "from ProjectsTable, PictureTable, Usertable, CategoryTable "&_
        "where Projectstable.ID=PictureTable.projectNum AND "&_
        "categoryNum=CategoryTable.ID AND "&_
        "ProjectsTable.userNum=Usertable.ID AND "&_
        "UserTable.ID=PictureTable.userNum "&_
            "order by Created"

set info=conn.execute(SQL)

  if info.eof then
    response.write "
No Data Found
"
  else

    do
      response.write "
" & info(0) & "
 By: " & info(1) & " Posted in: " & info(2) & " Created on: " & info(3) & "
" &_
                     "" &_
                     "
" & info(5) & "
"

      info.movenext
    loop until info.eof
  end if

  conn.close

%>

A: I have rewritten your query using ANSI 92 explicit join syntax rather than the ANSI 89 version you have used (which as the names suggest was replaced over 20 years ago with explicit joins):
SELECT  projectName, UserName, Category, Created, url, Projectstable.description
FROM    ProjectsTable
        INNER JOIN PictureTable
            ON Projectstable.ID = PictureTable.projectNum
        INNER JOIN Usertable
            ON UserTable.ID = PictureTable.userNum
            AND ProjectsTable.userNum = Usertable.ID
        INNER JOIN CategoryTable
            ON categoryNum = CategoryTable.ID
ORDER BY Created;

Which highlighted to me that you are limiting your results to where the User in the picture table is the same as the user in the project table. Is this intentional?
Do you get the required results if you remove one of the criteria? So either
SELECT  projectName, UserName, Category, Created, url, Projectstable.description
FROM    ProjectsTable
        INNER JOIN PictureTable
            ON Projectstable.ID = PictureTable.projectNum
        INNER JOIN Usertable
            ON UserTable.ID = PictureTable.userNum
            --AND ProjectsTable.userNum = Usertable.ID
        INNER JOIN CategoryTable
            ON categoryNum = CategoryTable.ID
ORDER BY Created;

Or
SELECT  projectName, UserName, Category, Created, url, Projectstable.description
FROM    ProjectsTable
        INNER JOIN PictureTable
            ON Projectstable.ID = PictureTable.projectNum
        INNER JOIN Usertable
            ON ProjectsTable.userNum = Usertable.ID
            --AND UserTable.ID = PictureTable.userNum
        INNER JOIN CategoryTable
            ON categoryNum = CategoryTable.ID
ORDER BY Created;

For further reading on ANSI 89 vs ANSI 92 join syntax Aaron Bertrand has written a great article about it in his bad habits to kick series.

A: The answer was in fact errors in the database itself. More pointedly, it was incorrect linking between tables. The SQL statement might be outdated but it wasn't causing the errors.


text:
Q: Optimizing a Postgres query I have following query
            SELECT
                ca.sfid,
                CASE WHEN p.Name IS NOT NULL THEN p.Name ELSE '' END AS Property,
                CASE WHEN uc.Name IS NOT NULL THEN uc.Name ELSE '' END AS UnitofInterest,
                CASE WHEN fp.Name IS NOT NULL THEN fp.Name ELSE '' END AS FloorplanofInterest,
                CASE WHEN ca.Status IS NOT NULL THEN ca.Status ELSE '' END AS Status,
                CASE WHEN ca.Origin IS NOT NULL THEN ca.Origin ELSE '' END AS Origin,
                CASE
                    WHEN ca.IC_Call_Answered_by_AH__c = 'true' THEN 'Anyone Home'
                    ELSE 'Property'
                END AS AnswerBy,
                CASE WHEN ca.CaseNumber IS NOT NULL THEN ca.CaseNumber ELSE '' END AS CaseNumber,
                CASE WHEN ca.Ad_Source_Type__c IS NOT NULL THEN ca.Ad_Source_Type__c ELSE '' END AS Source,
                CONCAT(c.FirstName,' ',c.LastName) AS contactname,
                CASE WHEN (c.Phone IS NOT NULL OR c.Phone != '' ) THEN c.Phone ELSE '' END AS Phone,
                CASE WHEN c.MobilePhone IS NOT NULL THEN c.MobilePhone ELSE '' END AS Mobile,
                CASE WHEN c.Email IS NOT NULL THEN c.Email ELSE '' END AS Email,
                CASE WHEN c.most_recent_military_pay_grade__c IS NOT NULL THEN c.most_recent_military_pay_grade__c ELSE '' END AS MilitaryPayGrade,

                CASE WHEN ca.Price_Quoted_1__c IS NOT NULL THEN ca.Price_Quoted_1__c ELSE '' END AS "price/termquoted",
                CASE WHEN ca.Move_in_Date__c IS NOT NULL THEN to_char(ca.Move_in_Date__c AT TIME ZONE 'US/Pacific', 'MM/DD/YYYY') ELSE '' END AS MoveinDate,
                CASE WHEN ca.Of_Occupants__c::varchar IS NOT NULL THEN ca.Of_Occupants__c::varchar ELSE '' END AS "#occupants",
                CASE WHEN ca.Bed_Count_Pref__c IS NOT NULL THEN ca.Bed_Count_Pref__c ELSE '' END AS BedCountPref,
                CASE WHEN ca.Bath_Count_Pref__c IS NOT NULL THEN ca.Bath_Count_Pref__c ELSE '' END AS BathCountPref,
                CASE WHEN ca.Pet_Count__c::varchar IS NOT NULL THEN ca.Pet_Count__c::varchar ELSE '' END AS "#pets",
                CASE WHEN ca.Pet_Type__c IS NOT NULL THEN ca.Pet_Type__c ELSE '' END AS PetTypes,
                CASE WHEN ca.Breed__c IS NOT NULL THEN ca.Breed__c ELSE '' END AS Breed,
                CASE WHEN ca.Pet_Name__c IS NOT NULL THEN ca.Pet_Name__c ELSE '' END AS PetName,
                CASE
                    WHEN (ca.Desired_Rent_Start__c IS NOT NULL AND ca.Desired_Rent_Range_End__c IS NOT NULL) THEN CONCAT(ca.Desired_Rent_Start__c,' - ',ca.Desired_Rent_Range_End__c)
                    ELSE ''
                END AS DesiredRentRange,
                CASE WHEN ca.Desired_Lease_length__c::varchar IS NOT NULL THEN ca.Desired_Lease_length__c::varchar ELSE '' END AS DesiredLeaseLength,
                CASE WHEN ca.Reason_for_Moving__c IS NOT NULL THEN ca.Reason_for_Moving__c ELSE '' END AS ReasonforMoving,
                CASE WHEN ca.Notes__c IS NOT NULL THEN ca.Notes__c ELSE '' END AS Notes,
                CASE WHEN ca.Reasons_For_Not_Setting_a_Showing__c IS NOT NULL THEN ca.Reasons_For_Not_Setting_a_Showing__c ELSE '' END AS ReasonforNotSettingShowing,
                CASE WHEN ca.CreatedDate IS NOT NULL THEN to_char(ca.CreatedDate AT TIME ZONE 'US/Pacific', 'MM/DD/YYYY HH:MI AM') ELSE '' END AS "date/timeopened",
                CASE
                    WHEN app.appointment_date__c IS NOT NULL THEN  CONCAT(to_char(app.appointment_date__c AT TIME ZONE 'US/Pacific', 'MM/DD/YYYY'),' ',app.from__c,'-',app.to__c)
                    ELSE ''
                END AS "appointmentdate/time",
                CASE WHEN ca.Yardi_Guest_Card_ID__c IS NOT NULL THEN ca.Yardi_Guest_Card_ID__c ELSE '' END AS PMSGuestCardID,
                rank() OVER (PARTITION BY ca.contactid, ca.property_of_interest__c ORDER BY ca.createddate DESC)
            FROM
                salesforce.Case ca
                INNER JOIN salesforce.Contact c on ca.ContactId = c.sfid AND c.accountId = ca.accountId
                LEFT JOIN salesforce.Appointment__c app ON ca.sfid = app.case__c
                LEFT JOIN salesforce.Property__c p ON p.sfid = ca.Property_of_Interest__c AND p.account__c = ca.accountId
                LEFT JOIN salesforce.Floor_Plan__c fp ON ca.Floor_Plan_of_Interest__c = fp.sfid AND fp.account__c = ca.accountId
                LEFT JOIN salesforce.Unit__c uc ON ca.Unit_of_Interest__c = uc.sfid AND uc.account__c = ca.accountId

            WHERE
        ca.Guest_Card_Status__c = 'Sent via Workflow'
        AND ca.accountId = '001i000000ESO3CAAX'
        AND to_char(to_char(ca.createddate AT TIME ZONE 'UTC' AT TIME ZONE 'US/Pacific','YYYY-MM-DD HH24:MI:SS')::date, 'YYYY-MM-DD') BETWEEN  '2016-06-02' AND '2016-07-02'
        AND to_char(c.Last_Activity__c AT TIME ZONE 'US/Pacific', 'YYYY-MM-DD') BETWEEN  '2016-03-04' AND '2016-07-02'
        AND ( ca.Status IN ( 'Inquiry', 'Showing Set', 'Showing Completed', 'Application Pending', 'Resident' )  )
        AND ( ca.IC_Call_Answered_by_AH__c IN ( 'false', 'true' ) )
        AND ( ca.origin IN ( 'Phone', 'Email', 'Voicemail', 'Chat', 'Walk-In', 'Web' )  OR ca.origin IS NULL OR ca.origin = ''  ) LIMIT 20 OFFSET 0

And following is the query plan for it

We have indexes on following columns:

*

*AccountId

*createddate

*Status

*Origin

Using PostgreSQL.
But query is taking long time to run. Can you please suggest any optimization in it?
Thanks

A: Without knowing much about your data set and being unable to read the screenshot of the query plan, I see a couple easy improvements you can make.
First, your use of the indexed columns accountId, status, and origin columns is fine. However, your usage of the createddate column is flawed. By converting the column to a string and then performing a comparison after it has been converted to a string, you are no longer using the index -- Postgres must perform a full scan and run two costly to_char conversions.
Qualify on your createddate column with a comparison native to the datatype of the column.
For example, if the datatype of createdate is timestamp, then you could qualify on it like this:
AND ca.createdate BETWEEN '2016-06-02'::timestamp AND '2016-07-02'::timestamp
This will use the index and it will perform much better.
Second, make sure that you've created one index that uses all four of the columns you've listed. If you have created four separate indexes for each of those columns, then you are not realizing the full performance gains possible from indexing. An index that uses all four of the columns will allow Postgres to progressively narrow down the result set with each column. If you have four separate indexes, then Postgres can only narrow down the result set with one column.


text:
Q: How to prefill voyager BREAD form with currently logged in user? [SOLVED]
I have a simple listing in my laravel 5.7 project,and used voyager to manage its data.
and i want to make a fully working created_by and last_edit_by BREAD table but still have no idea to get the currently logged in user.
i currently using custom views(resources/views/vendor/voyager) with copy-pasted original codes,but still using original VoyagerBreadController.php with some additional import.
?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Auth\AuthManager;
use Illuminate\Support\Facades\Auth;
use Auth\Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Wisata;
use App\User;

namespace App\Http\Controllers\Voyager;

use TCG\Voyager\Http\Controllers\VoyagerBreadController as BaseVoyagerBreadController;

class VoyagerBreadController extends BaseVoyagerBreadController
{
    //
}

and able to do this on my custom view
//get currently logged user
@php
  $currentUser = Auth::user()->nama;
@endphp

//printed output(for testing)
 {{$currentUser}}

and it works!,so i tried to set the BREAD option like this
{
    "default" : "{{$currentUser}}"
}

however,unlike my custom views it doesn't returned the $currentUser value,just plain {{$currentUser}} in my tables.
please help me to make a fully functional created_by and last_edit_by table.
notes: im open to use any packages.
EDIT : it's solved by duplicating the form just below the real dynamic form in my custom view(edit-add.blade.php),make a hidden type created_by & last_edited_by table & keep the BREAD option empty. and you can still adjust the visiblity without any problems.
//created_by form

<input type="hidden" class="form-control" name="created_by" placeholder="Created By" value="{{$currentUser}}">

//last_edited_by form

<input type="hidden" class="form-control" name="last_edited_by" placeholder="Last Edited By" value="{{$currentUser}}">

anyway , i still would be very thankful if someone give more efficient solution :)

A: You can add additional properties to the model without changing anything in the view file.
Just add the save() method in the corresponding Model class and assign additional properties.
Model
public function save(array $options = [])
{
    if (Auth::user()) {
        $this->created_by = Auth::user()->getKey();
        //you may use user's name or any other property
        $this->updated_by = Auth::user()->name;
    }

    return parent::save();
}

This will add created_by and updated_by whenever saving the new model record. You may add additional logic to the save() method as per your need.
Tested in Laravel 8 [and should be work in 5.7 too]


text:
Q: Using debugger to Log command lines of crashed applications We have an application that crashes at startup, especially under high load.  Problem is, there's no way to tell apart the various instances of this process from one another, except the invocation command line itself.
Is there a way to use WinDBG, WER, etc. to extract the command lines of crashed processes?  I know it's nested in the PEB somewhere.  The goal would be to just have it dump the information so that we can see if the crashing processes have anything in common.
Thoughts?

A: Try ??@$peb->ProcessParameters->CommandLine

A: In WinDbg, !peb shows the Process Environment Block including the command line. Because the output is long, I recommend filtering it using .shell:
.shell -ci "!peb" find "CommandLine"


text:
Q: Add weight parameter in custom module I created a content type and it's have many nodes. And write custom module for show on frontpage.
My nodes order:
 $themeurl = '/drupal/'.path_to_theme().'/images';
    $sql = "SELECT * FROM `node`
            LEFT JOIN `field_data_field_anasayfa_catwalk` ON `field_data_field_anasayfa_catwalk`.`entity_id` = `node`.`nid`
            WHERE type = 'designers_albums'
            AND `node`.`status` = 1
            AND `node`.`language` = '".$language->language."'
            AND `field_data_field_anasayfa_catwalk`.`field_anasayfa_catwalk_value` = 1
            ORDER BY `node`.`created` ASC";

But now, installed Weight module and want sort by weight. How can i change this option? Thank you.

A: Entities(nodes) weights are stored in weight_weights database table.
You can try that query
     $sql = "SELECT * FROM `node`
        LEFT JOIN `field_data_field_anasayfa_catwalk` ON `field_data_field_anasayfa_catwalk`.`entity_id` = `node`.`nid`
        LEFT JOIN `weight_weights` AS w ON w.entity_id=`node`.`nid`
        WHERE type = 'designers_albums'
        AND `node`.`status` = 1
        AND `node`.`language` = '".$language->language."'
        AND `field_data_field_anasayfa_catwalk`.`field_anasayfa_catwalk_value` = 1
        ORDER BY w.weight, `node`.`created` ASC";

Btw, in future you should consider learning Drupal database abstraction layer or EntityFieldQuery.


text:
Q: ProvisioningImportEventsCallback error while trying to import Work item type definition I try this command in %programfiles(x86)%\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer>
witadmin importwitd /collection:http://server/tfs/collction /p:project /f:"workitem.xml"

and get this in red:

Microsoft.TeamFoundation.WorkItemTracking.Server.ProvisioningImportEventsCallback

(Edit:) The exportwitd command works without error, and I am trying to import the same XML that I just exported, to the same WIT.
I found some references to this error, but most solutions seem to say not to use that with VSTS:
https://social.msdn.microsoft.com/Forums/en-US/6d797a4c-9f87-458a-9572-cb7552c3d607/witadmin-returns-error?forum=TFService
Unable to import work item type definition: Microsoft.TeamFoundation.WorkItemTracking.Server.ProvisioningImportEventsCallback
But I'm not using VSTS, I'm using TFS 2017 Update 3.
I've tried clearing my TFS cache under %AppData%\Local\Microsoft\Team Foundation\7.0\Cache and I've also tried clearing my credential vault.
I've also tried using the WorkItemTypeCollection.Import Method but it yields the same error.
Also, the import is successful if I use my account with Server Administration permissions, which suggests it's a permission error, but I'm stumped by the error message. What does it mean?

A: To export or list work item types, you must be a member of the Project Administrators group or have your View project-level information permission set to Allow.
To destroy, import, or rename work item types, you must be a member of the Team Foundation Administrators security group or the Project Administrators security group.
You may check the account permission.