text:
Q: Performance in GUID comparison I read this question and another question. In one of these two questions, I also read that Guid Structure consists of following four fields: Int32, Int16, Int16 and Byte[8], so the comparison between two Guid should be faster.
Well, I use the Guid Structure only to generate UUID, and then I have to compare only those previously generated UUID. Therefore, I would like to convert each UUID generated quickly in a format comparable.
I ran some tests using the following code (I took inspiration from this question).
        struct FastUuid
        {
            public long _part1;
            public long _part2;

            public FastUuid(byte[] value)
            {
                _part1 = BitConverter.ToInt64(value, 0);
                _part2 = BitConverter.ToInt64(value, 8);
            }
        }

        static void Main(string[] args)
        {
            TestUuidCompare(1000000000);
            Console.ReadLine();

        }

        public static void TestUuidCompare(uint numberOfChecks)
        {
            Guid uuid1 = Guid.NewGuid();
            Guid uuid2 = new Guid(uuid1.ToByteArray());

            byte[] a1 = uuid1.ToByteArray();
            byte[] a2 = uuid2.ToByteArray();

            string s1 = uuid1.ToString();
            string s2 = uuid2.ToString();

            BigInteger b1 = new BigInteger(uuid1.ToByteArray());
            BigInteger b2 = new BigInteger(uuid2.ToByteArray());

            long l1part1 = BitConverter.ToInt64(uuid1.ToByteArray(), 0); // Parts 1 and 2
            long l1part2 = BitConverter.ToInt64(uuid1.ToByteArray(), 8); // of uuid1.

            long l2part1 = BitConverter.ToInt64(uuid2.ToByteArray(), 0); // Parts 1 and 2
            long l2part2 = BitConverter.ToInt64(uuid2.ToByteArray(), 8); // of uuid2.

            long[] la1 = { l1part1, l1part2 }; // Parts 1 and 2 of uuid1.
            long[] la2 = { l2part1, l2part2 }; // Parts 1 and 2 of uuid2.

            int i1part1 = BitConverter.ToInt32(uuid1.ToByteArray(), 0);  // Parts 1, 2, 3
            int i1part2 = BitConverter.ToInt32(uuid1.ToByteArray(), 4);  // and 4
            int i1part3 = BitConverter.ToInt32(uuid1.ToByteArray(), 8);  // of
            int i1part4 = BitConverter.ToInt32(uuid1.ToByteArray(), 12); // uuid1.

            int i2part1 = BitConverter.ToInt32(uuid2.ToByteArray(), 0);  // Parts 1, 2, 3
            int i2part2 = BitConverter.ToInt32(uuid2.ToByteArray(), 4);  // and 4
            int i2part3 = BitConverter.ToInt32(uuid2.ToByteArray(), 8);  // of
            int i2part4 = BitConverter.ToInt32(uuid2.ToByteArray(), 12); // uuid2

            FastUuid fast1 = new FastUuid(uuid1.ToByteArray());
            FastUuid fast2 = new FastUuid(uuid2.ToByteArray());

            // UUID are equal (worse scenario)

            Stopwatch sw = new Stopwatch();
            bool result;

            sw.Reset(); sw.Start();
            for (int i = 0; i < numberOfChecks; i++)
            {
                result = (uuid1 == uuid2);
            }
            Console.WriteLine("- Guid.Equals: \t{0}", sw.Elapsed);

            sw.Reset(); sw.Start();
            for (int i = 0; i < numberOfChecks; i++)
            {
                result = Array.Equals(a1, a2);
            }
            Console.WriteLine("- Array.Equals(byte): \t{0}", sw.Elapsed);

            sw.Reset(); sw.Start();
            for (int i = 0; i < numberOfChecks; i++)
            {
                result = s1.Equals(s2);
            }
            Console.WriteLine("- String.Equals: \t{0}", sw.Elapsed);

            sw.Reset(); sw.Start();
            for (int i = 0; i < numberOfChecks; i++)
            {
                result = b1.Equals(b2);
            }
            Console.WriteLine("- BigInteger.Equals: \t{0}", sw.Elapsed);

            sw.Reset(); sw.Start();
            for (int i = 0; i < numberOfChecks; i++)
            {
                result = (l1part1 == l2part1 && l1part2 == l2part2);
            }
            Console.WriteLine("- Two long compare: \t{0}", sw.Elapsed);

            sw.Reset(); sw.Start();
            for (int i = 0; i < numberOfChecks; i++)
            {
                result = Array.Equals(la1, la2);
            }
            Console.WriteLine("- Array.Equals(long): \t{0}", sw.Elapsed);

            sw.Reset(); sw.Start();
            for (int i = 0; i < numberOfChecks; i++)
            {
                result = (i1part1 == i2part1 && i1part2 == i2part2 && i1part3 == i2part3 && i1part4 == i2part4);
            }
            Console.WriteLine("- Four int compare: \t{0}", sw.Elapsed);

            sw.Reset(); sw.Start();
            for (int i = 0; i < numberOfChecks; i++)
            {
                result = fast1.Equals(fast2);
            }
            Console.WriteLine("- FastUuid: \t{0}", sw.Elapsed);
        }

With the following results.

*

*Guid.Equals:           18.911 s

*Array.Equals(byte):    12.003 s

*String.Equals:         26.159 s

*BigInteger.Equals:     22.652 s

*Two long compare:       6.530 s  <--- the fastest

*Array.Equals(long):    11.930 s

*Four int compare:       6.795 s

*FastUuid:           1m 26.636 s  <--- the slowest

Why the FastUuid comparison is the slowest?
Since the UUID should be the key to a Dictionary, is there a way to get the performance comparison between two long, and at the same time, implement the UUID with a small (16 byte) object/struct?
EDIT:
Actually, the tests that I performed measure the performance of the comparison between two UUID, so they have little meaning to evaluate the performance of accessing a Dictionary, because when I invoke the ContainsKey method, it calculates the hash value of the UUID.
Should I evaluate the performance in calculating the hash value of the Guid, String, FastUuid, etc.?
How does the ContainsKey method work?

A: The default implementation of Equals for structs uses reflection for comparison, which is slower. (See more at ValueType.Equals on MSDN.)
You should override Equals and provide your own implementation:
public override bool Equals(object other)
{
    var fastOther = other as FastUuid?;
    return fastOther.HasValue &&
        fastOther.Value._part1 == _part1 &&
        fastOther.Value._part2 == _part2;
}

This won't fix the problem entirely, however. Since this is a struct you should also implement IEquatable<FastUuid> to avoid having to box/unbox the other item:
public bool Equals(FastUuid other)
{
    return
        other._part1 == _part1 &&
        other._part2 == _part2;
}

Equals is then just:
public override bool Equals(object other)
{
    var fastOther = other as FastUuid?;
    return fastOther.HasValue && Equals(fastOther.Value);
}

A: Structs use runtime reflection to determine what needs to be compared.  Override Equals with your own comparison method to get much faster results.
see http://msdn.microsoft.com/en-us/library/2dts52z7.aspx
Update - Overriding equals for a struct ends up having boxing overheads (converting struct to object and back to struct), but if you define an Equals that takes the FastUuid struct directly, it runs much faster:
        public bool Equals(FastUuid value)
        {
            return this._part1 == value._part1
                && this._part2 == value._part2;
        }

This runs slightly faster than the Guid implementation on my box (4.2sec vs 5.8sec, but still slower than long comparison at 1.7sec).
ps. Pls be careful to run tests with release builds only, as debug builds can seriously affect timing.


text:
Q: Unable to locate element of autocomplete options In my application i have a text box which when i enter the city name brings the city names to
select a city.when i am trying to locate the element,it says it is unable to locate the element.
THis is HTML code

Hyderabad

Here is my script code
driver.find_element_by_name('residential_city_id').send_keys("Hyderabad")
tme.sleep(5)
html_list=driver.find_element_by_id("autocomplete-options-fd419e03-fc56-725a-dc68-0dd3e55a2b19")
items = html_list.find_elements_by_tag_name("li")
for item in items:
    text = item.text
    print(text)

i am getting the following error
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate
element: {"method":"css selector","selector":"[id="autocomplete-options-fd419e03-fc56-725a-dc68-0dd3e55a2b19"]"}
  (Session info: chrome=76.0.3809.132)

A: I think your issue is in these lines of code here:
html_list=driver.find_element_by_id("autocomplete-options-fd419e03-fc56-725a-dc68-0dd3e55a2b19")
items = html_list.find_elements_by_tag_name("li")

The ID autocomplete-options-fd419e03-fc56-725a-dc68-0dd3e55a2b19 looks like a randomized ID that changes each time you refresh the page. You want to use a more robust selector in this case.
I don't think there is a need to get items list at all. I think you can replace the two lines of code above with just one:
driver.find_element_by_xpath("//span[text()='Hyderabad']")

This will find the span element with text Hyderabad
Now your code will look like:
driver.find_element_by_name('residential_city_id').send_keys("Hyderabad")
tme.sleep(5)
driver.find_element_by_xpath("//span[text()='Hyderabad']")

A: To click() on the auto complete element with text as Hyderabad you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

*

*Using CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "ul.autocomplete-content.dropdown-content li.active > span > span.highlight"))).click()

*Using XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@class='autocomplete-content dropdown-content']//li[@class='active']/span/span[@class='highlight' and text()='Hyderabad']"))).click()

*Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible for double-escaping to cause harm to the DB? If I accidentally double escape a string, can the DB be harmed?
For the purposes of this question, let's say I'm not using stored procedures or parametrized queries
For example, let's say I get the following input:
bob's bike
And I escape that:
bob\'s bike
But my code is horrible, and escapes it again:
bob\\\'s bike
Now, if I insert that into a DB, the value in the DB will be
bob\'s bike
Which, while is not what I want, won't harm the DB. Is it possible for any input that's double escaped to do something malicious to the DB assuming that I take all other necessary security precautions?

A:
assuming that I take all other
  necessary security precautions

Hardcoding SQL and/or parameter values into an application should never be considered "taking the necessary security precautions", because you will always be subject to SQL injection attacks (in the case of a web application).
It's best to use stored procedures if you can, and if that's not an option, at a minimum you should be using parameterized queries (bind variables is another term for this).
But to answer your question, storing bob\'s bike in the database isn't going to do any harm in and of itself, but take care to consider the other points mentioned above, they are vitally important from a security perspective.

A: Single escaping is equally as harmful/harmless as double escaping in terms of security.
The biggest issue is that you need to double-unescape. Otherwise, if you only single-unescape, you will end up with backslashes in database output.
For example, if you run bob\\\'s bike through the unescape() function, it will output bob\'s bike which will then be printed to the page, unless you unescape it again. But don't unescape too many times, because this can remove intentional backslashes (and possibly do more harm).
Does this question have anything to do with PHP's magic quotes feature by chance? Just curious...


