text:
Q: Turtle window doesn't close and shows error " terminator " even with 2 lines of code I am learning about OOP in python and to be specific about turtle module.
Wrote this code and running it shows error " Terminator " ...hope its not the skynet
timmy = Turtle()
print(timmy)
timmy.shape("turtle")
timmy.color("blue")

Output exceeds the size limit. Open the full output data in a text editor
---------------------------------------------------------------------------
Terminator                                Traceback (most recent call last)
Untitled-1.ipynb Cell 1 in <cell line: 4>()
      1 from turtle import Turtle,Screen
----> 4 timmy = Turtle()
      5 print(timmy)
      6 timmy.shape("turtle")

File ~/anaconda3/lib/python3.9/turtle.py:3815, in Turtle.__init__(self, shape, undobuffersize, visible)
   3813 if Turtle._screen is None:
   3814     Turtle._screen = Screen()
-> 3815 RawTurtle.__init__(self, Turtle._screen,
   3816                    shape=shape,
   3817                    undobuffersize=undobuffersize,
   3818                    visible=visible)

File ~/anaconda3/lib/python3.9/turtle.py:2558, in RawTurtle.__init__(self, canvas, shape, undobuffersize, visible)
   2556 self._undobuffersize = undobuffersize
   2557 self.undobuffer = Tbuffer(undobuffersize)
-> 2558 self._update()

File ~/anaconda3/lib/python3.9/turtle.py:2661, in RawTurtle._update(self)
   2659     return
   2660 elif screen._tracing == 1:
-> 2661     self._update_data()
...
-> 1293     raise Terminator
   1294 if self._tracing > 0:
   1295     self._updatecounter += 1

Terminator:

turtle graphics window which doesn't close
If i re-run the program it runs fine
from turtle import Turtle,Screen

timmy = Turtle()
print(timmy)
timmy.shape("turtle")
timmy.color("blue")

timmy.forward(100)
my_screen = Screen()
my_screen.bgcolor("coral")
my_screen.exitonclick()

Error message:
Output exceeds the size limit. Open the full output data in a text editor
---------------------------------------------------------------------------
Terminator                                Traceback (most recent call last)
Untitled-1.ipynb Cell 1 in <cell line: 4>()
      1 from turtle import Turtle,Screen
----> 4 timmy = Turtle()
      5 print(timmy)
      6 timmy.shape("turtle")

File ~/anaconda3/lib/python3.9/turtle.py:3815, in Turtle.__init__(self, shape, undobuffersize, visible)
   3813 if Turtle._screen is None:
   3814     Turtle._screen = Screen()
-> 3815 RawTurtle.__init__(self, Turtle._screen,
   3816                    shape=shape,
   3817                    undobuffersize=undobuffersize,
   3818                    visible=visible)

File ~/anaconda3/lib/python3.9/turtle.py:2558, in RawTurtle.__init__(self, canvas, shape, undobuffersize, visible)
   2556 self._undobuffersize = undobuffersize
   2557 self.undobuffer = Tbuffer(undobuffersize)
-> 2558 self._update()

File ~/anaconda3/lib/python3.9/turtle.py:2661, in RawTurtle._update(self)
   2659     return
   2660 elif screen._tracing == 1:
-> 2661     self._update_data()
...
-> 1293     raise Terminator
   1294 if self._tracing > 0:
   1295     self._updatecounter += 1

Terminator:

Again re-running gives the desired output

A: There is nothing wrong with your code,  Although I might have expressed it differently:
from turtle import Turtle, Screen

my_screen = Screen()
my_screen.bgcolor("coral")

timmy = Turtle()
timmy.shape("turtle")
timmy.color("blue")

timmy.forward(100)

my_screen.exitonclick()

You need to look outside your code for the problem.  In this case, the Anaconda environment.  Try it outside that environment to convince yourself the code works.
Depending on how Anaconda tries to rerun it, there might be a Terminator error as once the turtle environment shuts down after the exitonclick() it cannot be restarted.  The program has to be rerun anew, in a clean image.


text:
Q: Workaround for load local data infile? My web host has upgraded its servers. The newer 5.7.27 version of MySQL that they installed has LOAD DATA LOCAL INFILE disabled by default, resulting in Error 1148 when I try to execute the command. Unfortunately I can't start or stop the MySQL instance as that is under the control of the web host. What are some workarounds or alternate methods that will allow me to import data with the least effort? All the data I want to import are currently in TSV (tab separated value) format, but I could switch to CSV or something else if required. I have Workbench installed as well if it helps.
The problem is basically the same as this one, except I cannot access and reconfigure the server (the selected answer to that question).

A: I'd write a Python script to take your TSV input, and use it to generate INSERT statements in a loop. Each statement would handle perhaps 100-200* new rows. Then it would execute those statements.
Run it on the same server. Do it in a transaction so you don't make a mess on your first few tries if there are errors.
There you have it: TSV import.
* Or, well, whatever you want. Doing them one at a time will be slow (because there is a small overhead associated with the execution of each SQL statement), but you probably can't just dump them all into a single INSERT unless the amount of information is small. Check your server settings/limits, and come up with a reasonable batch size for your use case. For <2000 rows, and reasonably "short" row data, 100-200 rows per statement would usually be appropriate.

Pseudo-code:
batchSize = 100
buffer = []

handleInput():
   for each line in tsvFile:
       data = parse(line)
       add data to buffer
       if size(buffer) > batchSize:
          flushBuffer
   if size(buffer) > batchSize:
      flushBuffer

flushBuffer:
    str = "INSERT INTO tbl (col1, col2, col3) VALUES"
    for each row in buffer:
       if !str.empty():
          str += ","
       str += "(" + row[col1] + ", " + row[col2] + ", " + row[col3];
    executeSqlStatement(str)
    buffer = []

redpajama_set_name: RedPajamaStackExchange


text:
Q: All existing plans or all of existing plans?
Possible Duplicate:
Is "of " necessary in "all of "?

Which one of the following is correct (or preferred if both are grammatical)?

*

*All existing plans.

*All of existing plans.

A: You can say either

... all existing plans

or

... all of the existing plans

but not

... all of existing plans


text:
Q: How to add navigation bar button without using navigation controller from storyboard? I'm having issues adding navigation bar button to a UINavigationBar directly without using UINavigationController.
The way it appears when using with UINavigationController on iPhoneX, is different from what it looks when i directly add an UINavigationBar.
Even if i set the height of navigationBar manually, the background color and bar button still stick to the top.
Using UINavigationBar

After adjusting height or even using SafeAreaInset to set bar height

using UINavigationController -> desired result


text:
Q: Rvest: using css selector pulls data from different tab in URL I am very new to scraping, and am trying to pull data from a section of this website -  https://projects.fivethirtyeight.com/soccer-predictions/premier-league/. The data I'm trying to get is in the second tab, "Matches," and is the section titled "Upcoming Matches."
I have attempted to do this with SelectorGadget and using rvest, as follows -
library(rvest)
url <- ("https://projects.fivethirtyeight.com/soccer-predictions/premier-league/")
url %>%
   html_nodes(".prob, .name") %>%
   html_text()

this returns values, however corresponding to the first tab on the page, "Standings." How can I reference the correct section that I am trying to pull?

A: First:I don't know R but Python.
When you click Matches then page uses JavaScript to generate matches and it loads JSON data from:
https://projects.fivethirtyeight.com/soccer-predictions/forecasts/2021_premier-league_forecast.json
https://projects.fivethirtyeight.com/soccer-predictions/forecasts/2021_premier-league_matches.json
https://projects.fivethirtyeight.com/soccer-predictions/forecasts/2021_premier-league_clinches.json
I checked only one of them - 2021_premier-league_matches.json - and I see it has data for Completed Matches

I made example in Python:
import requests

url = 'https://projects.fivethirtyeight.com/soccer-predictions/forecasts/2021_premier-league_matches.json'

response = requests.get(url)
data = response.json()

for item in data:
    # search date
    if item['datetime'].startswith('2022-03-16'):

        print('team1:', item['team1_code'], '|', item['team1'])
        print('prob1:', item['prob1'])
        print('score1:', item['score1'])
        print('adj_score1:', item['adj_score1'])
        print('chances1:', item['chances1'])
        print('moves1:', item['moves1'])
        print('---')

        print('team2:', item['team2_code'], '|', item['team2'])
        print('prob2:', item['prob2'])
        print('score2:', item['score2'])
        print('adj_score2:', item['adj_score2'])
        print('chances2:', item['chances2'])
        print('moves2:', item['moves2'])

        print('----------------------------------------')

Result:
team1: BHA | Brighton and Hove Albion
prob1: 0.30435
score1: 0
adj_score1: 0.0
chances1: 1.244
moves1: 1.682
---
team2: TOT | Tottenham Hotspur
prob2: 0.43627
score2: 2
adj_score2: 2.1
chances2: 1.924
moves2: 1.056
----------------------------------------
team1: ARS | Arsenal
prob1: 0.22114
score1: 0
adj_score1: 0.0
chances1: 0.569
moves1: 0.514
---
team2: LIV | Liverpool
prob2: 0.55306
score2: 2
adj_score2: 2.1
chances2: 1.243
moves2: 0.813
----------------------------------------


text:
Q: NMinimize error I want to use NMinimize in the following way:
Uni[phi_, psi_,theta_] := {{E^(I*phi)*Cos[theta], E^(I*psi)*Sin[theta]}, {-E^(-I*psi)*Sin[theta], E^(-I*phi)*Cos[theta]}}
LocalUni[a1_, a2_, a3_, b1_, b2_, b3_, c1_, c2_, c3_] := KroneckerProduct[Uni[a1, b1, c1], KroneckerProduct[Uni[a2, b2, c2], Uni[a3, b3, c3]]]
StateDifference[a1_, a2_, a3_, b1_, b2_, b3_, c1_, c2_, c3_] := RhoKnown - LocalUni[a1, a2, a3, b1, b2, b3, c1, c2,  c3].RhoFound.ConjugateTranspose[LocalUni[a1, a2, a3, b1, b2, b3, c1, c2, c3]]

so I have the function StateDifference, and I want to minimize its absolute value, in terms of the a1,a2... parameters. Thus I apply:
NMinimize[{Abs[N[StateDifference[m1, m2, m3, m4, m5, m6, m7, m8, m9]]]}, {m1, m2, m3, m4, m5, m6, m7, m8, m9}]