text:
Q: How to write a select query with Scala Anorm? How to get user_name value , using Scala Anorm? I tried:
 val result = SQL("SELECT user_name a FROM user WHERE user_id = {user_id}").on('user_id -> 1).executeQuery()
 println("result ="+result)

And, I am getting  result = SqlQueryResult(FlattenedManagedResource[?](...),false) instead of this I was expecting user_name value in table.
How should I do to get what I want?

A: You have to use a result parser; e.g
import anorm.SqlParser.scalar
val parser = scalar[String].single
// expect only one row (single),
// with only one column (scalar),
// of type String

val user: String = SQL("SELECT user_name a FROM user WHERE user_id = {user_id}").on('user_id -> 1).as(parser)

It's recommended you have a look at the documentation


text:
Q: What is the Windows version of cron? A Google search turned up software that performs the same functions as cron, but nothing built into Windows.
I'm running Windows XP Professional, but advice for any version of Windows would be potentially helpful to someone.
Is there also a way to invoke this feature (which based on answers is called the Task Scheduler) programatically or via the command line?

A: Zcron is available free for personal use.

A: The closest equivalent are the Windows Scheduled Tasks (Control Panel -> Scheduled Tasks), though they are a far, far cry from cron.
The biggest difference (to me) is that they require a user to be logged into the Windows box, and a user account (with password and all), which makes things a nightmare if your local security policy requires password changes periodically. I also think it is less flexible than cron as far as setting intervals for items to run.

A:
Is there also a way to invoke this feature (which based on answers is called the Task Scheduler) programatically [...]?

Task scheduler API on MSDN.

A: If you prefer good ol' cron, CRONw is the way to go.
Supported systems

* Windows 2000 (any version)    works
* Windows XP (SP 2)             works
* Windows Server 2003           works
* Windows NT 4 (SP 6)           should work but not tested
* Windows 3.11, Windows 95,
  Windows 98, Windows ME,
  Windows XP beneath SP2        not supported by design

A: Not exactly a Windows version, however you can use Cygwin's crontab. For install instructions, see here: here.

A: There is NNCron for Windows. IT can schedule jobs to be run periodically.

A: For the original question, asking about Windows XP (and Windows 7): Windows Task Scheduler
For command-line usage, you can schedule with the AT command.
For newer Microsoft OS versions, Windows Server 2012 / Windows 8, look at the schtasks command line utility.
If using PowerShell, the Scheduled Tasks Cmdlets in Windows PowerShell are made for scripting.

A: The Windows "AT" command is very similar to cron. It is available through the command line.

A: In addition to Windows Task Scheduler you also have 'at' on Windows. I'm not sure how it differs from Task Scheduler besides the fact that it has a command line interface.

A: Use the Windows Task Scheduler to schedule tasks over time and dates.

A: pycron is close match on Windows.  The following entries are supported:
1    Minute (0-59)
2    Hour (2-24)
3    Day of month (1-31)
4    Month (1-12, Jan, Feb, etc)
5    Day of week (0-6) 0 = Sunday, 1 = Monday etc or Sun, Mon, etc)
6    User that the command will run as
7    Command to execute

A: The 'at' command.

"The AT command schedules commands and
  programs to run on a computer at a
  specified time and date. The Schedule
  service must be running to use the AT
  command."

A: The At command is now deprecated
you can use the SCHTASKS

A: *

*You can use the Scheduled-Tasks API in PowerShell along with a config.json file for parameters input. I guess the minimum limitation is 5 minutes. A sample tutorial for very basic Schedule Tasks creation via APIs

*You can use the schtasks.exe via cmd too. I could see the minute modifier limitation to 1 minute on executing schtasks.exe /Create /?. Anyways AT is now deprecated.

Anyways, I am working on a tool to behave like CRON. I will update here if it is successfull.

A: Check out the excellent Cronical program at https://github.com/mgefvert/Cronical
It is a .NET program that reads a text file with unix-like cron lines. Very convenient to use. It will send emails if stdout just like unix cron. It even supports acting as the service runner.


text:
Q: How to change the ugly looking JavaScript file type icon in Windows 7? I'm just starting out to learn JavaScript, and I already hate the ugly looking icon that Microsoft uses for this file type. It's old and boring, looks like something that came right out of Windows 95.

I can't stand looking at it!
So I have decided to show you how to change it to something more appealing.

A: *

*Head over to NirSoft website and download a program called
"FileTypesMan v1.65".

*Unpack FileTypesMan from the ZIP file.

*Head over to Icon Archive and search for "javascript" to find
some nice icon you can use. Make sure you download the ICO version
of it. You can of course use your own icons as well.

*Now copy your ICO file to %SystemRoot%\system32 or to the root of
your C disk. Just make sure it's in some place you won't move it
from at some point.

*Run the FileTypesMan EXE file.

*Press Ctrl+F and type in .js and then press Enter to locate this
extension, and Esc to close the Find dialog box.

*It should be already selected, if not, select it and press F2 to
edit the file type.

*In the field "Default Icon" click the button next to it to locate
your ICO file. If you stored it to %SystemRoot%\system32 it should
be in C:\Windows\system32 folder. You can also type in the search
path. Click OK, then OK again to save changes.

You should now have something more pleasant to look at, like this:

Icon created by Untergunter, licensed as CC Attribution-Noncommercial-Share Alike 3.0.
This icon is nothing special really, but does look much better in a modern operating system such as Windows 7, than the default JScript icon that Microsoft uses. Another benefit of using this particular icon is that you get several icon sizes, so clicking the "change your view" button in Windows Explorer actually works for this file type, you get a nice big icon instead of the Windows 95 wreck you get by default.
You can use FileTypesMan program to change any file type icon on Windows 7. It's also portable, so no need to install it. Anthor way to accomplish the same result would be to use Registry Editor (regedit.exe). I won't cover that, since others have already done so.
Credits go out to HTG for explaining how to use this wonderful program.
Screenshots


text:
Q: PowerShell command prints the value rather than executing I have written a power shell command to achieve a specific function and I'm new to power shell.
That should perform the action and I'm pretty sure I have entered exact working command.
But when I try to execute the command inside for each loop, it prints the command rather than executing. NWAdminCommand is my command and it gets values from user input.
$NWAdminCommand = Read-Host "Enter NWAdmin Command to perform request action"

foreach ($SPSite in $spWebApp.Sites)
    {

      foreach($SPWeb in $SPSite.AllWebs)
         {
    $NWAdminCommand;
         }
     }
    }

A: I'm not sure this would work. But have you tried to use Invoke-Expression
The Invoke-Expression cmdlet evaluates or runs a specified string as a command and returns the results of the expression or command. Without Invoke-Expression, a string submitted at the command line would be returned (echoed) unchanged.
http://technet.microsoft.com/en-us/library/hh849893.aspx
$cmd = '& 7z.exe a -tzip "c:\temp\with space\test2.zip" "C:\TEMP\with space\changelog"'

Invoke-Expression $cmd

https://stackoverflow.com/questions/3592851/executing-a-command-stored-in-a-variable-from-powershell

A: just to understand:
your asking:

Enter NWAdmin Command to perform request action:

i then type ali and it would loop through each subsite within the given site (i have 5):
so the result should be:

ali
ali
ali
ali
ali

solution:
Add-PSSnapin Microsoft.Sharepoint.Powershell

$NWAdminCommand = Read-Host "Enter NWAdmin Command to perform request action"

$spWebApp = Get-SPWebApplication http://mywebapplication:23125/

foreach ($SPSite in $spWebApp.Sites)
{
    foreach($SPWeb in $SPSite.AllWebs)
    {
        $NWAdminCommand;
    }
}

above needs to be within a file witht the extention of .ps1 , run that file within powershell! code has been tested on my server, if your looking for somthing else than please do refine your question :)
if you want to ask that question for each site looped than its in the wrong location... i dont see why you want to print the same reply for each site looped and print the same result to screen:
solution:
Add-PSSnapin Microsoft.Sharepoint.Powershell

$spWebApp = Get-SPWebApplication http://mywebapplication:23125/

foreach ($SPSite in $spWebApp.Sites)
{
    foreach($SPWeb in $SPSite.AllWebs)
    {
        $NWAdminCommand = Read-Host "Enter NWAdmin Command to perform request action"

        //do what you want with the varible $NWAdminCommand related to site $SPWeb
    }
}

above would ask the question for each site, that varible (answer) is now only related to that site and is reset every site that is iterated.


text:
Q: How to convert sql query to codeigniter query Can somebody help me convert this Sql Query
SELECT *
FROM customer c
LEFT JOIN customer_order co
ON c.customer_number = co.customer_number
AND co.order_status IN ('preparing', 'prepared')
WHERE c.customer_status='unpaid'
AND c.order_status = 'unserve'
AND co.cus_ord_no IS null

into Codeigniter query just like the image below for example

A: When query statements do not have clauses that need to change conditionally then using $this->db-query() is the way to go.
$sql = "SELECT * FROM customer c LEFT JOIN customer_order co
ON c.customer_number=co.customer_number AND co.order_status IN ('preparing', 'prepared')
WHERE c.customer_status='unpaid' AND c.order_status='unserve' AND co.cus_ord_no IS null";

$query = $this->db->query($sql)->result();
echo json_encode($query);

It might be wise to include a check on the return from query() though because if it fails (returns false) then the call to result() will throw an exception. One way that can be handled is like this.
$query = $this->db->query($sql);
if($query !== FALSE)
{
    echo json_encode($query->result());
    return;
}

echo json_encode([]); // respond with an empty array

Query Builder (QB) is a nice tool, but it is often overkill. It adds a lot of overhead to create a string that literally is passed to $db->query(). If you know the string and it doesn't need to be restructured for some reason you don't need QB.
QB is most useful when you want to make changes to your query statement conditionally. Sorting might be one possible case.
if($order === 'desc'){
   $this->db->order_by('somefield','DESC');
} else {
       $this->db->order_by('somefield','ASC');
}

$results = $this->db
    ->where('other_field', "Foo")
    ->get('some_table')
    ->result();

So if the value of $order is 'desc' the query statement would be
SELECT * FROM some_table WHERE other_field = 'Foo' ORDER BY somefield 'DESC'

But if you insist on using Query Builder I believe this your answer
$query = $this->db
    ->join('customer_order co', "c.customer_number = co.customer_number AND co.order_status IN ('preparing', 'prepared')", 'left')
    ->where('c.customer_status','unpaid')
    ->where('c.order_status','unserve')
    ->where('co.cus_ord_no IS NULL')
    ->get('customer c');

//another variation on how to check that the query worked
$result = $query ? $query->result() : [];
echo json_encode($result);

A: You can do
public function view_customers()
{
    $sql = "SELECT * FROM customer c LEFT JOIN customer_order co ON c.customer_number = co.customer_number AND co.order_status IN ('preparing', 'prepared') WHERE c.customer_status='unpaid' AND c.order_status = 'unserve' AND co.cus_ord_no IS null";

    return $this->db->query($sql)->result();
}

You can use row() for one output to object, or row_array() if one output but array. result() is multiple objects and result_array() is multiple arrays.
My way do usually is like this:
Controller:
public function view()
{
    $this->load->model('My_Model');

   $data = new stdclass;
   $data->user_lists = $this->my_model->view_users(array('nationality'=>'AMERICAN'));
}

Model:
public function view_users($param = null) //no value passed
{
   $condition = '1';
   if (!empty($param)) { //Having this will trap if you input an array or not
     foreach ($param as $key=>$val) {
       $condition .= " AND {$key}='{$val}'"; //Use double quote so the data $key and $val will be read.
     }
   }

   $sql = "SELECT * FROM users WHERE {$condition}"; //Use double quote so the data $condition will be read.
   // Final out is this "SELECT * FROM users WHERE 1 AND nationality='AMERICAN'";

   return $this->db->query($sql)->result();
}


text:
Q: Removal of noisy pixels using opencv I am trying to detect text from an input image using openCV.
For that I need to remove the noise components from the image. The criteria for that which am using is that if the pixel count of certain component is less than 15 am eliminating that particular component.
e.g suppose the below given images are provided as i/p to the function:

As it can be seen both the images contain a lot of unwanted noisy pixels, specially the first one.
So if anyone can suggest a feasible way for achieving it, it would be highly appreciated.

A: Ok, sorry but this isn't in c and its not using opencv, however I'm sure labelling must be possible in opencv, just I haven't used it yet... so this might help... Basically the idea is:

*

*Find, and label all separate blobs in the image

*Remove all blobs that fall outside certain constraints (size, shape)

Here I implement this in python using scipy, but just for size (not shape, although this is easy and would get rid of the long thin lines in first image below). For this to work we must know an acceptable range of sizes for the letters - however you could determine this after labelling by looking at average blob size.. You may still get letter sized false positives - but these could possibly be removed by observing that they fall outside a certain area of concentrated blobs (as text is spacially regular)... Also minimum sentence length could be a powerful constraint.
Anyhow, code:
import scipy
from scipy import ndimage

im = scipy.misc.imread('learning2.png',flatten=1)
#threshold image, so its binary, then invert (`label` needs this):
im[im>100]=255
im[im<=100]=0
im = 255 - im
#label the image:
blobs, number_of_blobs = ndimage.label(im)
#remove all labelled blobs that are outside of our size constraints:
for i in xrange(number_of_blobs):
    if blobs[blobs==i].size < 40 or blobs[blobs==i].size>150:
        im[blobs==i] = 0
scipy.misc.imsave('out.png', im)

results:


text:
Q: DynamoDB query function is not working while trying to access the data So I tried to fetch data from dynamodb, using the below code, I am getting null and no log is showing after the query function is called.
I tried it locally, it is working locally, only through lambda function it is not working, I also checked if my role has the permission to read dynamodb, it does. So I am clueless on this
"use strict";

const config = require("./config");
const AWS = require("aws-sdk");

AWS.config.update({
  region: "us-east-1"
});
let dynamodb = new AWS.DynamoDB.DocumentClient({
  region: "us-east-1"
});

var getAnswerToQuestion = (questionKey, callback) => {

  var params = {
    TableName: "genral-questions-db",
    KeyConditionExpression: "#questionKey = :question",
    ExpressionAttributeNames: {
      "#questionKey": "question"
    },
    ExpressionAttributeValues: {
      ":question": String(questionKey)
    }
  };
  console.log("Trying to query dynamodb");

  dynamodb.query(params, (err, data) => {
    if(err) {
      console.log (err)
      callback(err);
    } else {
      console.log(data.Items);
      callback(data.Items[0]);
    }
  });
}

module.exports = {
  getAnswerToQuestion
};

logs:
Function Logs:
START RequestId: 6adeddbe-4925-4877-a2c0-d20576145224 Version: $LATEST
2019-09-22T17:35:30.088Z    6adeddbe-4925-4877-a2c0-d20576145224    event.bot.name=bcbsri
2019-09-22T17:35:30.088Z    6adeddbe-4925-4877-a2c0-d20576145224    dispatch userId=pn6yexoq87uej2evt9huhilc5f99bhb7, intentName=GenralQuestionIntent
2019-09-22T17:35:30.088Z    6adeddbe-4925-4877-a2c0-d20576145224    GenralQuestionIntent was called - Srinivas
2019-09-22T17:35:30.089Z    6adeddbe-4925-4877-a2c0-d20576145224    have to query the db hsa
2019-09-22T17:35:30.089Z    6adeddbe-4925-4877-a2c0-d20576145224    Trying to query dynamodb
END RequestId: 6adeddbe-4925-4877-a2c0-d20576145224
REPORT RequestId: 6adeddbe-4925-4877-a2c0-d20576145224  Duration: 596.83 ms Billed Duration: 600 ms Memory Size: 128 MB Max Memory Used: 76 MB  Init Duration: 193.27 ms

not even getting error, it just does not give back any data. Please help me to resolve this issue
EDIT:
here is the code from where I am trying to call the utils method(db)
module.exports =  function(intentRequest) {
    return new Promise((resolve, reject) => {

        // Resolve question key
        const questionKey = intentRequest.currentIntent.slots.QuestionKey;

        let speechText;

        console.log('have to query the db', questionKey);

        utils.getAnswerToQuestion(questionKey, res => {
            if(res ) {
                speechText = res.answer;
            } else {
                speechText = "Sorry, details about " + questionKey + " was not found";
            }

            const response = {
                fullfilmentState: 'Fulfilled',
                message: { contentType: 'PlainText', content: speechText }
            };
            console.log(response);

            resolve(response);
            return lexResponses.close(intentRequest.sessionAttributes, response.fullfilmentState, response.message);
        });
    });
};

A: I would bet that this is the most common problem that people see when using Node.js with Lambda.
When a Node.js Lambda reaches the end of the main thread, it ends all other threads. When it reaches the end of the handler, it stops all concurrent promises or async calls that are running.
To make sure that the lambda does not prematurely terminate those threads, wait until those promises are complete by using await.
In your case, use the .promise() method with any AWS requests and then await them:
try {
    const data = await dynamodb.query(params).promise();
    console.log(data.Items);
    callback(data.Items[0]);
}  catch (err) {
    console.log(err);
    callback(err);
}


text:
Q: takes from 3 to 5 positional arguments but 6 were given? My program is supposed to draw a chessboard using user input. The drawing has to occur with the call of draw(). I am getting an error:
line 18, in main
 chessboard = Chessboard(tr, startX, startY, eval(width),  val(height))
TypeError: __init__() takes from 3 to 5 positional arguments but 6 were given

The thing is that my main module cannot change. I have to leave it as it is. It's a requirement. So, how can I solve that problem when I cannot change a thing from it? It only gives me an error on line 18.
main module:
import turtle
from chessboard import Chessboard

def main():
    startX, startY = eval(input("Enter a starting point: "))
    width = input("Input a width: ")
    height = input("Input a height: ")

    tr = turtle.Turtle()

    if width == "" and height == "":
        chessboard = Chessboard(tr, startX, startY)
    elif height == "":
        chessboard = Chessboard(tr, startX, startY, width=eval(width))
    elif width == "":
        chessboard = Chessboard(tr, startX, startY, height=eval(height))
    else:
        chessboard = Chessboard(tr, startX, startY, eval(width), eval(height))

        chessboard.draw()

        tr.hideturtle()
        turtle.done()

main()

I leave my chessboard.py module in case it has to do something with it:
import turtle

class Chessboard:
    def __init__(self, startX, startY, width=250, height=250):
        self.__startX = startX
        self.__startY = startY
        self.__width = width
        self.__height = height

    def draw(self, __startX, __startY, __width=250, __height=250):
        turtle.clear
        self.__drawChessboard(__startX, __startY, __width, __height)

    def __drawChessboard(self, __startX, __startY, __width=250, __height=250):
        # uses height x width, default 250
        turtle.setheading(0)
        turtle.penup()
        turtle.goto(__startX, __startY)
        turtle.pendown()
        turtle.goto(__startX + __width, __startY)
        turtle.goto(__startX + __width, __startY + __height)
        turtle.goto(__startX, __startY + __height)
        turtle.goto(__startX, __startY)

        self.__drawAllRectangles(self, __startX, __startY, __width, __height)

        turtle.exitonclick()

    def __drawAllRectangles(self, __startX, __startY, __width, __height):
        __checkerWidth = __width / 8
        __checkerHeight = __height / 8
        for row in range(8):
            for column in range(4):
                if row % 2 == 0:
                    self.__drawRectangle(self, __startX + (2 * column * __checkerWidth),
                                         __startY + (row * __checkerHeight), __checkerWidth, __checkerHeight)
                else:
                    self.__drawRectangle(self, __startX + __checkerWidth + (2 * column * __checkerWidth),
                                         __startY + (row * __checkerHeight), __checkerWidth, __checkerHeight)

    def __drawRectangle(self, __startX, __startY, __checkerWidth, __checkerHeight):
        turtle.penup()
        turtle.setheading(0)
        turtle.goto(__startX, __startY)
        turtle.fillcolor("black")
        turtle.begin_fill()
        turtle.pendown()
        turtle.goto(__startX + __checkerWidth, __startY)
        turtle.goto(__startX + __checkerWidth, __startY + __checkerHeight)
        turtle.goto(__startX, __startY + __checkerHeight)
        turtle.goto(__startX, __startY)
        turtle.end_fill()

Thanks for your help!