where I just replaced a1,a2, with m1,m2 etc (this should not matter).
The problem is when I run this:
The objective function {{Abs[<<1>>],Abs[(-0.0526+0.0765 I)+<<1>>+<<11>>],Abs[(0.1122 -0.0484 I)+<<12>>],Abs[<<12>>+2.71828^(Times[<<2>>]+Times[<<2>>]+Times[<<2>>]) <<1>> ((-0.113-0.0444 I) Power[<<2>>] Cos[<<1>>] Cos[<<1>>] Cos[<<1>>]-(0.0196 -0.1235 I) Power[<<2>>] Cos[<<1>>] Cos[<<1>>] Sin[<<1>>]+(0.0062 +0.1358 I) Power[<<2>>] Cos[<<1>>] Cos[<<1>>] Sin[<<1>>]-(0.1134 -0.0651 I) <<3>> Sin[<<1>>]+(<<1>>) <<4>>-(0.1036 -0.0864 I) Power[<<2>>] Cos[<<1>>] Sin[<<1>>] Sin[<<1>>]+(0.0596 +0.1086 I) Power[<<2>>] Cos[<<1>>] Sin[<<1>>] Sin[<<1>>]+(0.1218 +0.014 I) Power[<<2>>] Sin[<<1>>] Sin[<<1>>] Sin[<<1>>])],Abs[(<<7>> +<<1>>)+<<12>>],Abs[<<1>>],Abs[<<1>>],Abs[(0.0314 +0.0286 I)+2.71828^(Times[<<2>>]+Times[<<2>>]+Times[<<2>>]) Conjugate[Sin[<<1>>] Sin[<<1>>] Sin[<<1>>]] (<<1>>)+<<11>>]},<<7>>} should be scalar-valued. >>

The matrices RhoKnown and RhoFound are just 2 numerical 8x8 matrices. (Hermitian and of trace 1).

A: The problem resides in the fact that I was minimizing over a matrix not a number. This can be done, however, over the sum of the total matrix elements, by using the line:
FinalFunct[a1_, a2_, a3_, b1_, b2_, b3_, c1_, c2_, c3_] := Sum[StateDifference[a1, a2, a3, b1, b2, b3, c1, c2,c3][[k]][[k]], {k, 1,   Length[StateDifference[a1, a2, a3, b1, b2, b3, c1, c2, c3]]}]

and using NMinimize on this function. My apologies for not seeing this before posting the question.


text:
Q: Height of background image only resizes on refresh I have a div with id #hero and I've set the height of #hero to change to the window height with this jquery:
$(document).ready(function(){
 $("#hero").height($(window).height());
    $(window).resize(function(){
      $("#hero").height($(window).height());
})
});

This works fine when I first load the page, when I refresh the page, or when I resize the page. But when I navigate to the home page from another page, #hero doesn't resize.
Any idea what could be causing this issue?
It may be worth mentioning that I'm using Rails 3.0, but I don't know what that would have to do with it.
Thanks in advance!


text:
Q: check for audio voice driver installed in c# i use a sound player in my winform application.
Is there a way to check for sound cards driver (is installed/or not installed)on OS?
i want to chek it programatelly in c#

A: i got it
using System.Runtime.InteropServices;

[DllImport("winmm.dll", SetLastError = true)]
public static extern uint waveOutGetNumDevs();

private void frmSound_Load(object sender, System.EventArgs e){
if(waveOutGetNumDevs() != 0)
{
  lblSound.Text = "The Sound device is detected for this system";
}
else
{
    lblSound.ForeColor = Color.Red;
    lblSound.Text = "The Sound device is Not Found for this system";
}
}


text:
Q: How to Parse Java-script contains[dynamic] on web-page[html] using Python? I am building a spider and I am using Beautiful soup to parse the contain of particular URL.
Now, some sites are using Java-script to show dynamic contain which will be shown to user once some action [clicking or time] happens.
Beautiful soup just parse the static contain which is before the java-script tag has run.
I want the contain after java-script run.
Is there any way to do this?
I can think of one way: Grab the url, open the browser and run this URL and java-script tags as well. And then pass this url to Beautiful soup, which can see contains which java-script[dynamic contains] has produced. However, if I am crawling millions of links then this solution is not useful. If there is some in-built module available which can generate dynamic contain of the Html page before hand.

A: Your best bet for accurately parsing Javascript-enhanced content from web pages is to load the page via a browser engine. Luckily there are ways to automate this in Python.
The method I've had the most success with is to use the pywebkitgtk project which lets you programmatically create and control instances of the Webkit browser engine from within a Python application.  I also use the jswebkit module to simplify execution of Javascript in the page context.
Another option is PyQt4's QtWebKit class which I've only used for experimentation.
Here is a working example of using pywebkitgtk and jswebkit together to extract data from a Webkit-rendered page.  In a production environment you'll want to run several of these processors in parallel, each rendering to its own instance of the X virtual framebuffer (Xvfb).
import os

import gtk
import jswebkit
import lxml.html
import pygtk
import webkit

def load_finished(view, frame):
    # called when the document finishes loading
    if frame != view.get_main_frame():
        return
    ctx = jswebkit.JSContext(frame.get_global_context())
    res = ctx.EvaluateScript('window.location.href')
    print res
    res = ctx.EvaluateScript('document.body.innerHTML')
    tree = lxml.html.fromstring(res)
    print tree.xpath('//input[@type="submit"]')

# initialization
pygtk.require20()
gtk.gdk.threads_init()

# create the webview and hook up callbacks to signals
view = webkit.WebView()
view.set_size_request(1024, 768)
view.connect('load-finished', load_finished)

# configure the webview
props = view.get_settings()
props.set_property('enable-java-applet', False)
props.set_property('enable-plugins', False)
props.set_property('enable-page-cache', False)

# create a window to host the webview
win = gtk.Window()
win.add(view)
win.show_all()

# open google front page
view.open('http://www.google.com')

# spin, processing gtk events
while True:
    try:
        while gtk.events_pending():
            gtk.main_iteration(False)
    except KeyboardInterrupt:
        break

Example output:
http://www.google.com/
[<InputElement 2a64a78 name='btnG' type='submit'>, <InputElement 2a64bb0 name='btnG' type='submit'>, <InputElement 2a64ae0 name='btnI' type='submit'>]


text:
Q: Hide VirtualBox in Dock when launching Vagrant I upgraded my VirtualBox to 5.1 a while ago, and now whenever I run vagrant up the VirtualBox icon shows up in my Dock. This was not the behaviour I had in VirtualBox 5.0 (or so I remember).
How can I hide this icon without having to edit anything?

A: I had this same issue and it lasted months! It appears to have been some kind of bug with either Virtualbox or Vagrant. I was on Vagrant version 1.9.1 and Virtualbox 5.1.19 (I think). Upgrading to the latest of each of those should fix your problem.
As of this writing Vagrant is version 1.9.7 and Virtualbox is 5.1.22.


text:
Q: Tensorflow Distributed Multi-Machine Training: Failing to connect to nodes other than self If I only use nodes 2-4 in TF_CONFIG, the program just hangs, where if I have one set as the primary (node01) the script throws the error logs below. I believe node01 is delegated as chief due to placement so this may be why it fails further down the line, but the issue still remains.
Code:
import os
import json

import tensorflow as tf
import mnist_setup

per_worker_batch_size = 64
tf_config = json.loads(os.environ['TF_CONFIG'])
num_workers = len(tf_config['cluster']['worker'])

strategy = tf.distribute.MultiWorkerMirroredStrategy()

global_batch_size = per_worker_batch_size * num_workers
multi_worker_dataset = mnist_setup.mnist_dataset(global_batch_size)

with strategy.scope():
  # Model building/compiling need to be within `strategy.scope()`.
  multi_worker_model = mnist_setup.build_and_compile_cnn_model()

multi_worker_model.fit(multi_worker_dataset, epochs=3, steps_per_epoch=70)

TF_CONFIG:
{'cluster': {'worker': ['node01:34425', 'node02:36257']},
 'task': {'type': 'worker', 'index': 1}}

Output:
/home/ubuntu/miniforge3/lib/python3.10/site-packages/tensorflow_io/python/ops/__init__.py:98: UserWarning: unable to load libtensorflow_io_plugins.so: unable to open file: libtensorflow_io_plugins.so, from paths: ['/home/ubuntu/miniforge3/lib/python3.10/site-packages/tensorflow_io/python/ops/libtensorflow_io_plugins.so']
caused by: ["[Errno 2] The file to load file system plugin from does not exist.: '/home/ubuntu/miniforge3/lib/python3.10/site-packages/tensorflow_io/python/ops/libtensorflow_io_plugins.so'"]
  warnings.warn(f"unable to load libtensorflow_io_plugins.so: {e}")
/home/ubuntu/miniforge3/lib/python3.10/site-packages/tensorflow_io/python/ops/__init__.py:104: UserWarning: file system plugins are not loaded: unable to open file: libtensorflow_io.so, from paths: ['/home/ubuntu/miniforge3/lib/python3.10/site-packages/tensorflow_io/python/ops/libtensorflow_io.so']
caused by: ['/home/ubuntu/miniforge3/lib/python3.10/site-packages/tensorflow_io/python/ops/libtensorflow_io.so: cannot open shared object file: No such file or directory']
  warnings.warn(f"file system plugins are not loaded: {e}")
2023-02-04 06:16:07.014328: I tensorflow/core/distributed_runtime/rpc/grpc_server_lib.cc:447] Started server with target: grpc://node02:36257
2023-02-04 06:16:07.039956: I tensorflow/core/distributed_runtime/coordination/coordination_service_agent.cc:277] Coordination agent has successfully connected.
2023-02-04 06:16:08.150050: W tensorflow/tsl/framework/cpu_allocator_impl.cc:82] Allocation of 188160000 exceeds 10% of free system memory.
2023-02-04 06:16:12.054935: E tensorflow/core/distributed_runtime/coordination/coordination_service_agent.cc:678] Coordination agent is in ERROR: UNAVAILABLE: failed to connect to all addresses
Additional GRPC error information from remote target /job:worker/replica:0/task:0:

I have tried the other suggestions such as "unset https_proxy" and similar, however this only worked for being able to change localhost -> node01 in the tf_config file, with node01 being the only node. I also changed the iptables to allow all Input/Output traffic from the ip of each machine on the local network, still with no success. The code is an excerpt from the tutorial on tensorflow's tutorial notebook on distributed training, with the only modifications of removing the tf-nightly install, and changing localhost to the hostnames of my machines.
I am running tensorflow 2.11.0
Link here: https://github.com/tensorflow/docs/blob/master/site/en/tutorials/distribute/multi_worker_with_keras.ipynb


text:
Q: Reference to existing instance of a COMVisible object I have two .NET projects, and I would like to create a 2-way communication between these.
ProjectA is a Shared Add-In, that creates a ribbon in an MS Office application.
ProjectB is a WinForms app, that gathers/sends info from/to a server.
I have created an interface, IAddInCommunication, that defines methods which I want to call from ProjectB. This interface is in a separate class library project. The Connect class in ProjectA implements the IAddInCommunication interface (along with some others). I added a reference to the interface's DLL in ProjectB as well.
Now I'm trying to call the methods of the shared add-in, which is running in MS Word, for example. To achieve this, I'm using the following code (in ProjectB):
const string ProgId="ProjectA.Connect";
//...
Type officeAddInType = Type.GetTypeFromProgID(ProgId);
object obj = Activator.CreateInstance(officeAddInType);
_remoteAddIn = (IAddInCommunication)obj;
_remoteAddIn.TestMethod("Hello");