A: The first argument of every class method, including init, is always a reference to the current instance of the class. By convention, this argument is always named self. In the init method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called.
EDIT: I didnt read the part where you said you can't change the main module, I apologize
class Chessboard:
    def __init__(self, tr, startX, startY, width=250, height=250):
        self.tr = tr
        self.__startX = startX
        self.__startY = startY
        self.__width = width
        self.__height = height

    def draw(self):
        self.tr.clear()
        self.__drawChessboard(self.__startX, self.__startY, self.__width, self.__height)

    def __drawChessboard(self, __startX, __startY, __width=250, __height=250):
        # uses height x width, default 250
        self.tr.setheading(0)
        self.tr.penup()
        self.tr.goto(__startX, __startY)
        self.tr.pendown()
        self.tr.goto(__startX + __width, __startY)
        self.tr.goto(__startX + __width, __startY + __height)
        self.tr.goto(__startX, __startY + __height)
        self.tr.goto(__startX, __startY)

        self.__drawAllRectangles(__startX, __startY, __width, __height)

        self.tr.exitonclick()

    def __drawAllRectangles(self, __startX, __startY, __width, __height):
        __checkerWidth = __width / 8
        __checkerHeight = __height / 8
        for row in range(8):
            for column in range(4):
                if row % 2 == 0:
                    self.__drawRectangle(__startX + (2 * column * __checkerWidth),
                                         __startY + (row * __checkerHeight), __checkerWidth, __checkerHeight)
                else:
                    self.__drawRectangle(__startX + __checkerWidth + (2 * column * __checkerWidth),
                                         __startY + (row * __checkerHeight), __checkerWidth, __checkerHeight)

    def __drawRectangle(self, __startX, __startY, __checkerWidth, __checkerHeight):
        self.tr.penup()
        self.tr.setheading(0)
        self.tr.goto(__startX, __startY)
        self.tr.fillcolor("black")
        self.tr.begin_fill()
        self.tr.pendown()
        self.tr.goto(__startX + __checkerWidth, __startY)
        self.tr.goto(__startX + __checkerWidth, __startY + __checkerHeight)
        self.tr.goto(__startX, __startY + __checkerHeight)
        self.tr.goto(__startX, __startY)
        self.tr.end_fill()


text:
Q: Rails write variable in view without using <%= %> Let's say I've got the variable @var. Usually I would use <%= @var %> to write it into the view. Now I want to call a module method from within my view which internally decides to write the content of @var or not.
Inside the module I can't use <%= %>. How can I print the content of @var from within the module? The method would be called like this: <% my_method %>. Thanks
Update
Thanks for the answers so far. Maybe I should say more about my initial problem to be more clear. Sorry if I wasn't clear enough.
At first I used the <%= %> tag like this:
def print_if_present(var)
  var ? var : ""
end

<%= print_if_present var %>

But then, when the var was nil, I got "" as output, which took space in the view. How can I prevent this behavior?

A: I assume that your module is actualy the view helper. If is that so, simply return var.
def my_method
  if my_condition
    @var
  else # else clause is optional
    @other_var
  end
end

Note that the else clause is optional. If you want to write something or nothing, you can simply use the if. This is so because if the if is not executed and there is no else, it will return nil, that will be casted to an empty string in your template. Just to ilustrate,
if true
  1
end
 => 1 #return if last value

if false
  1
end
 => nil # return nil because there is no else block

Since you still want to print the return of your method on your template, you need to keep the equal sign:
<%= my_method %>

A: The best way to do this is to have your method return the string and use <%= ... %> as in fotanus' answer, but in Rails if you really need to write output directly from a helper you could use the concat method:

The preferred method of outputting text in your views is to use the <%= "text" %> eRuby syntax. The regular puts and print methods do not operate as expected in an eRuby code block. If you absolutely must output text within a non-output code block (i.e., <% %>), you can use the concat method.

So you can define a helper like this:
def my_method
  if some_condition
    concat "Something or other"
  else
    concat "Something else"
  end
end

And then use it in a non-output block:
<% my_method %>


text:
Q: Table and graph do not align The table and graph are not vertically aligned and I don't know how to fix it. Any suggestions?
\begin{tabular}{|c|c|} \hline
    $x$     &   $y$ \\ \hline
    $-2$    &   $-5$    \\ \hline
    $-1$    &   $-3$    \\ \hline
    $0$ &   $-1$    \\ \hline
    $1$ &   $1$ \\ \hline
    $2$ &   $3$ \\ \hline
    $3$ &   $5$ \\ \hline
\end{tabular}
\hspace{5cm}
\begin{tikzpicture}[scale=.3]
    \begin{scope}
        \clip (-10,-20) rectangle (10,0);
        \draw[step=2cm,gray,very thin]
            (-12,-22) grid (10,0);
    \end{scope}
    \draw [<->] (-11,-10) -- (11,-10);
    \draw [<->](0,-21) -- (0,1);
    \clip (-10,-20) rectangle (10,0);
\end{tikzpicture}

A: You can use the t option for tabular and (current bounding box.base) for baseline= in the tikzpicture:
\documentclass{article}
\usepackage{tikz}

\begin{document}

\begin{tabular}[t]{|c|c|} \hline
    $x$     &   $y$ \\ \hline
    $-2$    &   $-5$    \\ \hline
    $-1$    &   $-3$    \\ \hline
    $0$ &   $-1$    \\ \hline
    $1$ &   $1$ \\ \hline
    $2$ &   $3$ \\ \hline
    $3$ &   $5$ \\ \hline
\end{tabular}%
\hspace{5cm}%
\begin{tikzpicture}[baseline=(current bounding box.base),scale=.3]
    \begin{scope}
        \clip (-10,-20) rectangle (10,0);
        \draw[step=2cm,gray,very thin]
            (-12,-22) grid (10,0);
    \end{scope}
    \draw [<->] (-11,-10) -- (11,-10);
    \draw [<->](0,-21) -- (0,1);
    \clip (-10,-20) rectangle (10,0);
\end{tikzpicture}

\end{document}

Notice the character % that I added twice to remove spurious blank spaces. Perhaps instead of a hardwired horizontal space you could use \hfill.


text:
Q: Application identity authentication in Azure Mobile app. How? I'm using custom authentication with Azure Mobile App based on following this article.
Client application is Cordova App
Steps I did:

*

*Turn on App Service Authentication

*Add Microsoft.Azure.Mobile.Server.Login NuGet package

*Create custom authentication endpoint

*Configure service to require authentication

*Use token on client

And it works fine with [Authorize] attribute on action methods/controllers.
But Username/password authentication is not enough for me. What I want is make sure that only my mobile application (client) can use Mobile App hosted on Azure endpoint and no one else from the web (in addition to username/password). So some sort of app_id need to be verified on both side, probably based on some sort of hash-based message authentication.
All articles I found describes either custom authentication with username/password or via Azure AD tenant. But one breaks other, moreover I don't need Azure AD.
How I can achieve this? Is there some built-in methods?

A: App Service doesn't provide any built-in support for this when using custom authentication. The closest thing would be to use Azure Active Directory (AAD) service principal authentication. AAD supports app identities and you'd be able to check the identity of the app in the signed token at login time. However, you wouldn't be able to use custom username/password.
Otherwise, I think your best bet is to have some shared secret on both the client and the server to verify that it is only your app accessing the service. However, this is not considered a safe practice. Anyone who downloads your mobile app could theoretically extract this secret and use it from any app they want, so this is not recommended if you need to restrict access for security reasons.


text:
Q: "...focuses on the person's individual
motivation to pursue skills,..." I read a sentence on a video but am not sure what does "motivation" means in it.
Does it mean "enthusiasm for doing something" or "the need or reason for doing something" in the following sentence?

Some of the principles behind IE, intellectual entrepreneurship,
specifically its intellectual aspect, focuses on the person's
individual
motivation to pursue skills, expertise, and knowledge in one area, the development of what I call
the "unique intellectual capital", the individual's set of knowledge.

A: To motivate means: make someone want to do something.
I will give an example:

I am hungry. I am motivated to eat. My hunger motivates me to eat. The grocery store is far away. I do not want to walk to the store, so I am motivated to ride my bike. The far distance motivates me to ride my bike.

Another example, for your specific sentence:

I want to get a better job, so I will learn new skills. I am motivated to learn new skills. I have motivation to learn new skills, because I will get a better job. I have a motivation to learn new skills because it will be good for me. The potential for a new job motivates me to learn new skills.


text:
Q: Arqade have reset my reputation. What shall I do? I've lost my reputation on Arqade Stack Exchange. When I went onto another Stack Exchange, it worked but when I went back, everything disappeared: the reputation, the badges, the questions and the answers. I've searched and I haven't found an answer. Can anybody give me an answer?

As you can see, it's replaced me with "user251621"

A: I'm a moderator over at Arqade, but I'm unable to get into the specifics here for privacy reasons. I've sent you a private message to your account over on Arqade.


text:
Q: Hibernate BeanCreationException when using @entity I'm making tables in my PostgreSQL database using Hibernate. I have a class user, from which some other classes like student inherit using @inheritance. When I don't use @Entity, all the tables are created like they should, but when I use @Entity, none of the tables get made, and I get the following error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.ClassCastException: class org.hibernate.mapping.SingleTableSubclass cannot be cast to class org.hibernate.mapping.RootClass (org.hibernate.mapping.SingleTableSubclass and org.hibernate.mapping.RootClass are in unnamed module of loader 'app')
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:732) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:414) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) ~[spring-boot-2.6.3.jar:2.6.3]
    at com.example.MasterproofTool.MasterproefToolApplication.main(MasterproefToolApplication.java:10) ~[classes/:na]
Caused by: java.lang.ClassCastException: class org.hibernate.mapping.SingleTableSubclass cannot be cast to class org.hibernate.mapping.RootClass (org.hibernate.mapping.SingleTableSubclass and org.hibernate.mapping.RootClass are in unnamed module of loader 'app')
    at org.hibernate.cfg.annotations.PropertyBinder.bind(PropertyBinder.java:214) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.cfg.annotations.PropertyBinder.makePropertyValueAndBind(PropertyBinder.java:205) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:2319) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.cfg.AnnotationBinder.processIdPropertiesIfNotAlready(AnnotationBinder.java:967) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:792) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl.processEntityHierarchies(AnnotationMetadataSourceProcessorImpl.java:225) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess$1.processEntityHierarchies(MetadataBuildingProcess.java:239) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:282) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1460) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1494) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.15.jar:5.3.15]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.15.jar:5.3.15]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3.15.jar:5.3.15]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-5.3.15.jar:5.3.15]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.15.jar:5.3.15]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.15.jar:5.3.15]
    ... 16 common frames omitted

I have searched for an answer on the internet, but haven't found anything. The solution probably isn't that hard, but I can't seem to find it.


text:
Q: Some Errors while trying to BULK-INSERT I have a text file, which contains these infos:
1,Blabla,Bla,Munich, Entwickler
2,artin,Rosner,Chemnitz,Entwickler
3,Sebastian, Leuoth, Berlin ,Manager
4,bizbiz, bazbaz, Kulalampur, Student

I would like to use BULK insert, with a format file. I have generetade my format file with bcp as follows:
C:\Windows\system32>bcp test.dbo.DimensioList format nul -Uuser1 -Puser1 -n
-f "C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\Listfor
mat.fmt"