The problem is, that the _remoteAddIn is not pointing to the instance running in Office. It's just a new instance (as one would expect). How could I connect to the actual running instance of the Shared-AddIn?
I solved the communication from ProjectA to ProjectB with the SendMessage API, because I needed that in my application anyway. I would only implement SendMessage communication in my Add-In if there's really no better way.

A: You are probably looking for:
(IAddInCommunication)System.Runtime.InteropServices.Marshal.GetActiveObject(ProgId);

To get something from the running object table.


text:
Q: Remove noise from a rectangular wave matlab I have some recordings (from 16:00PM to 16:00PM) where ones indicate some kind of noise and zeros indicate quite moments. The following code tries to replicate these recordings.
dt = datenum('00:02:00','HH:MM:ss') - datenum('00:01:00','HH:MM:ss');
time_begin = datenum('00:00:00','HH:MM:ss');
time_end = datenum('24:00:00','HH:MM:ss');
time = repmat(cellstr(datestr(time_begin:dt:time_end,'HH:MM:ss')),2,1);

loudness = ones(1,numel(time));
quiet_start = [1489 1737];
quiet_end = [1603 1906];

for i = 1: numel(quiet_start)
   loudness(quiet_start(i):quiet_end(i))=0;
end

time = time(961:2400);
loudness = loudness(961:2400);

figure
plot(loudness)
ylim([0 3])

I know that in the interval 16:00PM - 16:00PM there should be only 1 "bout" of zeros. Here (if you plot loudness) you can see that there are 2 bouts of zeros.
I have 2 possibilities:

*

*remove one of the two bouts of zeros

*remove the bout of ones in the middle

Is there any measure that I can use to take this decision? I.e. Do I make a bigger error converting ones to zeros or viceversa?
There are 2 (or more) bouts of zeros because of some errors in the recordings...but for sure there should be only one. I would like to remove the bouts in order to "modify" the system as less as possible. For instance: in this case I would remove the first bout of zeros since it is the smallest, but what to do if there are more than 2 bouts? Is there any algorithm that deals with this kind of problems?


text:
Q: What's the idiomatic way to create APIs in Kotlin with async operations? When creating APIs in Kotlin, what is the idiomatic way to handle async actions?
We could create apis that require normal blocking calls, forcing application code to use something like runBlocking.
////
//// Plain functions
////

// library code
fun registerHandler(block: (it: Foo) -> String) {
    // save a reference to call when an action happens later
}

// application code
registerHandler {
    runBlocking {
        handleItSuspend(it)
    }
}

We could make use of suspend more which looks nicer for the application code but requires that we execute our callbacks from suspend functions or coroutine contexts, which may or may not be inconvenient for us.
////
//// Suspend functions
////

// library code
fun registerHandler(block: suspend (it: Foo) -> String) {
    // save a reference to call when an action happens later
}

// application code
registerHandler {
    handleItSuspend(it)
}

Or we could take functions that return deferred results
////
//// Deferred functions
////

// library code
// This handler can be called from anywhere without needing suspend.
fun registerHandler(block: (it: Foo) -> Deferred<String>) {
    // save a reference to call when an action happens later
}

// application code
registerHandler {
    // Function that isn't suspend but returns a deferred
    handleItAsync(it)
}

Is there a consensus or an official stance on what we should be doing?

A: As @msrd0 alluded to in a comment, you can easily convert between arguments for the second and third approaches, so they are equivalent:
val block1: suspend (Foo) -> String = ...
val block2: (Foo) -> Deferred<String> = { x -> async { block1(x) } }
val block3: suspend (Foo) -> String = { x -> block2(x).await() }

But I'd expect most calls to the Deferred version to look like
registerHandler { foo -> async { doSomethingSuspend(foo) } }

in which case the suspend version is easier to use, it will be just
registerHandler { foo -> doSomethingSuspend(foo) }

Of course, your code base may already use Deferred generally enough that this assumption doesn't hold.

requires that we execute our callbacks from suspend functions or coroutine contexts, which may or may not be inconvenient for us.

I don't think it can be too inconvenient, since it's just a simple async (or another coroutine builder) call inside registerHandler.
Or did you mean that registerHandler needs to be called there? That would only be true if it was itself declared suspend.


text:
Q: How will http server handle html5 web sockets? I am reading a lot about HTML5 and I like the web sockets in particular because they facilitate bi-directional communication between web server and web browser.
But we keep reading about chrome, opera, firefox, safari getting ready for html5. Which web server is ready to use web sockets feature? I mean, are web servers capable of initiating subsequent communication as of today? How about Google's own Appengine?
How can I write a sample web application that takes advantage of this feature in Java?

A: Jetty, for example, supports this feature since version 7: Jetty Websocket Server
Google App Engine have plans for this also. They even have working demo of this at Google I/O 2010, but it's not in production yet. See ticket #377

A: Bi-directional communication between web servers and browsers is nothing new. Stack Overflow does it today if a new answer is posted to a question you're reading. There are a few different strategies for implementing socket-style behavior using existing technologies:

*

*AJAX short polling: Connect to the server and ask if there are any new messages. If not, disconnect immediately and ask again after a short interval. This is useful when you don't want to leave a lot of long-running, idle connections open to the server, but it means that you will only receive new messages as fast as your polling interval, and you incur the overhead of establishing a new HTTP connection every time you poll.

*AJAX long polling: Connect to the server and leave the connection open until a new message is available. This gives you fast delivery of new messages and less frequent HTTP connections, but it results in more long-running idle processes on the server.

*Iframe long polling: Same as above, only with a hidden iframe instead of an XHR object. Useful for getting around the same-origin policy when you want to do cross-site long polling.

*Plugins: Flash's XMLSocket, Java applets, etc. can be used to establish something closer to a real low-level persistent socket to a browser.

HTML5 sockets don't really change the underlying strategies available. Mostly they just formalize the strategies already in use, and allow persistent connections to be explicitly identified and thus handled more intelligently. Let's say you want to do web-based push messaging to a mobile browser. With normal long-polling, the mobile device needs to stay awake to persist the connection. With WebSockets, when the mobile device wants to go to sleep, it can hand off the connection to a proxy, and when the proxy receives new data it can wake up the device and pass back the message.
The server-side is wide open. To implement the server-side of a short polling application, you just need some kind of a chronological message queue. When clients connect they can shift new messages off the queue, or they can pass an offset and read any messages that are newer than their offset.
Implementing server-side long polling is where your choices start to narrow. Most HTTP servers are designed for short-lived requests: connect, request a resource, and then disconnect. If 300 people visit your site in 10 minutes, and each takes 2 seconds to connect and download HTTP resources, your server will have an average of 1 HTTP connection open at any given time. With a long polling app, you're suddenly maintaining 300 times as many connections.
If you're running your own dedicated server you may be able to handle this, but on shared hosting platforms you're likely to bump up against resource limits, and App Engine is no exception. App Engine is designed to handle a high volume of low latency requests, e.g. short polling. You can implement long polling on App Engine, but it's ill-advised; requests that run for longer than 30 seconds will get terminated, and the long running processes will eat up your CPU quota.
App Engine's solution for this is the upcoming Channel API. The channel API implements long polling using Google's existing robust XMPP infrastructure.
Brett Bavar and Moishe Lettvin's Google I/O talk lays out the usage pattern as follows:
App Engine apps create a channel on a remote server, and are returned a channel ID which they pass off to the web browser.
class MainPage(webapp.RequestHandler):

    def get(self):
        id = channel.create_channel(key)
        self.response.out.write(
            {'channel_id': id})

The web browser passes the channel ID to the same remote server to establish a connection via iframe long polling:
<script src='/_ah/channel/jsapi'></script>
<script>
  var channelID = '{{ channel_id }}';
  var channel =
    new goog.appengine.Channel(channelId);
  var socket = channel.open();
  socket.onmessage = function(evt) {
    alert(evt.data);
  }
</script>

When something interesting happens, the App Engine app can push a message to the user's channel, and the browser's long poll request will immediately receive it:
class OtherPage(webapp.RequestHandler):

    def get(self):
        # something happened
        channel.send_message(key, 'bar')


text:
Q: How to inspect element for Selenium v3.6 as FireBug is not an option any more for FF 56? I am trying to find a way to use FireBug for FF. Unfortunately it's not supported for selenium v3.6. What can be done if I have to locate the elements, will "Inspect" element will be sufficient?
If I get down to less version of selenium, will that help?

A: If you visit the GitHub Page of FirePath, it clearly mentions that :

FirePath is a Firebug extension that adds a development tool to edit, inspect and generate XPath expressions and CSS3 Selectors

Now if you visit the Home Page of FireBug, it clearly mentions that :

The Firebug extension isn't being developed or maintained any longer. We invite you to use the Firefox DevTools instead, which ship with Firebug next.

So the direction is clear that, we have to use Development Tools which comes integrated with the Mozilla Firefox 56.x + release onwards.

Example Usage :
Now, let us assume we have to identify the xpath or cssSelector of the Search Box on Google Home Page https://www.google.com/.

*

*Open Mozilla Firefox or Google Chrome browser and browse to the url https://www.google.co.in

*Press F12 or Ctrl+Shift+I to open the Developer Tools

*Within the Developer Tools console, with in the Elements tab, once you click on the Inspector and mouse hover the Search Box and the WebElement pertaining to the Search Box gets highlighted within the DOM Tree.

*Within the HTML DOM you can right click and on mouse hover over Copy item you can clck on either of the following sub menu item:

*

*Copy selector: To copy the CssSelector (absolute)

*Copy XPath: To copy the XPath (absolute)

*Snapshot:

Additional Steps
Referring the copied CssSelector or XPath you can also construct a logical unique XPath or a CssSelector.

Testing your own XPath
To test your own written XPath, within the Developer Tools console, click on  the Console tab and within the editor paste the logical unique xpath you have constructed in the following format and hit Enter or Return:
$x("//*[@name='q']")

Example:

Testing your own CssSelector
To test your own written CssSelector, within the Developer Tools console, click on  the Console tab and within the editor paste the logical unique cssSelector you have constructed in the following format and hit Enter or Return:
$$("[name='q']")

Example:

A: Inspect element is sufficient if you only want to inspect element.
I found Firepath helpful with testing the locators. Downgrading to Firefox 30 – 54 should be enough. It has nothing to do with Selenium version.
Also you can look at Chropath for Chrome

A: Try this step in your case and check.

*

*Open A Blank Tab in Firefox

*Type about:config in address bar then press enter (click on I accept the risk!)

*Find browser.tabs.remote.autostart

*Select the option then click the mouse right side

*Turn The Option As False

*Close the browser for restart browser

*Open browser again, inspect the element. I hope It Works Properly.

A: ChroPath extension for xpath and best replacement for FirePath. It has no dependency on other extension like firepath was dependent on firebug. Just add ChroPath to Chrome browser and use it.
Download link- ChroPath
Features-

*

*gives unique xpath and css selectors

*It opens as sidebar tab in devtools panel where you can access DOM, inspect element in left side and write the XPath/CSS in right side.

*verify xpath and css selectors

*gives the list of matched node

*highlight the web element on hover

*scroll the hidden element in view area on hover.

*ChroPath is the only extension which gives unique CSS selectors for selected or inspected element.


text:
Q: How to get X and Y index of element inside GridLayout? I am studying a java tutorial and saw that the way to find the x/y indexes of a JButton inside a GridLayout is to traverse a bidimensional array of buttons b which is associated to the layout and checking if
b[i][j] == buttonReference.
  @Override
  public void actionPerformed(ActionEvent ae) {
    JButton bx = (JButton) ae.getSource();
    for (int i = 0; i < 5; i++)
      for (int j = 0; j < 5; j++)
        if (b[i][j] == bx)
        {
          bx.setBackground(Color.RED);
        }
  }

Is there an easier way to get the X/Y indexes of a button?
Something like:
JButton button = (JButton) ev.getSource();
int x = this.getContentPane().getComponentXIndex(button);
int y = this.getContentPane().getComponentYIndex(button);

this being a GameWindow instance and ev the ActionEvent triggered when the user presses the button.

In this case it should get: x == 2, y == 1
@GameWindow.java:
package javaswingapplication;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;

public class GameWindow extends JFrame implements ActionListener
{
  JButton b[][] = new JButton[5][5];

  int v1[] = { 2, 5, 3, 7, 10 };
  int v2[] = { 3, 5, 6, 9, 12 };

  public GameWindow(String title)
  {
    super(title);

    setLayout(new GridLayout(5, 5));
    setDefaultCloseOperation(EXIT_ON_CLOSE );

    for (int i = 0; i < 5; i++)
      for (int j = 0; j < 5; j++)
      {
        b[i][j] = new JButton();
        b[i][j].addActionListener(this);
        add(b[i][j]);
      }
  }

  @Override
  public void actionPerformed(ActionEvent ae) {
    ((JButton)ae.getSource()).setBackground(Color.red);
  }
}

@JavaSwingApplication.java:
package javaswingapplication;

public class JavaSwingApplication {
  public static void main(String[] args) {
    GameWindow g = new GameWindow("Game");
    g.setVisible(true);
    g.setSize(500, 500);
  }
}

A: You have saved an array of all JButtons; you could search for ae.getSource() and you have the position.
for (int i = 0; i < 5; i++) {
  for (int j = 0; j < 5; j++) {
    if( b[i][j] == ae.getSource() ) {
      // position i,j
    }
  }
}

A: From JButtons

*

*JButton#setName(String);

*JBUtton#setActionCommand(String);

*JBUtton#setAction(Action);
from/to Container
SwingUtilities#convert...
SwingUtilities#getDeepestComponentAt

A: This example shows how to create a grid button that knows its location on the grid. The method getGridButton() shows how to obtain a button reference efficiently based on its grid coordinates, and the action listener shows that the clicked and found buttons are identical.

package gui;

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * @see http://stackoverflow.com/questions/7702697
 */
public class GridButtonPanel {

    private static final int N = 5;
    private final List<JButton> list = new ArrayList<JButton>();

    private JButton getGridButton(int r, int c) {
        int index = r * N + c;
        return list.get(index);
    }

    private JButton createGridButton(final int row, final int col) {
        final JButton b = new JButton("r" + row + ",c" + col);
        b.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JButton gb = GridButtonPanel.this.getGridButton(row, col);
                System.out.println("r" + row + ",c" + col
                    + " " + (b == gb)
                    + " " + (b.equals(gb)));
            }
        });
        return b;
    }

    private JPanel createGridPanel() {
        JPanel p = new JPanel(new GridLayout(N, N));
        for (int i = 0; i < N * N; i++) {
            int row = i / N;
            int col = i % N;
            JButton gb = createGridButton(row, col);
            list.add(gb);
            p.add(gb);
        }
        return p;
    }

    private void display() {
        JFrame f = new JFrame("GridButton");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(createGridPanel());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new GridButtonPanel().display();
            }
        });
    }
}

A: You can use setName() to store within a JButton its location(ex. button.setName(i+" "+j);) when you create it; you can then access it by splitting the string you get from button.getName() around the space. It is not an especially efficient method, but it sounds a little like what you are (or were, by now) looking for.

A: this solution selects everything object between like them
first
write method that get text or Everything needed for Jbuuton or jlable or....
second change under code
public class Event_mouse implements MouseListener {

    @Override
    public void mouseReleased(MouseEvent e) {
        try {
            Everything source = (Everything) e.getSource();
             if(Everything.gettext==gol){

             }

        } catch (Exception ee) {
            JOptionPane.showMessageDialog(null, ee.getMessage());

    }

}

A: I think there is a better way, for example i made a new JButton class that extends JButton from javax.swing, i named it JButton2, then i added 2 new attributes to it (xGridPos and yGridPos) like this:
private class JButton2 extends JButton{
    public int xGridPos;
    public int yGridPos;
}

When I create a new JButton2 I set this new attributes with the x and y position on the grid so you can get the x and y and use them with getSource and using cast:
private class ListenerTest implements ActionListener{
    public void actionPerformed(ActionEvent theActionEvent){
        JButton2 theButton = (JButton2)actionE.getSource();
        // Use the xGridPos and yGridPos in section with theButton.xGridPos or
        // theButton.xGridPos
    }
}

I hope this is helpfull :D.

A: You do not need your buttons to explicitly store their x,y position.
Consider the following code:
JComponent e=//something with GridLayout
var count=e.getComponentCount();
var row=count/11;//for example, you have an 11*11 grid
var col=count%11;
var bb=new JButton(row+" "+col);//or any other text you like
bb.addActionListener(unused->System.out.println(
    "pressed button "+count+ " in row="+row+" col="+col
    ));
this.add(bb);


text:
Q: AWS Cron job for Lambda I have written a Lambda to fetch some prices on Nifty Index(share market) which runs every 5 mins and uploads data to S3.
For this i have written a cron using AWS EventBridge schedule given below
15/5 9-15 ? * MON-FRI *
now the problem is this runs from 9-15 AM to 4 PM but i want to run only till 3 - 30 PM daily.
So its running 30 mins extra which is consuming more space on s3 also
Any suggestions? Couldnt find elsewhere
Tried
15/5 9-15 ? * MON-FRI *
Current 9-15 AM to 4 PM
Expectation
9-15AM to 3-30 PM

A: This 15/5 9-15 ? * MON-FRI * expression will run
At every 5th minute from 15 through 59 past every hour from 9 through 15 on every day-of-week from Monday through Friday.
In your case between each hours 00 and 15 minutes (1X.00-1X.15) this cron will not execute.
So that you need more than one expression to meet your requirements.

*

*30/5 9 ? * MON-FRI * -> From 9.30-9.55

**/5 10-14 ? * MON-FRI * -> From 10.00-14.55

*0-30/5 15 ? * MON-FRI * -> From 15.00-15.30


text:
Q: Entity Relationships - Can a weak entity take part in a 'one to many' relationship as the 'one' With the following entity relationship structure I'm struggling to figure out if the relationship between the LOAN and ITEM entities is valid?
The weak entity of LOAN uses a partial key of 'loan_dateLeant' and the primary keys from CUSTOMER and ITEM to form LOANs primary key.
However LOAN has a 'one to many' relationship with ITEM as a loan can consist of more than one item.
But surely this means that if more than one item is loaned, then the loan record will have two item_id values for part of its primary key?

A: You're right, that's not valid - you can't use a to-many relationship as a defining part of a primary key. What you might consider doing instead is adding a unique loan_id that you make part of your primary key, instead of the items the loan contains; then a single loan is defined by its customer and loan ID (or customer, date, and loan ID).
If that doesn't work, make date_leant a datetime field, and increase the precision on it until you can't possibly (within the constraints of your system) have two loans occur at the same time - how likely is it that a single customer transacts two separate loans within milliseconds of each other?
Note this doesn't prevent the LOAN entity from taking part in the relationship as the "one"; it just means that you can't define the weak entity using the "many".

A: Actually, you can do this.
Remember, the primary key of LOAN will only depend on the date+customer identifier. As long as there is a maximum cardinality of "1" on the "can make" relationship (i.e., a loan is related to only 1-customer), you're fine on the primary key with LOAN.
The ITEM table, will instead take the (single) identifier of the loan (customerID + date) as a foreign key within ITEM. The Primary Key of LOAN will not be affected by this modeling.


text:
Q: Change TableView Header Text Color I would like to make a simple change in my tableView. I have a custom table view background and I would like to change the Header and Footer TEXT color,
ONLY the text color.
I've seen on internet that usually we must use the delegate method to give to the table view an entire new view but I would ONLY to change the text color (and, if possibile, the shadow)...
Is there a simple way to do this avoiding create a new entire view?
Please help me.
Thank you

A: If you want the header/footer to be customized in any way other than just a custom string, you will need to create a UIView.
This is documented in the UITableViewDataSource documentation:

tableView:titleForHeaderInSection:
Discussion
  The table view uses a fixed font style for section header titles. If you want a different font style, return a custom view (for example, a UILabel object) in the delegate method tableView:viewForHeaderInSection: instead.

A: Sorry but the only way to customize the font color of your header is to create a UIView in the delegate method
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
If you look at the answer posted here then you can see a pretty simple way to implement this into your application. All you have to do is copy and paste that function into your table view's data source and then change the UILabel properties to be whatever you would like it to be.
Here is the code from that post for easy reference:
Originally posted by Harsh:

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *tempView=[[UIView alloc]initWithFrame:CGRectMake(0,200,300,244)];
    tempView.backgroundColor=[UIColor clearColor];

    UILabel *tempLabel=[[UILabel alloc]initWithFrame:CGRectMake(15,0,300,44)];
    tempLabel.backgroundColor=[UIColor clearColor];
    tempLabel.shadowColor = [UIColor blackColor];
    tempLabel.shadowOffset = CGSizeMake(0,2);
    tempLabel.textColor = [UIColor redColor]; //here u can change the text color of header
    tempLabel.font = [UIFont fontWithName:@"Helvetica" size:fontSizeForHeaders];
    tempLabel.font = [UIFont boldSystemFontOfSize:fontSizeForHeaders];
        tempLabel.text=@"Header Text";