If I run this code:
INSERT INTO DimensioList
SELECT *
FROM
OPENROWSET(BULK 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\List.txt', FORMATFILE='C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\Listformat.fmt') as e

I am getting these errors:
   Msg 4866, Level 16, State 1, Line 2
    The bulk load failed. The column is too long in the data file for row 1, column 2. Verify that the field terminator and row terminator are specified correctly.
    Msg 7399, Level 16, State 1, Line 2
    The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error.
    Msg 7330, Level 16, State 2, Line 2
Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)".

by the way, my format file look like this:
11.0
5
1       SQLINT              0       4       ""   1     EID                  ""
2       SQLCHAR             2       20      ""   2     Vorname              Latin1_General_CI_AS
3       SQLNCHAR            2       40      ""   3     Nachname             Latin1_General_CI_AS
4       SQLCHAR             2       20      ""   4     Stadt                Latin1_General_CI_AS
5       SQLCHAR             2       20      ""   5     Beruf                Latin1_General_CI_AS

what do you mean, what should I do to solve this problem?

A: i prefer using XML-Format Files, you could try a format file like this:
(this is for files where your fields have fixed length - you can easily adopt this to variable length with terminator...)
<?xml version="1.0"?>
<BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <RECORD>
    <FIELD ID="1" xsi:type="CharFixed" LENGTH="4"/>
    <FIELD ID="2" xsi:type="CharFixed" LENGTH="20"/>
    <FIELD ID="3" xsi:type="CharFixed" LENGTH="40"/>
    <FIELD ID="4" xsi:type="CharFixed" LENGTH="20"/>
    <FIELD ID="5" xsi:type="CharTerm" TERMINATOR="\r\n"
 </RECORD>
 <ROW>
  <COLUMN SOURCE="1" NAME="EID" xsi:type="SQLSMALLINT"/>
  <COLUMN SOURCE="2" NAME="Vorname" xsi:type="SQLNVARCHAR"/>
  <COLUMN SOURCE="3" NAME="Nachname" xsi:type="SQLNVARCHAR"/>
  <COLUMN SOURCE="4" NAME="Stadt" xsi:type="SQLNVARCHAR"/>
  <COLUMN SOURCE="5" NAME="Beruf" xsi:type="SQLNVARCHAR"/>
 </ROW>
</BCPFORMAT>

Save this as Listformat.xml and you this instead in of Listformat.fmt


text:
Q: Spark Scala data frames grades classifying Hello I have original data like 1 I want to add a column based in a break point of 80 as a pass grade and the results should be as 2. I am using sqlContext.read.format("com.databricks.spark.csv") to read the original data. any help!

A: using .withColumn() will work as expected:
val resultUDF = udf( (total: Int) => if(total >= 80) "pass" else "fail")
df.withColumn("result", resultUDF($"total"))


text:
Q: Can't retrieve cookie value in PHP I stuck this code at the top of my login page which should redirect the user back to the home page if they are already logged in, but it doesn't work, it simply does nothing, even though I know the cookies has been set. To be extra sure the cookie had been set I went into chrome settings and checked all the cookies that my website has stored and sure enough, my cookie was set there. I have no idea why this isn't working, it's probably just a silly little error I made, but I've been programming all night, and I figure a fresh set of eyes might spot something I might have missed.
Code:
<?php
    if(isset($_COOKIE['user'])){
        header("Location: index.php?content=home");
    }
?>

How the cookie is assigned:
<?php
$user = $_POST['user'];
$pass = $_POST['pass'];

$redir = $_GET['redir'];

include('con.php');

$query = mysql_query("SELECT * FROM users WHERE name='{$user}'");
$numrows = mysql_num_rows($query);
$array = mysql_fetch_array($query);

if($user==""||$pass==""){
    header('Location: ../login.php?error=Please fill out EVERYTHING&redir=' . $redir);
}

else if($numrows < 1){
    header('Location: ../login.php?error=User does not exist&redir=' . $redir);
}

else if($pass !=$array['pass']){
    header('Location: ../login.php?error=Invalid user/pass combo&redir=' . $redir);
}

else{
    setcookie("user", $array['ID']);
    header('Location: ../index.php?content=' . $redir);
}

?>
EDIT: Below  is what i am getting when i   print_r($_COOKIE)
Array
(
    [_okbk] => cd4=true,vi5=0,vi4=1381557924453,vi3=active,vi2=false,vi1=false,cd8=chat,cd6=0,cd5=away,cd3=false,cd2=0,cd1=0,
    [_ok] => 5197-288-10-3215
    [olfsk] => olfsk8855679365806282
    [wcsid] => aqVZBde4DlLmegpG5L3JS16nDXl0aIA9
    [hblid] => oBSPj2E8hdamA4nK5L3JS16nDXrqAaPK
    [_oklv] => 1381563654520,aqVZBde4DlLmegpG5L3JS16nDXl0aIA9
)

A: You are setting cookie for 0 seconds like setcookie("user", $array['ID']);. 3rd parameter in setcookie is $expire and by default it is =0.
setcookie("user", $array['ID'], 3600, '/'); # set cookie for 1 hour and for whole domain


text:
Q: C++11 standard conformant bitmasks using enum class Can you implement standard conformant (as described in 17.5.2.1.3 of the n3242 draft) type safe bitmasks using enum class? The way I read it, a type T is a bitmask if it supports the |,&,^,~,|=,&= and ^= operators and further you can do if(l&r) where l and r are of type T. Missing from the list are the operator != and == and to allow sorting one probably also wants to overload <.
Getting the operators to works is just annoying boilerplate code but I do not see how to do if(l&r). At least the following does not compile with GCC (besides being extremely dangerous as it allows an erroneous implicit conversion to int):
enum class Foo{
    operator bool(){
        return (unsigned)*this;
    }
};

EDIT: I now know for certain that enum classes can not have members. The actual question how to do if(l&r) remains though.

A: Scoped enumerations (those created with either enum class or enum struct) are not classes. They cannot have member functions, they just provide enclosed enumerators (not visible at namespace level).

A:
Missing from the list are the operator != and ==

Those operators are already supported by enumeration types, integer types and std::bitset so there's no need to overload them.

and to allow sorting one probably also wants to overload <.

Why do you want to sort bitmasks?  Is (a|b) greater than (a|c)?  Is std::ios::in less than std::ios::app? Does it matter? The relational operators are always defined for enumeration types and integer types anyway.
To answer the main question, you would implement & as an overloaded non-member function:
Foo operator&(Foo l, Foo r)
{
    typedef std::underlying_type<Foo>::type ut;
    return static_cast<Foo>(static_cast<ut>(l) & static_cast<ut>(r));
}

I believe all the required operations for bitmask types could be defined for scoped enums, but not the requirements such as

Ci & Cj is nonzero and Ci & Cj iszero

and:

The value Y is set in the object X is the expression X & Y is nonzero.

Since scoped enums don't support impicit conversion to integer types, you cannot reliably test if it's nonzero or not.  You would need to write if ((X&Y) != bitmask{}) and I don't think that's the intention of the committee.
(I initially thought they could be used to define bitmask types, then remembered I'd tried to implement one using scoped enums and encountered the problem with testing for zero/nonzero.)
Edit: I've just remembered that std::launch is a scoped enum type and a bitmask type ... so apparently scoped enums can be bitmask types!

A: I think you can...
You'll have to add operators for bitmasky things.  I didn't do it here but you could easily overload any relational operator.
  /**
   *
   */
  // NOTE: I changed to a more descriptive and consistent name
  //       This needs to be a real bitmask type.
  enum class file_permissions : int
  {
    no_perms        = 0,

    owner_read      =  0400,
    owner_write     =  0200,
    owner_exe       =  0100,
    owner_all       =  0700,

    group_read      =   040,
    group_write     =   020,
    group_exe       =   010,
    group_all       =   070,

    others_read     =    04,
    others_write    =    02,
    others_exe      =    01,
    others_all      =    07,

    all_all     = owner_all | group_all | others_all, // 0777

    set_uid_on_exe  = 04000,
    set_gid_on_exe  = 02000,
    sticky_bit      = 01000,

    perms_mask      = all_all | set_uid_on_exe | set_gid_on_exe | sticky_bit, // 07777

    perms_not_known = 0xffff,

    add_perms       = 0x1000,
    remove_perms    = 0x2000,
    symlink_perms   = 0x4000
  };

  inline constexpr file_permissions
  operator&(file_permissions x, file_permissions y)
  {
    return static_cast<file_permissions>
      (static_cast<int>(x) & static_cast<int>(y));
  }

  inline constexpr file_permissions
  operator|(file_permissions x, file_permissions y)
  {
    return static_cast<file_permissions>
      (static_cast<int>(x) | static_cast<int>(y));
  }

  inline constexpr file_permissions
  operator^(file_permissions x, file_permissions y)
  {
    return static_cast<file_permissions>
      (static_cast<int>(x) ^ static_cast<int>(y));
  }

  inline constexpr file_permissions
  operator~(file_permissions x)
  {
    return static_cast<file_permissions>(~static_cast<int>(x));
  }

  inline file_permissions &
  operator&=(file_permissions & x, file_permissions y)
  {
    x = x & y;
    return x;
  }

  inline file_permissions &
  operator|=(file_permissions & x, file_permissions y)
  {
    x = x | y;
    return x;
  }

  inline file_permissions &
  operator^=(file_permissions & x, file_permissions y)
  {
    x = x ^ y;
    return x;
  }

A: A short example of enum-flags below.
#indlude "enum_flags.h"

ENUM_FLAGS(foo_t)
enum class foo_t
    {
     none           = 0x00
    ,a              = 0x01
    ,b              = 0x02
    };

ENUM_FLAGS(foo2_t)
enum class foo2_t
    {
     none           = 0x00
    ,d              = 0x01
    ,e              = 0x02
    };

int _tmain(int argc, _TCHAR* argv[])
    {
    if(flags(foo_t::a & foo_t::b)) {};
    // if(flags(foo2_t::d & foo_t::b)) {};  // Type safety test - won't compile if uncomment
    };

ENUM_FLAGS(T) is a macro, defined in enum_flags.h (less then 100 lines, free to use with no restrictions).

A: I'm not entirely sure what your acceptance criteria are, but you can just make operator & return a wrapper class with appropriate conversions and an explicit operator bool:
#include <type_traits>

template<typename T> using Underlying = typename std::underlying_type<T>::type;
template<typename T> constexpr Underlying<T>
underlying(T t) { return Underlying<T>(t); }

template<typename T> struct TruthValue {
    T t;
    constexpr TruthValue(T t): t(t) { }
    constexpr operator T() const { return t; }
    constexpr explicit operator bool() const { return underlying(t); }
};

enum class Color { RED = 0xff0000, GREEN = 0x00ff00, BLUE = 0x0000ff };
constexpr TruthValue<Color>
operator&(Color l, Color r) { return Color(underlying(l) & underlying(r)); }

All your other operators can continue to return Color, of course:
constexpr Color
operator|(Color l, Color r) { return Color(underlying(l) | underlying(r)); }
constexpr Color operator~(Color c) { return Color(~underlying(c)); }

int main() {
    constexpr Color YELLOW = Color::RED | Color::GREEN;
    constexpr Color WHITE = Color::RED | Color::GREEN | Color::BLUE;
    static_assert(YELLOW == (WHITE & ~Color::BLUE), "color subtraction");
    return (YELLOW & Color::BLUE) ? 1 : 0;
}


text:
Q: Handle the result of procedure A in procedure B I have procedure A, which has some in and out parameters. I can't change parameters or code of first procedure, but I need to get different result. I decided to create procedure B, which will pass additional parameter. I want to call procedure A from this procedure and handle result of procedure A in it. I know type of parameters, which procedure A returns.
I need somethink like this:
procedure A(id in number, names out names_array) is
begin
    // procedure A body
    // filling names var
end;

procedure B (id in number, myLimit in number, names out names_array) is
    temp_names names_array;
    i integer;
begin
    A(id => id, names => temp_names);
    while i < myLimit loop
        names(i) := temp_names(i);
    end loop;
end;

So the problem is in handling names (the result of procedure A). How I can do this correctly? Maybe with some select ... limit myLimit query?
Definition of names_array:
 TYPE names_array IS TABLE OF VARCHAR2 (40)
      INDEX BY BINARY_INTEGER;


text:
Q: Puppet and Windows directory permissions I can't believe how difficult puppet is being with Windows - particularly windows permissions!  I have a very simple pp file that I'm trying to execute:
case $operatingsystem {

...

'Windows': {
        file { 'c:/puppet/':
            ensure => directory,
            owner  => 'myUser',
            group  => 'Administrators',
            mode   => '0777',
        }
    }
}

This seems as simple as it could get - create a directory called "c:\puppet" and let everyone have access - IT'S NOT WORKING!  It creates a directory, but nobody has ANY permissions (except special permissions).  I am in the administrators group, so I can delete it and access it, but I want to drop stuff inside and be able to install from there (since apparently an "http" source doesn't work directly on Windows ...).
Is ANYONE else using puppet for Windows, or am I just using the wrong tool for this job?  I am getting very frustrated, and the documentation seems reasonable, but without simple examples of how I'm trying to use puppet I'm getting completely stuck.