    [tempView addSubview:tempLabel];

    [tempLabel release];
    return tempView;
}

A: Given that if you set the header/footer without a UIView subclass you are passing a NSString, it currently isn't possible to accomplish what you want without having to create a UIView.

A: func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    let headerView = view as! UITableViewHeaderFooterView
    headerView.textLabel?.textColor = ...
}

I am even able to set attributed text to this label


text:
Q: How can I protect a wp-content/uploads folder in IIS with web.config only for loggedin users? I've to protect a Wordress upload folder (wp-content/upload) only for loggedin users.
In many other sites (on Apache) I always use this .htaccess rules that redirects all traffic to a router file:
RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^wp-content/uploads/(.*)$ dl-file.php?file=$1 [QSA,L]

But how can I do this in IIS? I know there are tools like Ape that makes htaccess working in IIS, but how can I do this in IIS with only web.config? (no visible redirect, thus the url must always be the same)


text:
Q: How to create horizontal image scrolling in xamarin cross platform? Below is an image that I want to achieve using Xamarin cross-platform but I don't know how to do that. As like in play store we can horizontally scroll the apps. So please tell me how to do that.

A: Out of box Xamarin doesn't have any control that has DataTemplate and horizontal scrolling. Unfortunately I am not aware of any plugin either (at least not true DataTemplate that would allow unlimited number of items without performance and even stability problems). If you are fine with limited number of items you may want to use StackPanel and insert items in it. Otherwise you need to use the native control for each platform that provides this.

A: Try implementing using Sharpnado.Forms.HorizontalListView component. You can achieve the horizontal image scrolling collection.
One more component you can use is XamarinHorizontalList.


text:
Q: An Extra Drive is Showing in My Computer but not in Disk Management in Windows 10 Hey Any one please help me !! An unknown extra drive is shown in My Computer and when i tried to open it ... it says Access Denied .... I don't know from where it come from and when i checked it in Disk Management its not their. Please help me to remove that drive.
Below is the screen short of that Drive & Disk Management.

A: When I restarted my Windows system it's gone.
Remember: You should do a restart, not a shut down.
I think it's related to Windows updates.

A: I wonder if this could be that 100MB Windows Reserved EFI system partition that you somehow started displaying instead of it being hidden by default.


text:
Q: How To add automatic scrolling in slider I want to add automatic scrolling time to my slider code but unable to do it can you please suggest me something to help me out with the code to make this slider slide automatic with a set interval of time.
'use strict';

$(document).ready(function () {

  var $slides = $('.con__slide').length,
      topAnimSpd = 650,
      textAnimSpd = 1000,
      nextSlideSpd = topAnimSpd + textAnimSpd,
      animating = true,
      animTime = 4000,
      curSlide = 1,
      nextSlide,
      scrolledUp;

  setTimeout(function () {
    animating = false;
  }, 2300);

  //navigation up function
  function navigateUp() {
    if (curSlide > 1) {
      scrolledUp = true;
      pagination(curSlide);
      curSlide--;
    }
  }

  //navigation down function
  function navigateDown() {
    if (curSlide < $slides) {
      scrolledUp = false;
      pagination(curSlide);
      curSlide++;
      console.log(curSlide);
    }
  }

  $(window).on('load', function () {
    $('.con__slide--1').addClass('active');
  });

  //pagination function
  function pagination(slide, target) {
    animating = true;
    // Check if pagination was triggered by scroll/keys/arrows or direct click. If scroll/keys/arrows then check if scrolling was up or down.
    if (target === undefined) {
      nextSlide = scrolledUp ? slide - 1 : slide + 1;
    } else {
      nextSlide = target;
    }
    ////////// Slides //////////
    $('.con__slide--' + slide).removeClass('active');

    setTimeout(function () {
      $('.con__slide--' + nextSlide).addClass('active');
    }, nextSlideSpd);

    ////////// Nav //////////
    $('.con__nav-item--' + slide).removeClass('nav-active');
    $('.con__nav-item--' + nextSlide).addClass('nav-active');

    setTimeout(function () {
      animating = false;
    }, animTime);
  }

  // Mouse wheel trigger
  $(document).on('mousewheel DOMMouseScroll', function (e) {
    var delta = e.originalEvent.wheelDelta;
    if (animating) return;
    // Mouse Up
    if (delta > 0 || e.originalEvent.detail < 0) {
      navigateUp();
    } else {
      navigateDown();
    }
  });

  // Direct trigger
  $(document).on("click", ".con__nav-item:not(.nav-active)", function () {
    // Essential to convert target to a number with +, so curSlide would be a number
    var target = +$(this).attr('data-target');
    if (animating) return;
    pagination(curSlide, target);
    curSlide = target;
  });

  // Arrow trigger
  $(document).on('click', '.con__nav-scroll', function () {
    var target = $(this).attr('data-target');
    if (animating) return;
    if (target === 'up') {
      navigateUp();
    } else {
      navigateDown();
    }
  });

  // Key trigger
  $(document).on("keydown", function (e) {
    if (animating) return;
    if (e.which === 38) {
      navigateUp();
    } else if (e.which === 40) {
      navigateDown();
    }
  });

  var topLink = $(".con__slide--4-top-h-link"),
      botLink = $(".con__slide--4-bot-h-link");
  $(".con__slide--4-top-h-link, .con__slide--4-bot-h-link").on({
    mouseenter: function mouseenter() {
      topLink.css('text-decoration', 'underline');
      botLink.css('text-decoration', 'underline');
    },
    mouseleave: function mouseleave() {
      topLink.css('text-decoration', 'none');
      botLink.css('text-decoration', 'none');
    }
  });
});

Hope you understand the above code if you have any query in it feel free to ask me and please help me out as soon as possible.

A: Added setInterval in your code.
setInterval(() => {
if (curSlide >= $slides){
    if (animating) return;
    pagination(4, 1);
    curSlide = 1;
}
else
    navigateDown();
}, 10000);

Check updated fiddle.

A: update below navigateDown code.
//navigation down function
  function navigateDown() {
    if (curSlide < $slides) {
      scrolledUp = false;
      pagination(curSlide);
      curSlide++;
      console.log(curSlide);
    }else{
    curSlide=1;
    pagination(4,1)
    }
  }

Add this below line
setInterval(navigateDown,7000);


text:
Q: IOS heightForRowAtIndexPath, setting height for empty cells i am setting the heightForRowAtIndexPath like this:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    /* Contains the string */
    NSString *allStrings = [self convertMainData:indexPath];

    UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];
    CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
    CGSize labelSize = [allStrings sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];

    return labelSize.height + 20;
}

This gets called when the table is not empty, and the size gets calculated correctly, now the issue is that if there is data in the Table, all the cells get their height changed:
http://img716.imageshack.us/img716/3025/yrgt.png
I have tried checking for this in the delegate method
if([tableview cellForRowAtIndexPath:IndexPath] == nil)
   return 20;

But this returns an error, i have also tried wrapping it in != nil, but that has no effect, so how do i leave the empty rows at the default height ?

A: I am assuming that the cell displays allStrings as its content.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    /* Contains the string */
    NSString *allStrings = [self convertMainData:indexPath];

    if(allStrings.length == 0)
    return 20.0f; // return default height. Adjust accordingly

    UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];
    CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
    CGSize labelSize = [allStrings sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];

    return labelSize.height + 20;
}

A: What you're calling empty cells is actually just lines drawn by the table view below your actual cells. The spacing of these lines is determined by the height of your final cell. So if you want a specific spacing, you've got to insert a blank cell as your last row and return the specific height for that row in heightForRowAtIndexPath.
So, the solution proposed by Max will work. You've just got to add another entry in your data model as the last item such that [self convertMainData:indexPath] returns an empty string or nil for that item. If you need more details, please share the details of your data model and view controller's data source methods.

A: An empty tableview footer is the answer. Check this answer for implementation details.


text:
Q: Google App Engine + Form Validation I would like to do google app engine form validation but I dont know how to do it?
I tried like this:
from google.appengine.ext.db import djangoforms
from django import newforms as forms

class SurveyForm(forms.Form):
    occupations_choices = (
    ('1', ""),
    ('2', "Undergraduate student"),
    ('3', "Postgraduate student (MSc)"),
    ('4', "Postgraduate student (PhD)"),
    ('5', "Lab assistant"),
    ('6', "Technician"),
    ('7', "Lecturer"),
    ('8', "Other" )
    )

howreach_choices = (
    ('1', ""),
    ('2', "Typed the URL directly"),
    ('3', "Site is bookmarked"),
    ('4', "A search engine"),
    ('5', "A link from another site"),
    ('6', "From a book"),
    ('7', "Other")
    )

boxes_choices = (
    ("des", "Website Design"),
    ("svr", "Web Server Administration"),
    ("com", "Electronic Commerce"),
    ("mkt", "Web Marketing/Advertising"),
    ("edu", "Web-Related Education")
    )

name = forms.CharField(label='Name', max_length=100, required=True)
email = forms.EmailField(label='Your Email Address:')
occupations = forms.ChoiceField(choices=occupations_choices, label='What is your occupation?')
howreach = forms.ChoiceField(choices=howreach_choices, label='How did you reach this site?')
# radio buttons 1-5
rating = forms.ChoiceField(choices=range(1,6), label='What is your occupation?', widget=forms.RadioSelect)

boxes = forms.ChoiceField(choices=boxes_choices, label='Are you involved in any of the following? (check all that apply):', widget=forms.CheckboxInput)
comment = forms.CharField(widget=forms.Textarea, required=False)

And I wanted to display it like this:
template_values = {
        'url' : url,
        'url_linktext' : url_linktext,
        'userName' : userName,

'item1' : SurveyForm()
            }
And I have this error message:

Traceback (most recent call last):
    File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp_init_.py", line 515, in call
      handler.get(*groups)
    File "C:\Program Files\Google\google_appengine\demos\b00213576\main.py", line 144, in get
      self.response.out.write(template.render(path, template_values))
    File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\template.py", line 143, in render
      return t.render(Context(template_dict))
    File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\template.py", line 183, in wrap_render
      return orig_render(context)
    File "C:\Program Files\Google\google_appengine\lib\django\django\template_init_.py", line 168, in render
      return self.nodelist.render(context)
    File "C:\Program Files\Google\google_appengine\lib\django\django\template_init_.py", line 705, in render
      bits.append(self.render_node(node, context))
    File "C:\Program Files\Google\google_appengine\lib\django\django\template_init_.py", line 718, in render_node
      return(node.render(context))
    File "C:\Program Files\Google\google_appengine\lib\django\django\template\defaulttags.py", line 209, in render
      return self.nodelist_true.render(context)
    File "C:\Program Files\Google\google_appengine\lib\django\django\template_init_.py", line 705, in render
      bits.append(self.render_node(node, context))
    File "C:\Program Files\Google\google_appengine\lib\django\django\template_init_.py", line 718, in render_node
      return(node.render(context))
    File "C:\Program Files\Google\google_appengine\lib\django\django\template_init_.py", line 768, in render
      return self.encode_output(output)
    File "C:\Program Files\Google\google_appengine\lib\django\django\template_init_.py", line 757, in encode_output
      return str(output)
    File "C:\Program Files\Google\google_appengine\lib\django\django\newforms\util.py", line 26, in str
      return self.unicode().encode(settings.DEFAULT_CHARSET)
    File "C:\Program Files\Google\google_appengine\lib\django\django\newforms\forms.py", line 73, in unicode
      return self.as_table()
    File "C:\Program Files\Google\google_appengine\lib\django\django\newforms\forms.py", line 144, in as_table
      return self._html_output(u'%(label)s%(errors)s%(field)s%(help_text)s', u'%s', '', u'%s', False)
    File "C:\Program Files\Google\google_appengine\lib\django\django\newforms\forms.py", line 129, in _html_output
      output.append(normal_row % {'errors': bf_errors, 'label': label, 'field': unicode(bf), 'help_text': help_text})
    File "C:\Program Files\Google\google_appengine\lib\django\django\newforms\forms.py", line 232, in unicode
      value = value.str()
    File "C:\Program Files\Google\google_appengine\lib\django\django\newforms\util.py", line 26, in str
      return self.unicode().encode(settings.DEFAULT_CHARSET)
    File "C:\Program Files\Google\google_appengine\lib\django\django\newforms\widgets.py", line 246, in unicode
      return u'
*\n%s\n' % u'\n'.join([u'
*%s' % w for w in self])
    File "C:\Program Files\Google\google_appengine\lib\django\django\newforms\widgets.py", line 238, in iter
      yield RadioInput(self.name, self.value, self.attrs.copy(), choice, i)
    File "C:\Program Files\Google\google_appengine\lib\django\django\newforms\widgets.py", line 212, in init
      self.choice_value = smart_unicode(choice[0])
  TypeError: 'int' object is unsubscriptable

Do You have any idea how I can do this validation in different case?
I have tried to do it using this kind of:
class ItemUserAnswer(djangoforms.ModelForm):

class Meta:
  model = UserAnswer
But I dont know how to add extra labels to this form and it is displayed in one line.
Do You have any suggestions?
Thanks a lot as it making me crazy why it is still not working:/

A: The builtin method is_valid() should validate.
When submitting a form I do it with HTTP POST
    def post(self):
    try:
        upload_files = self.get_uploads('file')  # 'file' is file upload field in the form
        if upload_files:
            blob_info = upload_files[0]
    except:
        self.response.out.write('File not uploaded')
    try:
        data = AForm(data=self.request.POST)
        if data and data.is_valid():
            # Save the data, and redirect to the view page
            entity = data.save(commit=False)
            entity.added_by = users.get_current_user()
            entity.put()
            if upload_files:
                im = Image(reference=entity)
                im.primary_image = blob_info.key()
                im.put()
                entity.put()
                self.redirect('/serve/%s' % blob_info.key())
        else:
            # Reprint the form
            self.response.out.write(''
                                    '<form method="POST" '
                                    'action="/">'
                                    '
')
            self.response.out.write(data)
            self.response.out.write('
'
                                    '<input type="submit">'
                                    '</form>')
    except:
        self.redirect('/serve/%s' % blob_info.key())

A: Here is the issue

rating = forms.ChoiceField(choices=range(1,6), label='What is your occupation?', widget=forms.RadioSelect)

choices is set to an integer value.


text:
Q: Finding the source of a large amount of data added to hard drive Basically, a few days ago a saw that my C drive randomly went from 17 GB free to 1 GB free and I'm trying to find the source of it. Windows search using datecreated or datemodified is quite cumbersome to use; is there any program out there that can analyze this and show data such as large allocation of hard drive space in a small amount of time?

A: Grab something like WinDirStat.  Anything taking up 16 GB as a single file or as a folder should stand out fairly readily.

A: It could well be your Windows 10 upgrade. Even though you probably declined the upgrade, Microsoft will download it anyway ('so you have it when you want it').
The already recommended procedures will help you to identify the files' location. There is little sense in simply deleting them though, as Windows will just download them again for you (how nice of Microsoft).
I cannot produce the complete details here, but there's ways to prohibit it. Google 'avoid Windows 10 download'.


text:
Q: Get textAttachment in UITextView I have an NSTextAttachment. I need to have some identifier attached to it, so I did this:
textAttachment.setValue(id, forKey: idKey)

In shouldChangeTextIn range, I have:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
   if text.isEmpty && textView.textStorage.containsAttachments(in: range) {
       // retrieve textAttachment
   }
   return true
}

I want to retrieve the textAttachment and its id if the user deletes it (by pressing the backspace button on the keyboard).
How can I get the textAttachment in a UITextView given the range it is in?


text:
Q: Rudin's proof on Poincare Lemma. Two identical questions are here:
A question about differential forms
and here:
http://mathforum.org/kb/thread.jspa?forumID=13&threadID=2141549&messageID=7208112
In his proof, Rudin says that $\gamma$ is "clearly" $C^1$, which I found a bit confusing. Each $F_i$ was $C^1$ as proved, why is it clear that $\gamma$ is also $C^1$? Doesn't it require each $F_i$ to be $C^2$ in order for the partial derivatives to be $C^1$?
The problem is on the bottom of page 279 of Principles of Mathematical Analysis.
Rudin's Original Text Shot:


text:
Q: Why does Gnome-Shell act differently on my desktop than my laptop? Another question today; I have gnome-shell installed on both my laptop and my desktop, but on my desktop it acts entirely different then if it is on my laptop.
I know that sounds weird, so here is a description:
On my laptop, Gnome-Shell is used through a menu (accessed using the windows button on my keyboard, or an on-screen button) which lists all my open applications and workspaces. I prefer this version greatly.
On my desktop, though, Gnome-Shell acts nothing like this. Instead, the top of the screen lists applications and places. Through applications I can access, obviously, the different applications, and through places I access the home folder and the like.
These two enviroments are entirely different, yet both go under the moniker "Gnome-Shell". How is this, and how do I convert my desktop to the laptop format of gnome-shell?

A: I suspect your desktop may have entered fallback mode. It's not the actual gnome-shell. Can you tell me the specs of your desktop. You'll enter enter fallback mode if you haven't got the appropriate drivers for your video card. Or if your hardware simply can't support the shell.


text:
Q: Can I suspend Java runtime on method entry to have time to attach by debugger or profiler? Is there a way to suspend all business-logic execution threads of Java process when execution hits some method?
If  it is not possible via external configuration is there any method call to embedd into application to achieve desired result?

A: According to how to profile application startup with visualvm I can start application with
-Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=y

to stop execution on app startup.
May be it would be possible to set breakpoint and move to interesting app state and then attach with profiler and start app again.
Another option is to start with Java agent: https://visualvm.github.io/startupprofiler.html

A: One solution is the place this code right before the method you want to debug:

System.out.println("Press Any Key To Continue...");
new java.util.Scanner(System.in).nextLine();

This waits until you press enter, so you have time to attach your debugger.
Another method is to use the IDE Netbeans, which contains a debugger and allows you to set breakpoints anywhere.


text:
Q: RMarkdown: Why do I have to reinstall all packages everytime I knit? I have the following R code in one of my RMarkdown scripts:
install.packages("dplyr", repos="http://cran.us.r-project.org")
install.packages("tidyr", repos="http://cran.us.r-project.org")
install.packages("ggplot2", repos="http://cran.us.r-project.org")
library(dplyr)
library(tidyr)
library(ggplot2)
library(scales)
options(scipen = 999)
source("classify.r")

When I "knit" the Markdown to HTML with Shift+Ctrl+K, the packages are successfully installed and loaded. However, when I re-knit it, the packages are installed from scratch, every time - although I already have them, and that takes a while.
I am using RStudio.
How can I circumvent this without having to comment the respective lines?

A: Since "require returns (invisibly) a logical indicating whether the required package is available" you can conveniently use it for programming to either load the package or, if it's not available, (try to) install it and load it afterwards. So you could modify your code along the lines of:
if (!require(dplyr)) {
    install.packages("dplyr")
    require(dplyr)
}

This should load the package if it's already available or if not, try to install it and load it afterwards.

A: ```{r chunkNameHere, cache=TRUE}
install.packages("dplyr", repos="REPOLINK")
install.packages("tidyr", repos="REPOLINK")
install.packages("ggplot2", repos="REPOLINK")
library("dplyr")
library("tidyr")
library("ggplot2")
```

The 'cache' flag should ensure the packages aren't reinstalled each time.
Here is the output from the first time I knit:
  |................................                                 |  50%
  ordinary text without R code

  |.................................................................| 100%
label: chunkNameHere (with options)
List of 1
 $ cache: logi TRUE

processing file: Untitled.Rmd
trying URL 'REPOLINK'
Content type 'application/x-gzip' length 3870896 bytes (3.7 Mb)
opened URL
==================================================
downloaded 3.7 Mb

trying URL 'REPOLINK'
Content type 'application/x-gzip' length 72424 bytes (70 Kb)
opened URL
==================================================
downloaded 70 Kb

trying URL 'REPOLINK'
Content type 'application/x-gzip' length 2671874 bytes (2.5 Mb)
opened URL
==================================================
downloaded 2.5 Mb

/Applications/RStudio.app/Contents/MacOS/pandoc/pandoc Untitled.utf8.md --to html --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash-implicit_figures --output Untitled.html --smart --email-obfuscation none --self-contained --standalone --section-divs --template /Library/Frameworks/R.framework/Versions/3.1/Resources/library/rmarkdown/rmd/h/default.html --variable 'theme:bootstrap' --include-in-header /var/folders/l2/qcrxbd0s36x7jkk4k2szc9dr0000gn/T//Rtmpcy2bZL/rmarkdown-str8c75262f5f18.html --mathjax --variable 'mathjax-url:https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML' --no-highlight --variable highlightjs=/Library/Frameworks/R.framework/Versions/3.1/Resources/library/rmarkdown/rmd/h/highlight
output file: Untitled.knit.md

Output created: Untitled.html

And here it is when I run it a second time:
  |................................                                 |  50%
  ordinary text without R code

  |.................................................................| 100%
label: chunkNameHere (with options)
List of 1
 $ cache: logi TRUE