A: have you checked out
https://forge.puppetlabs.com/puppetlabs/acl
from their docs you can do something like..
acl { 'c:/puppet':
   permissions => [
   { identity => 'Administrator', rights => ['full'] },
   { identity => 'myuser', rights => ['read','execute'] }
   owner => 'myuser',
 ],
}

A: I've come up with a solution that seems to be systems administration by blunt force trauma:
exec { 'fix_acls':
    command => 'cmd.exe /c "takeown /r /f c:\puppet && icacls c:\puppet /grant SYSTEM:(OI)(CI)F myUser:(OI)(CI)F /T"',
    path    => $::path,
}

This gives myUser and SYSTEM access, I could also do this with USERS in general I think, but it seems there must be a better way.


text:
Q: How to use different parameter to rerun a test case if the first test is failed I use rerunfailures to rerun test case if it was failed, my question is how to use different parameter when rerun.
e.g. I want to test receiving a message from the mailbox, the default mailbox is Gmail, then I failed to receive a message in Gmail, the case will be rerun, but this time I want to use yahoo account to test.
Is there a way I can do this?


text:
Q: How can i get a specific image with python? I want to get artwork of the day image from wwww.wikiart.org
I tried this code:
from urllib import request
from bs4 import BeautifulSoup
from datetime import datetime as dt
import requests,os

def get_image():
    res=requests.get('https://www.wikiart.org/')
    soup=BeautifulSoup(res.text,"lxml")
    image=soup.find('a',{'class':'cursor_zoom'}).find('img')
    link=image.get('src')
    return link

def download():
    link=get_image()
    file_name = dt.now().strftime("%Y-%m-%d")
    user = os.getenv('USER')
    path='/home/'+user+'/Pictures/ArtWallpapers'
    full_path=os.path.join(path,file_name)

    if not os.path.exists(path):
        os.mkdir(path)

    with open(full_path, 'wb') as f:
        f.write(request.urlopen(link).read())
    return full_path

def change_wall():
    full_path=download()
    os.system("/usr/bin/gsettings set org.gnome.desktop.background picture-uri file:///"+full_path)

change_wall()

Then I failed, it says "AttributeError: 'NoneType' object has no attribute 'find'" What should i do in order to fix it?


text:
Q: Theil-Sen estimation, more than one independent variable Is the Theil-Sen estimation in robust regression only limited to a two dimensional problem or can you use it for more than one independent variable as well?

A: There have been a number of proposals for extending Theil-Sen estimation to multiple regression contexts.
I'll point to a couple:
1)
Zhou, W. and R. Serfling (2007),
Multivariate Spatial U-Quantiles: a Bahadur-Kiefer
Representation, a Theil-Sen Estimator for Multiple
Regression, and a Robust Dispersion Estimator,
Journal of Statistical Planning and Inference, May
see here

2)
Wang, X., X. Dang, H. Peng, and H. Zhang (2009),
The Theil-Sen Estimators in a Multiple Linear Regression Model
see here or here (different versions)

The first is based on extending univariate U-quantiles to multivariate U-quantiles, and the second is based on a multivariate median.


text:
Q: Conditional Probability practice exam question verification disease test
A certain clinical test is 98% effective in detecting a disease when
  the disease is in fact present. However, the test also shows a false
  positive in 1% of cases where the patient tested is in fact healthy.
  If 0.4% of the population actually suffers from the disease, what is
  the probability that a person who tests positive actually has the
  disease?

I would like to know how to do it in the way shown if my answer is incorrect as that is what we are asked to do in the exam. In other words we are not allowed to blow the population up by *1000.
P(B) = population who has the disease
P(B1) = .004
P(B2) = Population that does not have the disease but test positive
P(B2) = 1 − P(B1) = .996
P(A) Test is positive
P(A|B1) = .98
P(A|B2) = .01
Then
(.996∗.004)/(.996∗.004)+(.996∗.01)
= 27 (.28)
This figure seems off to me, it seems to good to be true if the test is positive you actually have the disease 28% of the time.
Are my calculations correct or did I miss something?

A: $H$=person is healthy
$T$=person is tested positive
You want to calculate $P(H^c|T)$
We have $$P(T|H^c)=0.98$$ $$P(T|H)=0.01$$ and $$P(H)=0.996$$
Using conditional probability definition,
$$P(H^c|T)=\frac{P(T\cap H^c)}{P(T)}=\frac{P(T|H^c)P(H^c)}{P(T)}$$
Total probability gives :
$$P(T)=P(T \cap H)+P(T\cap H^c)=P(T | H)P(H)+P(T| H^c)P(H^c)$$
Replacing, we have
$$P(H^c|T)=\frac{P(T|H^c)P(H^c)}{P(T | H)P(H)+P(T| H^c)P(H^c)}=\frac{0.98*0.004}{0.01*0.996+0.98*0.004} \approx 28.24\%$$
Now you can understand why $1\%$ false positive is unacceptable


text:
Q: trigger computed to be recalculated when observableArray element property is changed I have observableArray with elements (elements are not observables, but some unobservable objects). I have also computed variable that depands on observableArray. If I push elements into array, then everything works (I mean - computed variable is recalculated).
However, if I change some properties of observableArray single items, then computed is not recalculated:
var myObsArr = ko.observableArray();

// myObsArr is loaded using ko.mapping.fromJS with data from server
// but I am using custom mapping that won't create observables for observableArray items, part of my custom mapping (the one that corresponds to observable item) is something like this:
 create: function (options) {
    // here are some manipulations and
    return ko.toJS(options.data); //doesn't create observables for observableArry items
}

var computedArr = ko.computed(function() {
   var t = self.myObsArr();
   // do manipulations on t and return manipulated array
});

// later I need to change some elements of observable array, for example:
myObsArr[0].Month = "Mar"; //doesn't trigger computed to be recalculated

How to trigger computed to be recalculated when any object inside observable array is changed?

A: You can call valueHasMutated method on your myObsArr after modifying one of its elements. It will trigger the knockout dependency tracking and your computedArr will be notified about the change:
myObsArr[0].Month = "Mar";
myObsArr.valueHasMutated();

However you have to remember to call this every time you change an item in array so you are probably better to turn your Month into an ko.observable because in this case the ko change tracking will pick the changes automatically and it will notify your computed without any additional code.


text:
Q: Is this NFA correct? First time doing this! I have recently learned how to make DFA and NFA. For an assignment, I had the following question:
Draw the state diagram for an automaton accepting language L1 over alphabet
A = {a, b} from the previous homework. L1 is the set of all words w ∈ A∗
such that w contains
either only a's or only b's.
I created this state diagram in Latex. Can you guys see if this is correct? (I have no idea how to add the actual output of this code)
starting state: q0
final state: q4
1:

A: No, this in incorrect. The language this parses is the language of all strings that end in $b$.
Here's the DFA I'd use (it only has $4$ states, vs your NFA turned DFA would have $32$ states):
$\Sigma=\{a,b\}$
$Q=\mathcal P(\Sigma)$ ($\mathcal P$ is the power set).
$\delta(q,s)=\{s\}\cup q$
$q_0=\varnothing$
$F=\{\varnothing,\{a\},\{b\}\}$.
To check whether this is optimal, consider the regular expression for this language, $a^*+b^*$, and its derivatives.
$$D_\varepsilon(a^*+b^*)=a^*+b^*$$
$$D_a(a^*+b^*)=a^*$$
$$D_b(a^*+b^*)=b^*$$
$$D_{ab}(a^*+b^*)=\varnothing$$
Since there are at least $4$ distinct derivatives, this is optimal.
Edit:
For OP's new question, as I noted above, the presented NFA parses the language of strings ending with $b$.
Here's a DFA that solves the problem (DFAs are also NFAs)
$Q=\{0,a,b\}$
$\delta(q,c)=\begin{cases}a&c=a\\0&c=b\text{ and }q\neq a\\b&c=b\text{ and }q=a\end{cases}$
$q_0=0$
$F=\{b\}$.