/Applications/RStudio.app/Contents/MacOS/pandoc/pandoc Untitled.utf8.md --to html --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash-implicit_figures --output Untitled.html --smart --email-obfuscation none --self-contained --standalone --section-divs --template /Library/Frameworks/R.framework/Versions/3.1/Resources/library/rmarkdown/rmd/h/default.html --variable 'theme:bootstrap' --include-in-header /var/folders/l2/qcrxbd0s36x7jkk4k2szc9dr0000gn/T//Rtmp0WIDxR/rmarkdown-str8c8a542dd362.html --mathjax --variable 'mathjax-url:https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML' --no-highlight --variable highlightjs=/Library/Frameworks/R.framework/Versions/3.1/Resources/library/rmarkdown/rmd/h/highlight

processing file: Untitled.Rmd
output file: Untitled.knit.md

Output created: Untitled.html


text:
Q: How do I remove Amazon app but keep google apps? I'm using Ubuntu 12.10. Whenever I go to an amazon webpage it keeps popping up an 'Amazon app' in my Unity taskbar. I find this relatively useless because I'm already on the Amazon website.
I uninstalled it but it ended up uninstalling all my google and other apps as well. When I tried reinstalling the gmail app, it also reinstalled the Amazon app! Is there a way to separate Amazon from the other apps?

A: Try reinstalling unity-webapps-gmail


text:
Q: python: Using ncurses when underlying library logs to stdout I am trying to write a small python program that uses curses and a SWIGed C++ library. That library logs a lot of information to STDOUT, which interferes with the output from curses. I would like to somehow intercept that content and then display it nicely through ncurses. Is there some way to do this?

A: A minimal demonstrating example will hopefully show how this all works.  I am not going to set up SWIG just for this, and opt for a quick and dirty demonstration of calling a .so file through ctypes to emulate that external C library usage.  Just put the following in the working directory.
testlib.c
#include <stdio.h>

int vomit(void);

int vomit()
{
    printf("vomiting output onto stdout\n");
    fflush(stdout);
    return 1;
}

Build with gcc -shared -Wl,-soname,testlib -o _testlib.so -fPIC testlib.c
testlib.py
import ctypes
from os.path import dirname
from os.path import join

testlib = ctypes.CDLL(join(dirname(__file__), '_testlib.so'))

demo.py (for minimum demonstration)
import os
import sys
import testlib
from tempfile import mktemp

pipename = mktemp()
os.mkfifo(pipename)
pipe_fno = os.open(pipename, os.O_RDWR | os.O_NONBLOCK)
stdout_fno = os.dup(sys.stdout.fileno())

os.dup2(pipe_fno, 1)
result = testlib.testlib.vomit()
os.dup2(stdout_fno, 1)

buf = bytearray()
while True:
    try:
        buf += os.read(pipe_fno, 1)
    except Exception:
        break

print("the captured output is: %s" % open('scratch').read())
print('the result of the program is: %d' % result)
os.unlink(pipename)

The caveat is that the output generated by the .so might be buffered somehow within the ctypes system (I have no idea how that part all works), and I cannot find a way to flush the output to ensure they are all outputted unless the fflush code is inside the .so; so there can be complications with how this ultimately behaves.
With threading, this can be done also (code is becoming quite atrocious, but it shows the idea):
import os
import sys
import testlib
from threading import Thread
from time import sleep
from tempfile import mktemp

def external():
    # the thread that will call the .so that produces output
    for i in range(7):
        testlib.testlib.vomit()
        sleep(1)

# setup
stdout_fno = os.dup(sys.stdout.fileno())
pipename = mktemp()
os.mkfifo(pipename)
pipe_fno = os.open(pipename, os.O_RDWR | os.O_NONBLOCK)
os.dup2(pipe_fno, 1)

def main():
    thread = Thread(target=external)
    thread.start()

    buf = bytearray()
    counter = 0
    while thread.is_alive():
        sleep(0.2)
        try:
            while True:
                buf += os.read(pipe_fno, 1)
        except BlockingIOError:
            if buf:
                # do some processing to show that the string is fully
                # captured
                output = 'external lib: [%s]\n' % buf.strip().decode('utf8')
                # low level write to original stdout
                os.write(stdout_fno, output.encode('utf8'))
                buf.clear()
        os.write(stdout_fno, b'tick: %d\n' % counter)
        counter += 1

main()

# cleanup
os.dup2(stdout_fno, 1)
os.close(pipe_fno)
os.unlink(pipename)

Example execution:
$ python demo2.py
external lib: [vomiting output onto stdout]
tick: 0
tick: 1
tick: 2
tick: 3
external lib: [vomiting output onto stdout]
tick: 4

Note that everything is captured.
Now, since you do have make use of ncurses and also run that function in a thread, this is a bit tricky.  Here be dragons.

We will need the ncurses API that will actually let us create a new screen to redirect the output, and again ctypes can be handy for this.  Unfortunately, I am using absolute paths for the DLLs on my system; adjust as required.
lib.py
import ctypes

libc = ctypes.CDLL('/lib64/libc.so.6')
ncurses = ctypes.CDLL('/lib64/libncursesw.so.6')

class FILE(ctypes.Structure):
    pass

class SCREEN(ctypes.Structure):
    pass

FILE_p = ctypes.POINTER(FILE)
libc.fdopen.restype = FILE_p
SCREEN_p = ctypes.POINTER(SCREEN)
ncurses.newterm.restype = SCREEN_p
ncurses.set_term.restype = SCREEN_p
fdopen = libc.fdopen
newterm = ncurses.newterm
set_term = ncurses.set_term
delscreen = ncurses.delscreen
endwin = ncurses.endwin

Now that we have newterm and set_term, we can finally complete the script.  Remove everything from the main function, and add the following:
# setup the curse window
import curses
from lib import newterm, fdopen, set_term, endwin, delscreen
stdin_fno = sys.stdin.fileno()
stdscr = curses.initscr()
# use the ctypes library to create a new screen and redirect output
# back to the original stdout
screen = newterm(None, fdopen(stdout_fno, 'w'), fdopen(stdin_fno, 'r'))
old_screen = set_term(screen)
stdscr.clear()
curses.noecho()
border = curses.newwin(8, 68, 4, 4)
border.border()
window = curses.newwin(6, 66, 5, 5)
window.scrollok(True)
window.clear()
border.refresh()
window.refresh()

def main():

    thread = Thread(target=external)
    thread.start()

    buf = bytearray()
    counter = 0
    while thread.isAlive():
        sleep(0.2)
        try:
            while True:
                buf += os.read(pipe_fno, 1)
        except BlockingIOError:
            if buf:
                output = 'external lib: [%s]\n' % buf.strip().decode('utf8')
                buf.clear()
                window.addstr(output)
                window.refresh()
        window.addstr('tick: %d\n' % counter)
        counter += 1
        window.refresh()

main()

# cleanup
os.dup2(stdout_fno, 1)
endwin()
delscreen(screen)
os.close(pipe_fno)
os.unlink(pipename)

This should sort of show that the intended result with the usage of ncurses be achieved, however for my case it hung at the end and I am not sure what else might be going on. I thought this could be caused by an accidental use of 32-bit Python while using that 64-bit shared object, but on exit things somehow don't play nicely (I thought misuse of ctypes is easy, but turns out it really is!).  Anyway, this least it shows the output inside an ncurse window as you might expect.

A: @metatoaster indicated a link which talks about a way to temporarily redirect the standard output to /dev/null.  That could show something about how to use dup2, but is not quite an answer by itself.
python's interface to curses uses only initscr, which means that the curses library writes its output to the standard output.  The SWIG'd library writes its output to the standard output, but that would interfere with the curses output.  You could solve the problem by

*

*redirecting the curses output to /dev/tty, and

*redirecting the SWIG'd output to a temporary file, and

*reading the file, checking for updates to add to the screen.

Once initscr has been called, the curses library has its own copy of the output stream.  If you can temporarily point the real standard output to a file first (before initializing curses), then open a new standard output to /dev/tty (for initscr), and then restore the (global!) output stream then that should work.


text:
Q: Unresolved external symbol _parallel_manager referenced in function _main When trying to compile a program including a CUDA file, I get an error code of LNK2019, but I specifically made sure to include the relevant header file at the beginning of the code:
#include "parallel_functions.cuh"

Which consists entirely of:
#ifndef parallel_functions_cuh
#define parallel_functions_cuh

void
parallel_manager(image_chunk ***image_grid, network_chunk *** network_grid);

#endif

With an earlier program it was simple enough for me to include everything in one file (which removed the linker errors) but with this program that would not be a valid option.
The only reference I can find to this particular error with CUDA are in this prior question but the solutions there are already applied, with all libraries included.
The same error occurs in the simple example project consisting of launch.c, kernel.cu, and kernel.cuh.
launch.c:
#include "kernel.cuh"

void main()
{
    parallel_function();
}

kernel.cuh:
#ifndef kernel_cuh
#define kernel_cuh

void parallel_function();

#endif

kernel.cu:
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdio.h>

__global__ void kernel(char *a)
{
    a[threadIdx.x] = threadIdx.x;
}

void parallel_function()
{
    char* data;
    cudaMallocManaged(&data, 256);

    kernel<<<1, 256>>>(data);
    cudaDeviceSynchronize();

    for (int i = 0; i < 256; i++)
    {
        printf("%d ", data[i]);
    }

    cudaFree(data);
}

Which gives the following build output:
1>------ Build started: Project: ErrorProject, Configuration: Debug Win32 ------
1>  launch.c
1>launch.obj : error LNK2019: unresolved external symbol _parallel_function referenced in function _main
1>C:\Error\ErrorProject\Debug\ErrorProject.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

With the error list furthermore containing this:
LNK2019 unresolved external symbol _parallel_function referenced in function _main

The build dependencies use the default CUDA V8.0 targets, including the toolkit dependencies and cudart.lib in the linker settings.

A: Based on the comments, this appears to have been a mismatch between C-style linking and C++-style linking (also probably evident from the unresolved symbol itself -- which does not appear to be mangled).
nvcc uses C++-style compiling and linking.  C-style functionality can be accommodated but requires special handling, which is covered in many places here on the CUDA tag and elsewhere, so I'll not repeat that here.
By default, a number of compilers (apparently including the host compiler here) treat filenames ending in .c as implicitly specifying C-style linking.  As a result, the requested function in OP's source file (launch.c) could not be resolved against a provider elsewhere in the project, which was providing C++-style link points.
A possible solution in this case was to rename the launch.c to launch.cpp, which converted to C++ style linking for the whole project, resulting in consistency.


text:
Q: ActiveRecord: Column 'nivelAcceso' cannot be null I need to add a 'Change password' feature to the app I'm currently building, but when I try to change an user's password, I get the following error:
Column 'nivelAcceso' cannot be null; While the user's password and 'nivelAcceso' (the access the user has in the application) are found on the same table (usuarios) they aren't related in any way.
The route that handles the password change looks like this:
app.rb
put '/:id' do
change_password(params[:id], params[:password], params[:confirm])
end

While the controller looks like:
password_controller.rb
def change_password(id, password, confirm)
if password.nil? || confirm.nil?
redirect '/dashboard/change_password', error: 'Debe completar todos los campos.'
elsif password != confirm
redirect '/dashboard/change_password', error: 'Los campos no coinciden.'
else
u = User.find(id)

new_password = BCrypt::Password.create(password)

u.passwordUsuario = new_password

if u.save
  redirect '/dashboard/change_password', notice: 'Cambio de contraseña exitoso.'
else
  redirect '/dashboard/change_password', error: 'Ha ocurrido un error, intente nuevamente.'
end
end
end

I have tried the following with no avail so far:
u.nivelAcceso = session[:rol] # 'nivelAcceso' value is stored in the session

A: ActiveRecord says the column can't be null. This is usually due to the database being configured this way.
If you configured the database using ActiveRecord migrations, look for something like this:
create_table(:cars) do |t|
  # other commands
  t.string :foo, null: false
end

You can change this by writing and running a new migration:
change_column :table_name, :foo_column, :string, null: true

A: Turns out the route to change the password is exactly the same as the route to edit an user.
Original, non-working route:
put '/:id' do
change_password(params[:id], params[:password], params[:confirm])
end

Edited, working route:
put '/change_password/:id' do
change_password(params[:id], params[:password], params[:confirm])
end


text:
Q: Character for missing paragraph I am looking for a character to indicate a missing paragraph. It is used in German schools when correcting essays.
The character is used like this and looks like the red one here (source):

I have tried:

*

*detexify, but the best results are just \rfloor and \lceil, where I would need a combination of both

*googling for latex missing paragraph, which yields a lot of results regarding \paragraph, which is not what I need.

I am not looking for ¶ \textparagraph, of course.


text:
Q: Changing user while scp I need to copy file between Linux machines. The problem that the user I use to login (myuser), is different from the user that can access the file.
If I just ssh to the machine, I can switch the user using sudo su someuser, can I do it somehow while scp?
While using WinSCP I managed to do it, by configuring the SCP/Shell, so I believe there must be a similar way to do it via pure shell.

A: If you know the credentials to the other user (someuser) you can just specify it on your scp call.
From the man scp page:

File names may contain a user and host specification to indicate that
  the
       file is to be copied to/from that host.  Local file names can be made
       explicit using absolute or relative pathnames to avoid scp treating file
       names containing ':' as host specifiers.  Copies between two remote hosts
       are also permitted.

Here's the syntax used:
[[user@]host:]/path/to/file

Example
You want to copy the file /home/foo/bar from host1 to your localhost, using user someuser, here's the command:
scp someuser@host1:/home/foo/bar .

You will be asked for authentication (password, keys, ...).

A: Assuming that the user you CAN ssh to doesn't need a password to sudo su into the target user, you can try this:
dd if=myfile | ssh some.host "sudo -u targetuser dd of=myfile"

... Mind, I'm still unconvinced that simply configuring targetuser to only allow scp/sftp/rsync over SSH and using a RSA keypair for authentication isn't a much better option.

A: It's probably possible, but I'd say it's a very awkward way to go about it.
My first suggestion is to login as that user. Even if you don't have that user's password, you can add your own public ssh key to their authorized_keys and then scp using their key, as rahmu shows.
If that's not possible, my second suggestion is to login by ssh, sudo to the user and create a tarfile of the files you want to copy and put it somewhere that your own user can read. Then scp down that tarfile.

A: use -S on the scp command
e.g. https://superuser.com/questions/87597/how-to-perform-scp-as-a-sudo-user
it will allow you to execute a script, on much like i believe you were doing with the winscp use case.

A: I tried to give some examples in the following article. Basic idea is not use scp, but use dd and ssh with sudo user switch. Look:
http://hmmss.wordpress.com/2014/07/02/ssh-and-scp-with-another-user


text:
Q: IFormFileCollection: Cannot access a Disposed Object I am trying to upload a document into Azure Blob but it throws an error as below while reading the file stream.
Error,
Cannot access a disposed object.
Object name: 'FileBufferingReadStream'.

The error comes when the code OpenReadStream() called,
public async Task UploadAsync(IFormFileCollection files, string directoryName)
    {
        var blobContainer = await _azureBlobConnectionFactory.GetBlobContainer();
        CloudBlobDirectory directory = blobContainer.GetDirectoryReference(directoryName);
        for (int i = 0; i < files.Count; i++)
        {
            CloudBlockBlob blockblob = directory.GetBlockBlobReference(files[i].FileName);
            using (var stream = files[i].OpenReadStream())
            {
                await blockblob.UploadFromStreamAsync(stream);

            }
        }
    }

I am calling the UploadAsync method from my actual service classs like,
public async Task<bool> UploadToBlob(DocumentModel model,string directorypath)
    {
        try
        {
            //string directory = directorypath + model.EmailId + "/" + model.Files[0].FileName;
            await _blobService.UploadAsync(model.Files, "Documents/dummy.pdf");

            return true;
        }
        catch(Exception e)
        {
            throw e;
        }
    }

Where I did go wrong?

A: *

*The return method of Action method can be a possible reason for this issue

*The error occurs if the return type is not Task<T>.
You can modify your Action Method as follows:

[HttpPost]
public async Task<int> ActionMethod(IFormFile img)
{
     // same

     return resultValue;
}

References :

*

*When trying to upload file, FileBufferingReadStream.ThrowIfDisposed() error occur

*Cannot access a disposed object. Object name: FileBufferingReadStream

*IFormFile copy to memorystream ObjectDisposedException


text:
Q: $M = \max (X,Y)$ with $X$, $Y$ independent uniform variables over $[0,1]$. Find CDF of $M$ and $E[M]$ Suppose that $X$ and $Y$ are independent uniform $[0,1]$ random variables. Find the CDF
$F(x)$ for the random variable $M = \max(X,Y)$ and find $E[M]$.
So $M$ will be uniform over $[0,1]$ and is the probability of $(0 < M < k)$ the probability that $(0 < X < k) + (0 < Y < k)$? I am not even sure if I should assume these variables are discrete or continuous..
Would the cumulative distribution function be:
$0$ when $M < 0$
$2M/1$ when $0 < M < 1$
$1$ when $M \geq 1$
and would $E[M]$ simply be $E[X] = E[Y] = 1/2$?
I have a feeling something is going over my head here. Is what I am doing correct?
Thank you!

A: no $E(M) \ne 1/2$.
You need to find
$P(\max(X,Y) \le m)$. When is max of two numbers less than a given value?


text:
Q: Scroll element in selenium VBA I am trying to focus on an element to make this element in the center of the screen or way from the top to be above the middle.
This is what I did
.FindElementById("toBePaid[" & r - 1 & "]").ExecuteScript "this.scrollIntoView(true); window.scrollBy(0, -(window.innerHeight - this.clientHeight)-150);"

But I couldn't see the element as it is at the top-most of the screen of the website.
I have tried too
.FindElementById("toBePaid[" & r - 1 & "]").ScrollIntoView True

But the same problem is still there.

A: With the help of @QHarr I could dolve it
Function ScrollIntoViewCenter(element As WebElement)
  Const JS_SCROLL_CENTER = _
    "this.scrollIntoView(true);" & _
    "var y = (window.innerHeight - this.offsetHeight) / 2;" & _
    "if (y < 1) return;" & _
    "for (var e=this; e; e=e.parentElement) {" & _
    "  if (e.scrollTop == 0) continue;" & _
    "  var yy = Math.min(e.scrollTop, y);" & _
    "  e.scrollTop -= yy;" & _
    "  if ((y -= yy) < 1) return;" & _
    "}" & _
    "window.scrollBy(0, -y);"

  element.ExecuteScript JS_SCROLL_CENTER
End Function


text:
Q: Word count in MapReduce I have seen threads having resolution to this error but somehow the solutions don't help me.
I am running the code below :
public class WordCount
{
    public static class MyMapper extends Mapper<LongWritable,Text,Text,IntWritable>
    {
        final static IntWritable one=new IntWritable(1);
        Text word=new Text();

        public void map(LongWritable key,Text Value,Context context) throws IOException,InterruptedException
        {
            String line=Value.toString();
            StringTokenizer itr=new StringTokenizer(line);
            while (itr.hasMoreTokens())
            {
                word.set(itr.nextToken());
                context.write(word, one);
            }
        }

    }

    public static class MyReducer extends Reducer<Text,IntWritable,Text,IntWritable>{

        public void reduce(Text Key,Iterable<IntWritable> Values,Context context) throws IOException,InterruptedException
        {
            int sum=0;
            for (IntWritable value:Values)
            {
                sum=sum+value.get();
            }
            context.write(Key, new IntWritable(sum));}

        public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException
        {

            //Job job=new Job();
            Configuration conf=new Configuration();
            Job job=new Job(conf,"Word Count");

            job.setJarByClass(WordCount.class);
            job.setMapperClass(MyMapper.class);
            job.setReducerClass(MyReducer.class);
            job.setOutputKeyClass(Text.class);
            job.setOutputValueClass(IntWritable.class);
            FileInputFormat.addInputPath(job, new Path(args[0]));
            FileOutputFormat.setOutputPath(job,new Path(args[1]));
            System.exit(job.waitForCompletion(true) ? 0 : 1);
        }
    }
}

It has the main method in proper format.
It stil gives me the error below when I'm trying to run it.
 **hadoop jar MyTesting-0.0.1-SNAPSHOT.jar MyPackage.WordCount <Input> <Output>**
Exception in thread "main" java.lang.NoSuchMethodException: MyPackage.WordCount.main([Ljava.lang.String;)
        at java.lang.Class.getMethod(Class.java:1670)
        at org.apache.hadoop.util.RunJar.run(RunJar.java:215)
        at org.apache.hadoop.util.RunJar.main(RunJar.java:136)


text:
Q: Dynamic Button Icon Windows app I'm trying to do a pause/play button windows 10 app.
So far I know 3 ways to set the button using
button.context = "some segoe code"  - works fine when I initialize it with the button but on the code to change the context the button appears as a bunch of squares
Button symbolicon - works fine initializing but no idea how to alter the symbolicon value outside of button declaration
button uri - only thing I could find online about button changing, but I don't have the button libraries that come in windows phone...
what is your recommendations so on clickrelease the button changes to either the pause or the play

A: I have used SymbolIcon to achieve the toggle play/pause.
XAML:
<Button Click="play_Click">
    <SymbolIcon x:Name="play" Symbol="Play"/>
</Button>

C# code behind:
private void play_Click(object sender, RoutedEventArgs e)
{
    if (play.Symbol.Equals(Symbol.Play))
    {
        play.Symbol = Symbol.Pause;
    }
    else if (play.Symbol.Equals(Symbol.Pause))
    {
        play.Symbol = Symbol.Play;
    }
}

Comment if you encounter any issues.