text:
Q: What is the workaround for unstable library feature "core" issue? I am trying to add big integers together in Rust:
extern crate core;
use core::ops::Add;
use num::bigint::{BigInt};
use num::integer::Integer;
...
let mut big = "8705702225074732811211966512111".parse::<BigInt>().unwrap();
let one = "1".parse::<BigInt>().unwrap();
big = big.add(&one);

I got the following error:
src\main.rs:3:1: 3:19 error: use of unstable library feature 'core': the libcore library has not yet been scrutinized for stabilization in terms of structure and naming (see issue #27701)
src\main.rs:3 extern crate core;

Is there any workaround at this time? or is this entirely not doable for the time being?

A: You should be able to use the std::ops::Add trait instead of core::ops::Add.
use std::ops::Add;


text:
Q: Finding number of 'p' tags and iterate through them to scrape the underlying text using php So i don't have any idea about how I can scrape the underlying text of a paragraph from a website page, Which does not have any 'id' or 'class' using php.
One of the way is to count and iterate through the  tags in a , but the div itself gets closed before any  tags are encountered.
I intend to scrape wikitravel.org info in order to learn scraping.
Here is one of the example of the page source of wikitravel.org

[edit][add listing] Sleep

There are numerous hotels, residencies etc. in and around Kanyakumari and therefore, staying over is not be a problem. But there are agents, touts and brokers in every nook and corner looking for unsuspecting tourists. Eschew buying or booking rooms from them, as many a time you end up paying a lot more than the actual price. Vivekananda Kendra can be a good option for people looking for a decent, yet cheap accommodation, but it's around 3 km from Kanyakumari. Prefer hotels near the beach especially if you want to watch the sunrise right out of your bed! Note that, you should quote this preference when booking the room or else, you'll always be given a room without a window opening out to the sea. Moreover many a times, these rooms are in great demand and you'll find yourself shelling a extra 400 - 500 Rs (~10 US$)for such a room. Hotel Sea View, Hotel Sangam and a couple of other hotels offer such rooms and the rent is about Rs. 1100 (~ 25 US$) for 12 hrs. Note that many rooms are priced for 12 hrs  and not per day especially during the peak season.

ATM's in Kanyakumari:

Canara Bank
 Main Road, Kanyakumari 629702, ,

Indian Bank
  S No 658 / 1, National High Way Opp St Antony'S Higher Secondary Sckanyakumari 629702

State Bank Of Travancore
P.B.No.1, 1/17 Amman Sannathi Street, Kanyakumari, Tamil Nadu, 629702

can anybody help?
thanks in advance!

A: I've always found JQuery the best way to scrape HTML data. Have the PHP render out a page with JQuery which parses the scraped HTML then posts a JSON dataset back to the PHP.
If you want to stick with the pure PHP route try out a library along the lines of: http://simplehtmldom.sourceforge.net/

A: Take a look at simplehtmldom parser. It is supposed to work with jQuery-like selectors.
Here is an example for your case:
$html = file_get_html('http://www.wikitravel.com/yourpage');
foreach($html->find('p') as $element){
    echo $element->innertext; // the content in all the p tags
}


text:
Q: How to change the citation style for one citation for my bachelor thesis I want to improve my work with a citation in the beginning. How could I do this to make it look like this

Thanks in advance!
EDIT 1 : MWE
Okay this is a MWE which hopefully helps to answear the question. The MWE reference should be look like the one in the image.
\documentclass[12pt,a4paper,onecolumn,oneside,draft=on]{article}
\usepackage[left=4cm,right=2cm,top=2cm,bottom=2cm]{geometry}
\usepackage[onehalfspacing]{setspace}
\usepackage[english,ngerman]{babel}
\usepackage[T1]{fontenc}
\usepackage[ansinew]{inputenc}
\usepackage{titlesec}
\usepackage[nottoc]{tocbibind}
\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{float}
\usepackage[backend=biber,bibencoding=utf8,natbib=true,style=apa]{biblatex}
\addbibresource{Reftester.bib}
\usepackage{subcaption}
\usepackage{pdfpages}

\newtheorem{theorem}{Theorem}
\newtheorem{acknowledgement}[theorem]{Acknowledgement}
\newtheorem{algorithm}[theorem]{Algorithm}
\newtheorem{case}[theorem]{Case}
\newtheorem{claim}[theorem]{Claim}
\newtheorem{conclusion}[theorem]{Conclusion}
\newtheorem{condition}[theorem]{Condition}
\newtheorem{conjecture}[theorem]{Conjecture}
\newtheorem{corollary}[theorem]{Corollary}
\newtheorem{criterion}[theorem]{Criterion}
\newtheorem{definition}[theorem]{Definition}
\newtheorem{example}[theorem]{Example}
\newtheorem{exercise}[theorem]{Exercise}
\newtheorem{lemma}[theorem]{Lemma}
\newtheorem{notation}[theorem]{Notation}
\newtheorem{problem}[theorem]{Problem}
\newtheorem{proposition}[theorem]{Proposition}
\newtheorem{remark}[theorem]{Remark}
\newtheorem{solution}[theorem]{Solution}
\newtheorem{summary}[theorem]{Summary}
\newenvironment{proof}[1][Proof]{\noindent\textbf{#1.} }{\ \rule{0.5em}    {0.5em}}
\makeatletter
\def\@biblabel#1{\hspace*{-\labelsep}}
\makeatother
\makeatletter
\renewcommand{\@cite}[1]{#1}
\makeatother
\setlength{\parindent}{0 cm}
\setlength{\parskip}{6 pt}
\setcounter{tocdepth}{100}
\begin{document}
"This is a famous reference and should be higlighted as in the picture of this post."  \citet{Mokyr1999}

\printbibliography[ title={7 References}]

\end{document}

EDIT 2 : Bibtex Entry for MWE
@InBook{Mokyr1999,
chapter   = {The New Economic History and the Industrial Revolution.},
pages     = {1--127},
title     = {The British Industrial Revolution: An Economic Perspective},
publisher = {Boulder: Westview.},
year      = {1999},
author    = {Mokyr, Joel},
editor    = {Mokyr, Joel},
edition   = {2nd. ed.},
}

A: This answer only focusses on the citation aspect of the desired output. For nice formatting of the quotation itself, have a look at "Inspirational" quote at start of chapter and the many linked questions.
It is not entirely clear to me what citations of entry types other than @inbook should look like here. I extrapolated, but this will need adjustments.
We simply define a new citation command called \fancyquotecite that you can use instead of the usual \cite, \textcite, etc. \fancyquotecite is fuelled by the bibliography macro fancyquotecite and prints the labelname (the primary name associated with the work/entry, usually the author or editor) and the titles.
\documentclass[12pt,a4paper,onecolumn,oneside]{article}
\usepackage[english,ngerman]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{csquotes}

\usepackage[backend=biber, style=apa]{biblatex}

\DeclareCiteCommand{\fancyquotecite}
  {\usebibmacro{prenote}}
  {\usebibmacro{citeindex}%
   \usebibmacro{fancyquotecite}}
  {\multicitedelim}
  {\usebibmacro{postnote}}

\newbibmacro{fancyquotecite}{%
  \printnames[given-family]{labelname}%
  \setunit{\addcomma\space}%
  \printfield{maintitle}%
  \setunit{\addcomma\space}%
  \printfield{booktitle}%
  \setunit{\addcomma\space}%
  \printfield{title}%
}

\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}
@InBook{Mokyr1999,
  title        = {The New Economic History and the Industrial Revolution},
  pages        = {1--127},
  booktitle    = {The British Industrial Revolution},
  booksubtitle = {An Economic Perspective},
  publisher    = {Westview},
  location     = {Boulder},
  year         = {1999},
  author       = {Mokyr, Joel},
  editor       = {Mokyr, Joel},
  edition      = {2},
}
\end{filecontents}
\addbibresource{\jobname.bib}

\begin{document}
\fancyquotecite{Mokyr1999}

\printbibliography[heading=bibnumbered]
\end{document}

Please note how I changed the contents of some fields in your .bib file to work better  with biblatex.  Note also that it is a bad idea to include the chapter number in the title to \printbibliography, use heading=bibnumbered instead.


text:
Q: What exactly mean API_DEPRECATED_WITH_REPLACEMENT? What exactly mean API_DEPRECATED_WITH_REPLACEMENT("xxx", ios(4.2, 9.0)) ?

*

*The function is available in 9.0 but marked as deprecated in 9.0 and not exists in 9+ ?

*Or the function is available in 9.0 but marked as deprecated in 9.0 and still exists in 9+ ?

*Or that The function is not available at all in 9.0

Exactly I m concern about this 2 functions :
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options API_AVAILABLE(ios(9.0)); // no equiv. notification. return NO if the application can't open for some reason
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation API_DEPRECATED_WITH_REPLACEMENT("application:openURL:options:", ios(4.2, 9.0)) API_UNAVAILABLE(tvos);

Does I understand well that from ios 9.0 included (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation will not be called anymore and only - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options will be call ?


text:
Q: django daphne ModuleNotFoundError : 'settings' I made a django project using channels.
And I want to deploy it. Because my project uses channels, I should set up ASGI based environment.
I pushed my project and succeeded. So I got URL address.
https://demo-multichat.herokuapp.com
As you can see, Application error occured.
I got log.
$ heroku logs
2017-09-07T06:03:55.893921+00:00 app[worker.1]:     result = connection.blpop(list_names, timeout=self.blpop_timeout)
2017-09-07T06:03:55.893925+00:00 app[worker.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/redis/client.py", line 1269, in blpop
2017-09-07T06:03:55.894950+00:00 app[worker.1]:     return self.execute_command('BLPOP', *keys)
2017-09-07T06:03:55.894954+00:00 app[worker.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/redis/client.py", line 673, in execute_command
2017-09-07T06:03:55.895473+00:00 app[worker.1]:     connection.send_command(*args)
2017-09-07T06:03:55.895477+00:00 app[worker.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/redis/connection.py", line 610, in send_command
2017-09-07T06:03:55.895972+00:00 app[worker.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/redis/connection.py", line 585, in send_packed_command
2017-09-07T06:03:55.895968+00:00 app[worker.1]:     self.send_packed_command(self.pack_command(*args))
2017-09-07T06:03:55.896440+00:00 app[worker.1]:     self.connect()
2017-09-07T06:03:55.896444+00:00 app[worker.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/redis/connection.py", line 489, in connect
2017-09-07T06:03:55.896869+00:00 app[worker.1]:     raise ConnectionError(self._error_message(e))
2017-09-07T06:03:55.896892+00:00 app[worker.1]: redis.exceptions.ConnectionError: Error 111 connecting to localhost:6379. Connection refused.
2017-09-07T06:03:56.097153+00:00 heroku[worker.1]: Process exited with status 1
2017-09-07T06:04:35.728878+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=demo-multichat.herokuapp.com request_id=ae95450d-249f-46e4-af5e-fd69b3339fbd fwd="165.132.5.143" dyno= connect= service= status=503 bytes= protocol=http
2017-09-07T06:04:36.537336+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=demo-multichat.herokuapp.com request_id=5a48b0e9-0fae-46b2-9885-f1a8390b8eb9 fwd="165.132.5.143" dyno= connect= service= status=503 bytes= protocol=http
2017-09-07T06:04:37.170094+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=demo-multichat.herokuapp.com request_id=db7f5507-c748-4ae5-9718-379cacf3e8e1 fwd="165.132.5.143" dyno= connect= service= status=503 bytes= protocol=http
2017-09-07T06:05:50.020700+00:00 app[api]: Scaled to web@1:Free worker@1:Free by user juhyun1849@gmail.com
2017-09-07T06:05:56.482746+00:00 heroku[web.1]: Starting process with command `daphne multichat.asgi:channel_layer`
2017-09-07T06:05:59.257502+00:00 app[web.1]: Traceback (most recent call last):
2017-09-07T06:05:59.257522+00:00 app[web.1]:   File "/app/.heroku/python/bin/daphne", line 11, in <module>
2017-09-07T06:05:59.257631+00:00 app[web.1]:     sys.exit(CommandLineInterface.entrypoint())
2017-09-07T06:05:59.257633+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/daphne/cli.py", line 144, in entrypoint
2017-09-07T06:05:59.257753+00:00 app[web.1]:     cls().run(sys.argv[1:])
2017-09-07T06:05:59.257755+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/daphne/cli.py", line 174, in run
2017-09-07T06:05:59.257875+00:00 app[web.1]:     channel_layer = importlib.import_module(module_path)
2017-09-07T06:05:59.257876+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module
2017-09-07T06:05:59.257982+00:00 app[web.1]:     return _bootstrap._gcd_import(name[level:], package, level)
2017-09-07T06:05:59.257983+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 978, in _gcd_import
2017-09-07T06:05:59.258104+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 961, in _find_and_load
2017-09-07T06:05:59.258179+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
2017-09-07T06:05:59.258250+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
2017-09-07T06:05:59.258318+00:00 app[web.1]:   File "<frozen importlib._bootstrap_external>", line 678, in exec_module
2017-09-07T06:05:59.258403+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
2017-09-07T06:05:59.258472+00:00 app[web.1]:   File "./multichat/asgi.py", line 11, in <module>
2017-09-07T06:05:59.258560+00:00 app[web.1]:     channel_layer = get_channel_layer()
2017-09-07T06:05:59.258561+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/channels/asgi.py", line 115, in get_channel_layer
2017-09-07T06:05:59.258664+00:00 app[web.1]:     django.setup(set_prefix=False)
2017-09-07T06:05:59.258666+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 22, in setup
2017-09-07T06:05:59.258744+00:00 app[web.1]:     configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
2017-09-07T06:05:59.258748+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__
2017-09-07T06:05:59.258867+00:00 app[web.1]:     self._setup(name)
2017-09-07T06:05:59.258869+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup
2017-09-07T06:05:59.258935+00:00 app[web.1]:     self._wrapped = Settings(settings_module)
2017-09-07T06:05:59.258936+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__
2017-09-07T06:05:59.259050+00:00 app[web.1]:     mod = importlib.import_module(self.SETTINGS_MODULE)
2017-09-07T06:05:59.259052+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module
2017-09-07T06:05:59.259136+00:00 app[web.1]:     return _bootstrap._gcd_import(name[level:], package, level)
2017-09-07T06:05:59.259137+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 978, in _gcd_import
2017-09-07T06:05:59.259222+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 961, in _find_and_load
2017-09-07T06:05:59.259287+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 936, in _find_and_load_unlocked
2017-09-07T06:05:59.259356+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
2017-09-07T06:05:59.259438+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 978, in _gcd_import
2017-09-07T06:05:59.259504+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 961, in _find_and_load
2017-09-07T06:05:59.259570+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked
2017-09-07T06:05:59.259643+00:00 app[web.1]: ModuleNotFoundError: No module named 'settings'
2017-09-07T06:05:59.407057+00:00 heroku[web.1]: State changed from starting to crashed
2017-09-07T06:05:59.409405+00:00 heroku[web.1]: State changed from crashed to starting
2017-09-07T06:05:59.392197+00:00 heroku[web.1]: Process exited with status 1
2017-09-07T06:06:04.442747+00:00 heroku[web.1]: Starting process with command `daphne multichat.asgi:channel_layer`
2017-09-07T06:06:06.999728+00:00 app[web.1]: Traceback (most recent call last):
2017-09-07T06:06:06.999748+00:00 app[web.1]:   File "/app/.heroku/python/bin/daphne", line 11, in <module>
2017-09-07T06:06:06.999910+00:00 app[web.1]:     sys.exit(CommandLineInterface.entrypoint())
2017-09-07T06:06:06.999915+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/daphne/cli.py", line 144, in entrypoint
2017-09-07T06:06:07.000097+00:00 app[web.1]:     cls().run(sys.argv[1:])
2017-09-07T06:06:07.000101+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/daphne/cli.py", line 174, in run
2017-09-07T06:06:07.000291+00:00 app[web.1]:     channel_layer = importlib.import_module(module_path)
2017-09-07T06:06:07.000294+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module
2017-09-07T06:06:07.000469+00:00 app[web.1]:     return _bootstrap._gcd_import(name[level:], package, level)
2017-09-07T06:06:07.000667+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 961, in _find_and_load
2017-09-07T06:06:07.000472+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 978, in _gcd_import
2017-09-07T06:06:07.000786+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
2017-09-07T06:06:07.000900+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
2017-09-07T06:06:07.001008+00:00 app[web.1]:   File "<frozen importlib._bootstrap_external>", line 678, in exec_module
2017-09-07T06:06:07.001159+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
2017-09-07T06:06:07.001282+00:00 app[web.1]:   File "./multichat/asgi.py", line 11, in <module>
2017-09-07T06:06:07.001414+00:00 app[web.1]:     channel_layer = get_channel_layer()
2017-09-07T06:06:07.001418+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/channels/asgi.py", line 115, in get_channel_layer
2017-09-07T06:06:07.001585+00:00 app[web.1]:     django.setup(set_prefix=False)
2017-09-07T06:06:07.001588+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 22, in setup
2017-09-07T06:06:07.001725+00:00 app[web.1]:     configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
2017-09-07T06:06:07.001728+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__
2017-09-07T06:06:07.001873+00:00 app[web.1]:     self._setup(name)
2017-09-07T06:06:07.001876+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup
2017-09-07T06:06:07.002020+00:00 app[web.1]:     self._wrapped = Settings(settings_module)
2017-09-07T06:06:07.002024+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__
2017-09-07T06:06:07.002184+00:00 app[web.1]:     mod = importlib.import_module(self.SETTINGS_MODULE)
2017-09-07T06:06:07.002352+00:00 app[web.1]:     return _bootstrap._gcd_import(name[level:], package, level)
2017-09-07T06:06:07.002188+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module
2017-09-07T06:06:07.002355+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 978, in _gcd_import
2017-09-07T06:06:07.002479+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 961, in _find_and_load
2017-09-07T06:06:07.002593+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 936, in _find_and_load_unlocked
2017-09-07T06:06:07.002707+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
2017-09-07T06:06:07.002814+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 978, in _gcd_import
2017-09-07T06:06:07.002923+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 961, in _find_and_load
2017-09-07T06:06:07.003034+00:00 app[web.1]:   File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked
2017-09-07T06:06:07.003154+00:00 app[web.1]: ModuleNotFoundError: No module named 'settings'
2017-09-07T06:06:07.152538+00:00 heroku[web.1]: Process exited with status 1
2017-09-07T06:06:07.168247+00:00 heroku[web.1]: State changed from starting to crashed
2017-09-07T06:06:07.856101+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=demo-multichat.herokuapp.com request_id=f934301e-6f75-43bc-8e2d-76959a638d5c fwd="165.132.5.143" dyno= connect= service= status=503 bytes= protocol=http
2017-09-07T06:06:08.042260+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=demo-multichat.herokuapp.com request_id=cd37f077-714e-4739-abb7-01b8400245aa fwd="165.132.5.143" dyno= connect= service= status=503 bytes= protocol=http
2017-09-07T06:06:08.453060+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=demo-multichat.herokuapp.com request_id=b33103b3-167d-4dea-989c-c19c5e7598ad fwd="165.132.5.143" dyno= connect= service= status=503 bytes= protocol=http

I thought something goes wrong as to Procfile. Below is my Procfile setting.

web: daphne multichat.asgi:channel_layer
worker: python manage.py runworker

In my local terminal, I executed each line.
1st $ python manage.py runworker
2017-09-07 15:12:43,889 - INFO - runworker - Using single-threaded worker.
2017-09-07 15:12:43,889 - INFO - runworker - Running worker against channel layer default (asgi_redis.core.RedisChannelLayer)
2017-09-07 15:12:43,889 - INFO - worker - Listening on channels chat.receive, http.request, websocket.connect, websocket.disconnect, websocket.receive

It is fine. Good.

2nd $ daphne multichat.asgi:channel_layer
Traceback (most recent call last):
  File "/home/juhyun-park/PyVirt/Virt1/bin/daphne", line 11, in <module>
    sys.exit(CommandLineInterface.entrypoint())
  File "/home/juhyun-park/PyVirt/Virt1/lib/python3.6/site-packages/daphne/cli.py", line 144, in entrypoint
    cls().run(sys.argv[1:])
  File "/home/juhyun-park/PyVirt/Virt1/lib/python3.6/site-packages/daphne/cli.py", line 174, in run
    channel_layer = importlib.import_module(module_path)
  File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "./multichat/asgi.py", line 11, in <module>
    channel_layer = get_channel_layer()
  File "/home/juhyun-park/PyVirt/Virt1/lib/python3.6/site-packages/channels/asgi.py", line 115, in get_channel_layer
    django.setup(set_prefix=False)
  File "/home/juhyun-park/PyVirt/Virt1/lib/python3.6/site-packages/django/__init__.py", line 22, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "/home/juhyun-park/PyVirt/Virt1/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__
    self._setup(name)
  File "/home/juhyun-park/PyVirt/Virt1/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup
    self._wrapped = Settings(settings_module)
  File "/home/juhyun-park/PyVirt/Virt1/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 936, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'settings'

I got error messages.

How can I fix this issue?? I need your help.
If you need my project source code, I leave github repository url as comment.