text:
Q: Can't use Python's sh module in Bazel genrule When I run a python script, which uses the 'sh' module, from bazel genrule, it failed with this:
INFO: Analysed target //src:foo_gen (8 packages loaded).
INFO: Found 1 target...
ERROR: /home/libin11/workspace/test/test/src/BUILD:1:1: Executing genrule //src:foo_gen failed (Exit 1)
Traceback (most recent call last):
  File "src/test.py", line 2, in <module>
    sh.touch("foo.bar")
  File "/usr/local/lib/python2.7/dist-packages/sh.py", line 1427, in __call__
    return RunningCommand(cmd, call_args, stdin, stdout, stderr)
  File "/usr/local/lib/python2.7/dist-packages/sh.py", line 767, in __init__
    self.call_args, pipe, process_assign_lock)
  File "/usr/local/lib/python2.7/dist-packages/sh.py", line 1784, in __init__
    self._stdout_read_fd, self._stdout_write_fd = pty.openpty()
  File "/usr/lib/python2.7/pty.py", line 29, in openpty
    master_fd, slave_name = _open_terminal()
  File "/usr/lib/python2.7/pty.py", line 70, in _open_terminal
    raise os.error, 'out of pty devices'
OSError: out of pty devices
Target //src:foo_gen failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 2.143s, Critical Path: 0.12s
INFO: 0 processes.
FAILED: Build did NOT complete successfully

I want to integrate a thirdparty project to my own. The third party project is built with a python script, so I would like to build the project with bazel genrule.
Here is an example file list:
.
├── src
│   ├── BUILD
│   └── test.py
└── WORKSPACE

WORKSPACE is empty, BUILD is:
genrule(
    name = "foo_gen",
    srcs = glob(["**/*"]),
    outs = ["foo.bar"],
    cmd = "python $(location test.py)",
)

test.py is:
import sh
sh.touch("foo.bar")

And run:
bazel build //src:foo_gen

OS: Ubuntu 16.04
bazel: release 0.14.1

A: It looks like if you change the call to sh.touch("foo.bar", _tty_in=False, _tty_out=False) it works, but you'll still need a bit of modification to the genrule otherwise it won't produce output.
I prefer to import pip dependencies using the bazel python rules, so I can create the tool for my genrule. This way, bazel handles the pip requirement install and you don't have to chmod the test.py file.
load("@my_deps//:requirements.bzl", "requirement")

py_binary(
    name = "foo_tool",
    srcs = [
        "test.py",
    ],
    main = "test.py",
    deps = [
        requirement("sh"),
    ],
)

genrule(
    name = "foo_gen",
    outs = ["foo.bar"],
    cmd = """
      python3 $(location //src:foo_tool)
      cp foo.bar $@
    """,
    tools = [":foo_tool"],
)

Note the required copy in the genrule command. It's a bit cleaner if your python script can output to std out, then you can just redirect the output to the file instead of adding a copy command. See this for more info.
My output with these changes:
INFO: Analysed target //src:foo_gen (0 packages loaded).
INFO: Found 1 target...
Target //src:foo_gen up-to-date:
  bazel-genfiles/src/foo.bar
INFO: Elapsed time: 0.302s, Critical Path: 0.00s
INFO: 0 processes.
INFO: Build completed successfully, 1 total action


text:
Q: Is the mass of Higgs bosons measured only through the decay into photons? I'm reading an essay discussing the measurement of Higgs boson mass: https://cms.cern/news/cms-precisely-measures-mass-higgs-boson, which says that the latest and more accurate measurement results came from two procedures. One of them looked at decays to two Z bosons, which subsequently decay into electron or muon pairs, and the other focused on decays to two photons in the Figure below.

I also found similar graphs which feature other Higgs decay mechanisms, such as

I can see for both decays, the products are around 125 GeV, which is also the mass of the Higgs boson. My question is why don't experimentalists determine the mass through the second (or other) decay processes? What else information can we learn from the graphs like this?
Many thanks for the help!

A: In principle, all of the different major Higgs channels, from both the CMS and ATLAS groups, can be combined to determine the mass. For an intro into the sort of things that go into this process (which is used for many Higgs parameters), you can read this talk.
$\rm H\to\gamma\gamma$ is a relatively rare decay, but it is very clean and has low backgrounds. By comparison something like $\rm H\to b\bar{b}$ is much more common but has a huge background and is much more complicated to analyze.
It turns out that if you only care about the mass, it tends to be much better to go with the "rare but clean" decay as it gives a very clear indication of the mass without the larger systematic errors that can build up with more complicated decays.

redpajama_set_name: RedPajamaStackExchange


text:
Q: 10-digits BigDecimal cannot be saved in NUMBER(10, 2) column In a Oracle 12 database, one of my column is defined with NUMBER(10,2). The goal is to store numbers like that one: 12345678.12. Actually, I can store a such number thank to Oracle SQL Developer, so the format is matching.
Through my Hibernate-Java app, when I update an entity containing the following values, it works:
1.12
12.12
123.12
1234.12
12345.12
123456.12

But with the following, I get an error
1234567.12
12345678.12

ORA-01438: value larger than specified precision allowed for this column

It looks like a NUMBER(8, 2)...
The field is in an @Embeddable class, type BigDecimal, without any field annotation:
@Entity
@Table(...)
public class ClassA implements Serializable {

    @Embedded
    private ClassB bObject;
}

@Embeddable
public class ClassB implements Serializable {

    @Embedded
    private ClassC cObject;
}

@Embeddable
public class ClassC implements Serializable {

    private BigDecimal myField;
}

Is there any other things that can override my column definition?

A: The first number in the decimal type is the precision, the second digit is the scale.
From Oracle's documentation:

You can specify the precision (the total number of digits, both to the
  left and the right of the decimal point) and the scale (the number of
  digits of the fractional component).

If you have 10 digits before the fraction, you need a DECIMAL(12,2).
The error you see comes from Oracle, not Hibernate, so I doubt changing your entity configuration will solve your issue.

A: Thank to @Guillaume F., I enabled the trace logging for log4j and I discovered that the error occured in an audit table which was not up to date. The column definition still was NUMBER(8,2) instead of NUMBER(10,2)


text:
Q: Monodroid pass int[] in Intent I have two activity A, and B. I start activity B from activity A, like this:
var intent = new Intent(this, typeof (BActivity));
StartActivityForResult(intent, 1);

If you press a button on activity B, i have to pass an int[] array to activity A, i created a test code which does this:
var intent = new Intent();
int[] array = {1, 2, 3};
intent.PutExtra("__extra__", array);
SetResult(Result.Ok, intent);
Finish();

But whenever I try to get this value from the intent, i receiving null. Here is how i tried:
var value = data.GetIntArrayExtra("__extra__");

What am I doing wrong here? I tried the same with string, and it worked, it seems to me, that just the int array is not working...

A: try it as :
Bundle bdl = new Bundle();
int[] array = {1, 2, 3};
bdl.PutIntArray("__extra__",array);

Intent intent = new Intent();
intent.PutExtra("extra", bdl);
SetResult(Result.Ok, intent);
Finish();

and on OnActivityResult :
Bundle credBdl = data.GetBundleExtra("extra");
int[] array=credBdl.GetIntArray("__extra__");


text:
Q: trying to build a web ui tree from scratch I have seen yahoo ui using div for every node of the tree. Is this a good thing to do. Seems like every node including leaf node is heavily nested. I saw a div, table, tr, td being used for creating a node. Is this necessary. Is there a better way to do the same.
I tried to us tr for every node. Are there any issues with this approach
Thanks

A: Try this: Pure CSS Tree


text:
Q: How do I map a nested collection, Map>, with hibernate JPA annotations? I have a class I am not sure how to annotate properly.
My goal for Holder::data:

*

*List should maintain order not by comparator but by the natural ordering of the elements in the array. (Which can be an ndx column if that is helpful.)

*Holder will have the only reference to data, so Cascade all is probably applicable as well.

I am also open to a different design that removes the map, if that would make for a cleaner design.
@Entity
public class Holder extends DomainObject {
  private Map<Enum,List<Element>> data;
}

@Entity
public class Element extends DomainObject {
  private long valueId;
  private int otherData;
}

@Mappedsuperclass
public class DomainObject {
 // provides id
 // optimistic locking
 // create and update date
}

A: Here is a blog about collection of collections in hibernate http://blog.xebia.com/2007/10/05/mapping-multimaps-with-hibernate/
Hope it will help. It helped me.
Regards,
Anton

A: I don't think it is possible with hibernate(-core) to map any collection of collections:

Collections may contain almost any
other Hibernate type, including all
basic types, custom types, components,
and of course, references to other
entities.

(from the official doc)
Notice the almost and the omission of the collection type.
A workaround: You need to introduce a new type 'in between' the collection holder and the element. This type you can map as an entity or a component and it refers the original content of the map, in this case a list.
Something like:
@Entity
public class Holder extends DomainObject {
  @OneToMany
  private Map<Enum,InBetween> inBetweens;
}

@Entity
public class InBetween extends DomainObject {
  @OneToMany
  private List<Element> elements;
}

@Entity
public class Element extends DomainObject {
  private long valueId;
  private int otherData;
}

@Mappedsuperclass
public class DomainObject {
 // provides id
 // optimistic locking
 // create and update date
}

The rest of the mapping depends on your particular situation, but is rather straightforward.

A: Please note that the referred link to the Hibernate documentation seems out of date, I found the following working: http://docs.jboss.org/hibernate/core/3.5/reference/en/html/collections.html


text:
Q: Attempting to move Files but unable to move Folders via Python I am trying to move files and folders from directory to another. I am currently facing two issues.

*

*It only seems to move files but not any folders.

*It only picks up the uppercase or lowercase.

Do you know what might be missing to do this. I could add an or statement statement with startswith but would like to see if there is a better way to do this.
import os
from os import path
import shutil

src = "C:/Users/test/documents/"
dst = "C:/Users/test/Documents/test"

files = [i for i in os.listdir(src) if i.startswith("C") and \
         path.isfile(path.join(src, i))]
for f in files:
    shutil.move(path.join(src, f), dst)

A: This will go through the source directory, create any directories that do not yet exist in the destination directory, and move the files from the source to the destination directory:
(As I understand it, this is what you want)
import os
import shutil

src = "C:/Users/test/documents/"
dst = "C:/Users/test/documents/test"

for src_dir, dirs, files in os.walk(src):
    dst_dir = src_dir.replace(src, dst, 1)
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
    for file_ in files:
        src_file = os.path.join(src_dir, file_)
        dst_file = os.path.join(dst_dir, file_)
        if os.path.exists(dst_file):
            os.remove(dst_file)
        shutil.move(src_file, dst_dir)


text:
Q: Flink, TaskManager not responding Here's the case, we have 3 kafka topic (each has 50 partitions), they have different messages, while all these messages have field 'username',
topic_1 --> Message01 {String username; ...}, about 50,000 messages per minute
topic_2 --> Message02 {String username; ...}, about 3,000,000 messages per minute
topic_3 --> Message03 {String username; ...}, about 70,000 messages per minute

And we've defined a wrapper class,
MessageWrapper{
 List<Message01> list01;
 List<Message02> list02;
 List<Message03> list03;
}

We have a flatMap, which 'convert' original message to a tuple3,
String field --> username
Integer field --> type
MessageWrapper field --> the wrapper object

All 3 streams are processed by similar flatMap() function,
public void flatMap(Message01 value, Collector<Tuple3<String, Integer, MessageWrapper>> out)
        throws Exception {
    String name = value.getUsername();
    if (!StringUtils.isBlank(name)) {
        MessageWrapper wrapper = new MessageWrapper();
        List<Message01> list = new ArrayList<>();
        list.add(value);
        wrapper.setList01(list);
        out.collect(new Tuple3<>(name, 1, wrapper));
    }
}

After the flatMap(), we union these 3 streams,
stream1.union(stream2, stream3).keyBy(0).timeWindow(Time.seconds(300))
        .process(
                new ProcessWindowFunction<Tuple3<String, Integer, MessageWrapper>, MessageWrapper, Tuple, TimeWindow>() {

                    @Override
                    public void process(Tuple key,
                            ProcessWindowFunction<Tuple3<String, Integer, MessageWrapper>, MessageWrapper, Tuple, TimeWindow>.Context ctx,
                            Iterable<Tuple3<String, Integer, MessageWrapper>> elements,
                            Collector<MessageWrapper> out) throws Exception {
                        // merge all entities which have same username, to get a big fat wrapper object
                        MessageWrapper w = new MessageWrapper();
                        for (Tuple3<String, Integer, MessageWrapper> t3 : elements) {
                            MessageWrapper ret = t3.f2;
                            Integer type = t3.f1;
                            if (type == 1) {
                                // add to list01
                            } else if (type == 2) {
                                // add to list02
                            } else if (type == 3) {
                                // add to list03
                            }
                        }

                        if (all 3 lists are not empty) {
                            out.collect(ret);
                        }
                    }
                });

Currently we use 20 taskmanager, each 4 cores + 16G, totally 80 slots, we use 50 parallelism through.
We always run into problem that taskmanager not responding due to too much full gc,
Connecting to remote task manager + 'xxxxxxxxxxxxx' has failed. This might indicate that the remote task manager has been lost".

If we reduce the time window from 5 minutes to 1 minutes, everything is fine. According to this, seems like the flink cluster doesn't have enough resource, but 80 cores + 320G for just several millions messages (the size of each message is about 5KB), should be enough right?
Anyone could shed some light here? Or probably there're some problems in the code?

A: I solved this problem on my cluster setup by commenting the line with 127.0.1.1 on the /etc/hosts file of all machines. And I increased the parallelism of slots on the property taskmanager.numberOfTaskSlots: of the conf/flink-conf.yaml file.


text:
Q: Does it make sense to put new or bad questioners in a "sandbox"? Apparently, Worldbuilders SE has a sandbox where new, or "bad" questioners can place their questions in a separate queue and have them critiqued, edited, etc. before they are placed "live" on the main site. That way, all this activity occurs without impacting the main site.
Does it make sense to have such a "sandbox" on other SE sites?

A: This is highly dependent on the culture of the specific site.
For example, the idea of a sandbox actually originated from Programming Puzzles & Code Golf. It's highly successful there because questions on PPCG are so different from other Stack Exchange sites. Questions are posted not to request help but to pose a challenge, and they typically require much more work and fine-tuning than questions on other sites. There are also lots of ways to go wrong in writing a programming challenge (loopholes, etc.), so a sandbox is useful to weed those out.
Worldbuilding is also a much broader and more open-ended site, so it possibly makes sense to have a sandbox there, too. (It's not as "special" as PPCG, though, so a sandbox isn't as necessary in my opinion, and indeed it's much less active than PPCG's.)
The question you should really be asking yourself if you're considering whether a site needs a sandbox is: What problem would this solve? In the case of PPCG, as @ChrisJester-Young puts it, "Currently, the sandbox is a buffer against duplicate, poorly-specified, uninteresting, or just generally inviable challenges. It makes the task of framing challenges a collaborative, community-orientated effort." For Worldbuilding, it's a way to help new users out and ease them in to the slightly unorthodox site and community, compared to other sites. It's really just a thing that should be decided on a case-by-case basis.

A: This is functionally what happens already when a question is closed.  It is a state that a question is placed in when it is not currently answerable and needs to be fixed up, while still allowing critique and improvement of the question.


text:
Q: Delphi, how to create component from TForm or how to add own properties to Object Inspector for inheritor of TForm I want all forms in project inherited from one base form. I now how it's doing. But I would like that in the Object Inspector for forms it was possible to change their own additional properties.
I tried to create a component:
unit FjForm;

interface

uses Forms, Classes;

type
  TFjForm = class(TForm)
  private
    FSelected: boolean;
  published
    property Selected: Boolean read FSelected write FSelected;
  end;

implementation
procedure Register;
begin
  RegisterComponents('Fj', [TFjForm]);
end;

end.

Он компилируется, но в Tool Palette не появляется. Потом я создаю форму и делаю вот так
unit FramworkFjForm;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, FjForm,
  Dialogs;

type
  TForm3 = class(TFjForm)
  private
    { Private declarations }
  public
    { Public declarations }
  end;

implementation

{$R *.dfm}

end.

В Object Inspector ничего не меняется.
Fixing dfm
instead of object I write inherited
After that, the form stops opening, writes Error creating form: Ancestor for 'TFjForm' not found.
Of course, you can set properties in the form and initialize them in FormCreate, but it's more convenient to do this in the Object Inspector.
How to make it possible to set custom properties in the Object Inspector for the form?


text:
Q: How can I make this background image responsive? wordpress Ok so I have a custom wordpress theme and have tried multiple different ways to get this to work.
The issue I'm having is that on mobile screens and small screens it crops the image instead of rescaling it to fit the screen.
I'm trying to edit the splash img here's the code.
    .stockimage {
/*background-image:url('../img/guitarpic.jpg');*/
background-image:url('../img/splash-2.png');
background-size:100% 100%;
background-size:cover;
background-position:center center;

}

I've also tried bootstrap etc but to no avail I haven't got it to work as of yet.

A: Fixed the issue by removing background-size:cover; and replacing with background-size: 100% 100%


text:
Q: How do I add hyperlink in my textarea in my MVC project? Hi I am working on ASP.NET MVC project. I have textarea in my view where user will get download link to report.
Currently I have this code in my view page :
 @if (ViewData["datalink"] != null && !String.IsNullOrEmpty(ViewData["datalink"].ToString()))
         {
          <textarea class="jquery_ckeditor" cols="65" id="editor1" name="editor1" rows="10">Your report is now available
@ViewData["datalink"].ToString()</textarea>
         }

For above code output will be like this :
Your automated report is now available
www.test.com
But Instead of showing user directly link, I need to provide text with hyperlink like this :
Your automated report is now available
DownloadLink
How can I achieve this??

A: This is not possible to do with a textarea. You could use a div construct instead with contenteditable property assigned to it:

Which will enable you to place hyperlinks inside + it will give you the same similar functionality as textarea.

A:
Its not fixed content. Your report is now available is editable. User
  can edit that.

Instead of TextArea, go for Editor like TinyMCE (with ASP.Net MVC) that will display the content as you need.


text:
Q: Apply multiple functions to a single data object - custom summary statistics How can we compute descriptive summary statistics for a matrix M on a per-column basis that include mean, standard deviation, and 5%, 25%, 50%, 75%, and 95% quantiles?
This is how I would do it for the different summary statistics independently:
library(magrittr)
s_1 = M %>% apply(.,2, mean)
s_2 = M %>% apply(.,2, sd)
s_3 = M %>% apply(.,2, quantiles, c(0.05,0.25,0.5,0.75,0.95))
result = cbind(s_1, s_2, s_3)

Ideally, I would like to wrap this functionality into a single, easy-to-understand and easy-to-maintain function.

A: We can do this with dplyr
library(dplyr)
M %>%
   as.data.frame() %>%
   summarise_each(funs(Mean = mean, SD = sd,
             list(Quantile = quantile(., c(0.05,0.25,0.5,0.75,0.95)))))

data
set.seed(24)
M <- matrix(rnorm(30, 30), ncol=3)

A: Here is a custom function in base R that will do the trick. These are quite simple to build and alter to fit whatever stats you want:
myStats <- function(x) {
  myMean <- mean(x)
  mySd <- sd(x)
  myQuantiles <- quantile(x, probs=c(0.05,0.25,0.5,0.75,0.95))

  return(c(mean=myMean, sd=mySd, myQuantiles))
}

Now, let's test it
# get some data
set.seed(1234)
x <- rnorm(100)

 myStats(x)
      mean         sd         5%        25%        50%        75%        95%
-0.1567617  1.0044053 -1.3935761 -0.8953272 -0.3846280  0.4712061  1.7095200

As noted by the OP in the comments, it is possible to use this function in the apply family to calculate these stats over multiple variables. For example, for a data.frame, df with data in columns 3 and above (and ID variables in columns 1 and 2), you could use sapply to return a matrix of statistics for each column:
sapply(df[,-c(1,2)], myStats)


text:
Q: How to configure Spring Boot to execute a SQL query once with JdbcTemplate? I use Spring Boot and JdbcTemplate with Maven. I would like to execute a single SQL query in the database at start.
Here is a example of the application.yml file :
spring
    datasource
      driverClassName: oracle.jdbc.OracleDriver
      url: jdbc:oracle://localhost/test
      username: dbuser
      password: dbpass
      initialize: true

I found on the web that it can be done by creating a data.sql file in the root of the classpath (/resources directory by example) (Visit http://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html for initialization a database using Spring JDBC). So I just create a data.sql file in the /resources directory, near the application.yml file, with content :
alter session set nls_numeric_characters='.,';

But, the data.sql file is not executed when starting the application. The implementation seems easy yet. Did I forget any parameterizations or dependencies ?
I would be pleased to have some help. Thanks.


text:
Q: Using CSS and Xpath selectors with Scrapy I'm following the Scrapy official tutorial where I'm suppoused to scrape data from http://quotes.toscrape.com, the tutorial shows how to scrape the data with the following spider:
class QuotesSpiderCss(scrapy.Spider):
    name = "quotes_css"
    start_urls = [
        'http://quotes.toscrape.com/page/1/',
    ]

    def parse(self, response):
        quotes = response.css('div.quote')
        for quote in quotes:
            yield {
                'text': quote.css('span.text::text').extract_first(),
                'author': quote.css('small.author::text').extract_first(),
                'tags': quote.css('div.tags::text').extract()
            }

Then crawling the spider to a JSON file it returns what's spected:
[
{"text": "\u201cThe world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.\u201d", "author": "Albert Einstein", "tags": ["\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        "]},
{"text": "\u201cIt is our choices, Harry, that show what we truly are, far more than our abilities.\u201d", "author": "J.K. Rowling", "tags": ["\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n        "]},
{"text": "\u201cThere are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.\u201d", "author": "Albert Einstein", "tags": ["\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        "]},
...]

I'm trying to write the same Spider using xpath instead of css:
class QuotesSpiderXpath(scrapy.Spider):
    name = 'quotes_xpath'
    start_urls = [
        'http://quotes.toscrape.com/page/1/'
    ]

    def parse(self, response):
        quotes = response.xpath('//div[@class="quote"]')
        for quote in quotes:
            yield {
                'text': quote.xpath("//span[@class='text']/text()").extract_first(),
                'author': quote.xpath("//small[@class='author']/text()").extract_first(),
                'tags': quote.xpath("//div[@class='tags']/text()").extract()
            }

But this spider returns me a list with the same quote:
[
{"text": "\u201cThe world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.\u201d", "author": "Albert Einstein", "tags": ["\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        "]},
{"text": "\u201cThe world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.\u201d", "author": "Albert Einstein", "tags": ["\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        "]},
{"text": "\u201cThe world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.\u201d", "author": "Albert Einstein", "tags": ["\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n        ", "\n            Tags:\n            ", " \n            \n            ", "\n            \n            ", "\n            \n            ", "\n            \n        "]},
...]

Thanks in advance!

A: The reason you get always the same quote is because you're not using a relative XPath. See documentation.
Add a prefixing dot to your XPath statements like in the following parse method:
def parse(self, response):
    quotes = response.xpath('//div[@class="quote"]')
    for quote in quotes:
        yield {
            'text': quote.xpath(".//span[@class='text']/text()").extract_first(),
            'author': quote.xpath(".//small[@class='author']/text()").extract_first(),
            'tags': quote.xpath(".//div[@class='tags']/text()").extract()
        }


text:
Q: How to add a button on outlook toolbar to a custom form? Hi I have an Outlook form that I'd like to provide ready access to by adding a button or link to it on the outlook toolbar.  How can I customize the toolbar to do this?
Essentially, a single click of the button on the toolbar should bring up the custom form.
This should work in Outlook 2003 and 2007 (preferably).  If it only works in 2007 that would be acceptable.
Thanks!

A: There are a number of ways to do this, I guess the correct way would be to create and deploy an add-in.
Take a look at this example in the toolbar section on how to create a button in your addin.
http://www.packtpub.com/article/microsoft-office-outlook-programming-vsto-c-sharp-part1
You then will need the click handler to open you custom form.
Take a look a the code here for that on SO How do I create a custom Outlook Item?


text:
Q: Accessing variable of the calling class java I'm new to java programming.
My question is:
How can I access a variable in a calling class(a container inside Frame1) from Frame2 or Frame3?
For example: In the following code, I want to display the value in textfield a1(in PanelA nested in Frame1) in Frame2 and the value of textfield a2(in PanelB nested in Frame1) in the frame Frame3.
This is a sample code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

class PanelA extends JPanel implements ActionListener
{
    JTextField a1;
    JButton b1;

    PanelA()
    {
        a1=new JTextField("");
        b1=new JButton("Click me");
        b1.addActionListener(this);
        add(a1);
        add(b1);
    }

    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource()==b1){
        SwingUtilities.getWindowAncestor(this).setVisible(false);
        Frame2 x=new Frame2("Frame2");
        x.setSize(Toolkit.getDefaultToolkit().getScreenSize());
        x.setVisible(true);
        }
    }
}

class PanelB extends JPanel implements ActionListener
{
    JTextField a2;
    JButton b2;

    PanelA()
    {
        a2=new JTextField("");
        b2=new JButton("Click me");
        b2.addActionListener(this);
        add(a2);
        add(b2);
    }

    public void actionPerformed(ActionEvent e)
    {
        SwingUtilities.getWindowAncestor(this).setVisible(false);
        Frame3 x=new Frame3("Frame3");
        x.setSize(Toolkit.getDefaultToolkit().getScreenSize());
        x.setVisible(true);
    }
}

public class Frame1 extends JFrame
{
    Frame1(String s)
    {
        super(s);
        setLayout(newFlowLayout(FlowLayout.CENTER));
        PanelA x=new PanelA();
        x.setSize();
        x.setVisible(true);
        PanelB y=new PanelB();
        y.setSize();
        y.setVisible(true);
        JTabbedPane pan1=new JTabbedpane();
        pan1.addTab("A",x);
        pan1.addTab("B",y);
        add(pan1);
    }
}

public class Frame2 extends JFrame
{

}

public class Frame3 extends JFrame
{

}

The calling class to Frame1 is something like
public class FrameMain
{
    public static void main(String[] args)
    {
        Frame1 x= new Frame1("Frame1");
        x.setSize(Toolkit.getDefaultToolkit().getScreenSize());
        x.setVisible(true);
    }
}

A: Hi Friend you can use the object of that class to access its variable.
Use the keyword public to access globally.
As you wish to get the value of textfield use getText() of class JTextField.
import javax.swing.*;

public class test {

    public static void main(String a[])
    {
        A aobj=new A();
        B bobj=new B();
        System.out.println(aobj.tf1.getText());
        System.out.println(bobj.tf2.getText());
    }

}

class A
{
    JTextField tf1=new JTextField("one");
}
class B
{
    JTextField tf2=new JTextField("Two");
}

The output would be as follows
one
Two

A: You can create your own constructor for Frame2, like so:
public class Frame2 extends JFrame
{
    public Frame2(String textBoxValue)
    {
        //do whatever you want with your textbox value(set it to the textbox (make sure it's initialized at this point!), set it to a local variable)
    }
}

And then call this frame like so:
Frame2 x = new Frame2("Frame2", a1.getText());

You can do thesame thing for Frame3.
I do suggest to use clear class/variable names, so it's easier to see what they do.

A: The following code may help you,
Frame1
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

 public class Frame1 implements ActionListener{
 JFrame frame;
 JTextField t1;
 JButton btn;
 public PopupExample()
 {
   frame=new JFrame();
   frame.setLayout(null);
   frame.setSize(700,700);
   frame. setLocation(300,10);

   t1=new JTextField();
   t1.setBounds(82,10,100,20);

   frame.add(t1);

   btn=new JButton("SUBMIT");
   btn.setBounds(200,10,100,20);
    btn.addActionListener(this);
   frame.add(btn);

   frame.setVisible(true);
 }
 public static void main(String ar[])

 {
  Frame1 obj=new Frame1 ();

  }

 @Override
 public void actionPerformed(ActionEvent e) {
    if(e.getSource()==btn)
    {
        String input=t1.getText();
       Frame2 obj=new Frame2(input);

      }
  }
 }

Frame2
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Frame2 {
JFrame frame;
public Frame2(String text)
{
   frame=new JFrame();
   frame.setLayout(null);
   frame.setSize(700,700);
   frame. setLocation(300,10);

   JLabel l1=new JLabel(text);
    l1.setBounds(82,10,100,20);
    frame.add(l1);

   frame.setVisible(true);
 }

  public static void main(String ar[])

{
  Frame2 obj=new Frame2("");

 }

}

In this example, value is passing from one class to another via constructor.

A: Of course, there are various ways, but a simple way is to implement a method getTextField() in your Frame class (I would not call it Frame and if the Frames have the same functionality, you do not need Frame1 etc., but you just say Frame f3 = new Frame()), or alternatively a getPanel().getTextField(). This method returns the JTextField, and you can manipulate it, as you like.


text:
Q: Android app, tablet only on google play. How? I have just made an android application using PhoneGap which was designed for use with only tablets. However, after uploading the app to google play, it says it is only available for phones and cannot be installed on tablets :/
How can I make it so that the application is only available for tablets?
This is my AndroidManifest file:
<?xml version="1.0" encoding="utf-8"?>
<!--
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:windowSoftInputMode="adjustPan"
      package="com.p4l.inhome" android:versionName="1.0" android:versionCode="1" android:hardwareAccelerated="true">
    <supports-screens
        android:largeScreens="true"
        android:normalScreens="true"
        android:smallScreens="true"
        android:xlargeScreens="true"
        android:resizeable="true"
        android:anyDensity="true"
        />

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.RECORD_VIDEO"/>
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.BROADCAST_STICKY" />

    <application android:icon="@drawable/icon" android:label="@string/app_name"
        android:hardwareAccelerated="true"
        android:debuggable="true">
        <activity
             android:hardwareAccelerated="true"
             android:screenOrientation="landscape"
             android:name="InHomeFinal" android:label="Pay4Later InHome"
                android:theme="@android:style/Theme.Black.NoTitleBar"
                android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <uses-sdk android:minSdkVersion="7" android:targetSdkVersion="17"/>
</manifest>

Thanks

A: Change in manifest like this :
<supports-screens
        android:largeScreens="true"
        android:normalScreens="false"
        android:requiresSmallestWidthDp="600"
        android:smallScreens="false"
        android:xlargeScreens="true" />

<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="14" />

This will prevent any small/mobile device to install your application. Only device with large screen will have the privilege to install your application. Play store will automatically select the devices cording to these settings.


text:
Q: How can I get return primitive of String array "String[]" in mybatis I want to get String[] from the mybatis as a result
but result is as follow.

Error querying database.  Cause: java.lang.IllegalArgumentException:
  Mapped Statements collection does not contain value for
  com.aa.project.dao.homeDao.getHomeDaoROWID
sqlsession.selectOne(nameSpace + ".getTicketHomeDaoROWID");

java
String[] row = {};
row = homeService.getHomeServeiceROW();

@Service
public String[] getHomeServeiceROW() {
  return homeDao.getHomeDaoROW();
}

@Repository
public String[] getHomeDaoROW() {
  return sqlsession.selectOne(nameSpace + ".getHomeDaoROWID");
}

mapper.xml
<select id="getHomeDaoROWID" resultType="java.util.Map">
  SELECT AAID
  FROM AAS
</select>

in my oracle sqldeveloper
AAID is column name where contains A1, A2, A3, A4, A5 each tuple
I expect the ouput of row = {A1, A2, A3, A4, A5};
but error message is as follows
Error querying database.  Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for com.aa.project.dao.homeDao.getHomeDaoROWID
Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for com.aa.project.dao.homeDao.getHomeDaoROWID]을
java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for com.aa.project.dao.homeDao.getHomeDaoROWID


text:
Q: How to get steam to recognize game files downloaded on another machine? Yesterday I purchased GTA V for the PC via Steam and downloaded it onto my laptop at work. When I got home to transfer the 65 GB worth of files to my main computer, I cleared up 65 GB of space on my SSD and have just enough room to fit those downloaded files onto a Steam folder that I created. However, Steam won't recognize the game as installed. I tried to click the "Install" button for the game where it's currently pointed to the folder where I've copied all of this data, but after exiting Steam and opening it again, it's saying that there isn't enough room to install the game. I spent several hours looking up ways to solve this, but I haven't been able to so far.
Also, Is 65 GB enough space for this game, or will I need to clear up more room for it?
Edit: After following Ross's guide below, everything worked fine with the backup process!

A: You'll need 130 GB of space, maybe a bit more, to copy the files in the manner you describe. Steam first checks to see if you have enough free space to install the game, then it checks to see what files have already been copied to the machine. So you'll need 65 GB of space to store the copied files and additional 65GB of free space just so Steam won't refuse to "download" and install the game.
Probably the easiest way to work around this problem to use Steam's own backup and restore functionality to copy the game between computers. You'll need 65GB of free space on your home computer, and 65GB of space somewhere else. If you happen have a big enough portable USB drive, either a portable hard drive or USB key, than that would be ideal. Otherwise you can use a folder on your main computer and share it over the network. To perform the backup right-click on the game in your library and select "Backup Game Files...". To do the restore select "Backup and Restore Games..." from the "Steam" menu at the top left of client. Make sure to delete the Grand Theft Auto V files you've already copied to the home computer first.
(I've more detail of the backup and restore process in another answer.)
If you have 130 GB of space free on different hard drive on your home computer you can also create a secondary Steam library folder there, copy the GTA V files to secondary library and then "install" the game to that folder.

A: You can do what Ross said, or if you have the WHOLE library folder with you, you can shut down steam and copy it over the on your current steam library. When you open steam, it should be there.
(ps. You will need the GTA V folder ("SteamLibrary\steamapps\common\Grand Theft Auto V\") and the appmanifest_271590.acf file (SteamLibrary\steamapps\appmanifest_271590.acf), if you don't have both, steam won't recognise it.)
Note: This is a bit harder than the other solution but this doesn't require 2x size.
Note 2: I did this several times and it works.

A: I found another way, which is to to copy the game directory on 'Steamapps' » 'Common'. Just start installing the game and then pause (doesn't matter when) which will make Steam create a file named "appmanifest_1234.acf" (number part will differ depending on the game) under the 'Steamapps' directory.
Open that file with a text editor and you will see there the game's name. Under that there's a line name "StateFlags" "1026". Change that number to "4", and voila! There you go, you complete the installation - simple as that.
Sample screenshot:


text:
Q: how to find host name from IP with out login to the host i need to find the host name of a UNIX host whose IP is known with out login to that UNIX host

A: You can do a reverse DNS lookup with host, too. Just give it the IP address as an argument:
$ host 192.168.0.10
server10 has address 192.168.0.10

A: Another NS lookup utility that can be used for reversed lookup is dig with the -x option:
$ dig -x 72.51.34.34

; <<>> DiG 9.9.2-P1 <<>> -x 72.51.34.34
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 12770
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1460
;; QUESTION SECTION:
;34.34.51.72.in-addr.arpa.      IN      PTR

;; ANSWER SECTION:
34.34.51.72.in-addr.arpa. 42652 IN      PTR     sb.lwn.net.

;; Query time: 4 msec
;; SERVER: 192.168.178.1#53(192.168.178.1)
;; WHEN: Fri Jan 25 21:23:40 2013
;; MSG SIZE  rcvd: 77

or
$ dig -x 127.0.0.1

; <<>> DiG 9.9.2-P1 <<>> -x 127.0.0.1
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 11689
;; flags: qr aa ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;1.0.0.127.in-addr.arpa.                IN      PTR

;; ANSWER SECTION:
1.0.0.127.in-addr.arpa. 10      IN      PTR     localhost.

;; Query time: 2 msec
;; SERVER: 192.168.178.1#53(192.168.178.1)
;; WHEN: Fri Jan 25 21:23:49 2013
;; MSG SIZE  rcvd: 63

Quoting from the dig manpage:

Reverse lookups -- mapping addresses to names -- are simplified by the
  -x option.  addr is an IPv4 address in dotted-decimal notation, or a colon-delimited IPv6 address. When this option is used, there is no
  need to provide the name, class and type arguments.  dig automatically
  performs a lookup for a name like 11.12.13.10.in-addr.arpa and sets
  the query type and class to PTR and IN respectively.

A: For Windows ping -a 10.10.10.10

A: The other answers here are correct - use reverse DNS lookups.
If you want to do it via a scripting language (Python, Perl) you could use the gethostbyaddr API.

A: *

*For Windows, try:
NBTSTAT -A 10.100.3.104

or
ping -a 10.100.3.104

*For Linux, try:
nmblookup -A 10.100.3.104

They are almost same.

A: Use nslookup
nslookup 208.77.188.166
...
Non-authoritative answer:
166.188.77.208.in-addr.arpa     name = www.example.com.

A: python -c "import socket;print(socket.gethostbyaddr('127.0.0.1'))"

if you just need the name, no additional info, add [0] at the end:
python -c "import socket;print(socket.gethostbyaddr('8.8.8.8'))[0]"

A: It depends on the context. I think you're referring to the operating system's hostname (returned by hostname when you're logged in). This command is for internal names only, so to query for a machine's name requires different naming systems. There are multiple systems which use names to identify hosts including DNS, DHCP, LDAP (DN's), hostname, etc. and many systems use zeroconf to synchronize names between multiple naming systems. For this reason, results from hostname will sometimes match results from dig (see below) or other naming systems, but often times they will not match.
DNS is by far the most common and is used both on the internet (like google.com. A 216.58.218.142) and at home (mDNS/LLMNR), so here's how to perform a reverse DNS lookup: dig -x <address> (nslookup and host are simpler, provide less detail, and may even return different results; however, dig is not included in Windows).
Note that hostnames within a CDN will not resolve to the canonical domain name (e.g. "google.com"), but rather the hostname of the host IP you queried (e.g. "dfw25s08-in-f142.1e100.net"; interesting tidbit: 1e100 is 1 googol).
Also note that DNS hosts can have more than one name. This is common for hosts with more than one webserver (virtual hosting), although this is becoming less common thanks to the proliferation of virtualization technologies. These hosts have multiple PTR DNS records.
Finally, note that DNS host records can be overridden by the local machine via /etc/hosts. If you're not getting the hostname you expect, be sure you check this file.
DHCP hostnames are queried differently depending on which DHCP server software is used, because (as far as I know) the protocol does not define a method for querying; however, most servers provide some way of doing this (usually with a privileged account).
Note DHCP names are usually synchronized with DNS server(s), so it's common to see the same hostnames in a DHCP client least table and in the DNS server's A (or AAAA for IPv6) records. Again, this is usually done as part of zeroconf.
Also note that just because a DHCP lease exists for a client, doesn't mean it's still being used.
NetBIOS for TCP/IP (NBT) was used for decades to perform name resolution, but has since been replaced by LLMNR for name resolution (part of zeroconf on Windows). This legacy system can still be queried with the nbtstat (Windows) or nmblookup (Linux).

A: If you are specifically looking for a Windows machine, try below command:
nbtstat -a 10.228.42.57

A: In most cases, traceroute command works fine. nslookup and host commands may fail.

A: You can use traceroute command as well.
http://linux.die.net/man/8/traceroute
just use the traceroute  it will show you the routing path with host names (IPs resolved)


text:
Q: MOUSEOVER: How to start a function and let it play until the end without start it over and over? I want to start a function when I over mouse an ID #show-details.
But I need it to start only one until it ends, not to start over and over again ...
With my code below It starts when I mouseover it but starts over and over even if it doesn't finish.
I need some help :)
function showDetails() {

  var details = document.getElementById('show-details');

  details.addEventListener('mouseover', initDetailsLetters);

}

A: i think you need a flag, if the flag doesnt exist then create it and start over, if it does exist then dont run the code

A: Try a callback function, I have found this example to help you: Proper way to wait for one function to finish before continuing?
This looks similar to your problem


text:
Q: How to import multiple files from a smartphone in a WPF app? We encounter a problem using Microsoft.Win32.OpenFileDialog in a WPF app (targeting .NET Framework 4.7.2).
We want to be able to import multiple files from a smartphone connected to a computer via USB connection. However, it seems impossible to do so using the OpenFileDialog, because it fires message box "Cannot open multiple items from this location. Try selecting a single item instead.". You can reproduce it using this simple code and selecting at least 2 pictures from your smartphone:
var openFileDialog = new Microsoft.Win32.OpenFileDialog();
openFileDialog.Multiselect = true;
openFileDialog.ShowDialog();

This problem is known (see here and here) and related to the MTP protocol. The problem does not occur with a smartphone connected using the alternative "USB Mas Storage" (UMS), but this option is not available on modern smartphones.
The UWP FileOpenPicker seems to handle better the selection of multiple items (see here to see how to use it in a WPF app) but we accounter an InvalidCastException when using PickMultipleFilesAsync. The problem is described here and the answers suggest that FileOpenPicker cannot be used in WPF .NET Framework apps.
As said in the comments, an other way to achieve this would be to implement a file picker from skratch, using the MTP protocol for the smartphone devices.
The downside of this approach is that the .NET and UWP file pickers offer a lots of great features and are fully integrated to the OS.
We have run out of ideas to solve this problem, so my question is:
Is there a way to import multiple files from a smartphone using the Windows file picker in a WPF app targeting .NET Framework?
The same question has been asked on the Microsoft Q&A.

A: I'm a bit late to reply but I found the solution thanks to the Microsoft Q&A thread.
As far as I know, it's not possible to select multiple files from a MTP device using the Microsoft.Win32.OpenFileDialog because you can not set all the IFileOpenDialog options.
As a result, you need to use your own IFileOpenDialog to set the options: be sure to add the FOS_ALLOWMULTISELECT option and remove the FOS_FORCEFILESYSTEM:
ComFileDialog.IFileOpenDialog fileOpenDialog = null;
ComFileDialog.IShellItemArray shellItemArray = null;
ComFileDialog.IShellItem shellItem = null;
try
{
    // Set options
    fileOpenDialog = (ComFileDialog.IFileOpenDialog)new ComFileDialog.FileOpenDialogRCW();
    fileOpenDialog.GetOptions(out var options);
    options |= ComFileDialog.FOS_ALLOWMULTISELECT | ComFileDialog.FOS_FILEMUSTEXIST | ComFileDialog.FOS_PATHMUSTEXIST;
    fileOpenDialog.SetOptions(options);

    // Show window
    if (fileOpenDialog.Show() != ComFileDialog.S_OK)
    {
        return;
    }

    // Get results
    if (fileOpenDialog.GetResults(out shellItemArray) != ComFileDialog.S_OK)
    {
        return;
    }

    uint items = 0;
    if (shellItemArray.GetCount(out items) != ComFileDialog.S_OK)
    {
        return;
    }

    // Result loop
    for (uint item = 0; item < items; item++)
    {
        try
        {
            if (shellItemArray.GetItemAt(item, out shellItem) != ComFileDialog.S_OK)
            {
                continue;
            }

            // Use the IShellItem
        }
        finally
        {
            if (shellItem != null)
            {
                Marshal.ReleaseComObject(shellItem);
                shellItem = null;
            }
        }
    }
}
finally
{
    if (fileOpenDialog != null)
    {
        Marshal.ReleaseComObject(fileOpenDialog);
    }
    if (shellItemArray != null)
    {
        Marshal.ReleaseComObject(shellItemArray);
    }
    if (shellItem != null)
    {
        Marshal.ReleaseComObject(shellItem);
    }
}

You can find find the Window Shell API Interfaces on pinvoke.net:

*

*https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nn-shobjidl_core-ifiledialog

*https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nn-shobjidl_core-ifileopendialog

*http://pinvoke.net/default.aspx/Interfaces/IFileOpenDialog.html

*https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nn-shobjidl_core-ishellitem

*http://pinvoke.net/default.aspx/Interfaces/IShellItem.html

*https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nn-shobjidl_core-ishellitemarray

*http://pinvoke.net/default.aspx/Interfaces/IShellItemArray.html

*http://www.pinvoke.net/default.aspx/Interfaces/FileOpenDialogRCW.html


text:
Q: Getting the following error ORA-01427: single-row subquery returns more than one row 01427. 00000 - "single-row subquery returns more than one row" I am getting the following error:
I want to get a column value from the first query and pass that value to the next query.
ORA-01427: single-row subquery returns more than one row
01427. 00000 -  "single-row subquery returns more than one row"

with the following query:
 with

deal_XX AS(

SELECT distinct idh.vendor supplier
                  ,idh.deal_id
                  ,mff_report.mff_merch_sql.get_sup_name(idh.vendor) sup_name

              FROM im_doc_head idh
                  ,mff_report.stage_complex_deal_head_hist scdhh
                  ,im_complex_deal_detail icdd
                  ,mff_report.v_loc vl
                  ,item_master im
                                  ,item_master im_parent
             WHERE (   (    idh.type IN ('DEBMEC','CRDMEC') --Debit and Credit Memos in APPROVED or POSTED
                        AND idh.status IN ('APPRVE','POSTED'))
                    OR (    idh.type = 'CRDNRC'             --Credit Note Requests in APPROVED or MATCHED
                        AND idh.status IN ('APPRVE','MTCH')))
               AND idh.deal_type = 'C'
               AND NVL(:PM_supplier,idh.vendor) = idh.vendor

               AND idh.deal_id = scdhh.deal_id (+)
               AND SUBSTR(idh.ext_doc_id,(INSTR(idh.ext_doc_id,'-',1) + 1),INSTR(idh.ext_doc_id,'-',1,2) - (INSTR(idh.ext_doc_id,'-',1) + 1)) = scdhh.deal_detail_id (+)
               AND idh.doc_date = scdhh.end_invoice_date (+)
               AND idh.doc_id = icdd.doc_id
               AND icdd.location = vl.loc
               AND icdd.item = im.item
                               AND im.item_parent = im_parent.item (+)
               AND (   :PM_supplier IS NOT NULL
                    OR :PM_doc_date_from IS NOT NULL
                    OR :PM_doc_date_to IS NOT NULL
                    OR :PM_approval_date_from IS NOT NULL
                    OR :PM_approval_date_to IS NOT NULL
                    OR :PM_ext_doc_id IS NOT NULL
                    OR :PM_batch_mode = 'Y')
                    )

  select distinct  ship.order_no    , (select deal_id from deal_XX) hhhh
  from ordloc_discount od
     ,shipment ship
     ,mff_report.stage_complex_deal_head_hist scdhh
    where od.deal_ID = (select deal_id from deal_XX)

    and od.deal_id = scdhh.deal_id
    and ship.status_code = 'R'
    and od.order_no = ship.order_no
    and ship.receive_date BETWEEN
        to_date(scdhh.start_invoice_date , 'YYYY-MM-DD" "HH24:MI:SS')
         AND
         to_date(scdhh.end_invoice_date , 'YYYY-MM-DD" "HH24:MI:SS') ;

A: If you run Q1:select deal_id from deal_XX then you probably get more than one row. Therefore, there are two issues:

*

*Having select *, (subselect) from tableX then the subselect has to return always just one value for each row of the tableX. Since you have Q1 as a subselect, your query fails.

*The same issue is when you have select * from tableX X where X.y = (subselect). Again, query processor expects you to provide a subselect returning just one value for each row  of TableX and you have Q1 returning many rows.
The solutions depend on what you are trying to achieve. The second issue could be possibly fixed using od.deal_ID IN (select deal_id from deal_XX) meaning that you want rows where deal_id can be found in the list of deal_ids returned by deal_XX.


text:
Q: How to have tail -f show colored output with vim? In this question, Gilles answered

Yet another possibility is to run tail -f in an Emacs shell buffer and use Emacs's syntax coloring abilities.

Because I'm a vim user, I'd like to do this with vim, not emacs.
Does vim have this feature?

A: You can write a multithread plugin to change the buffer(s) in real time in Python or any other script that Vim supports and has threads.
But this only works in terminal as far as I know. At least in X11, the GUI version will crash if the GUI is modified by another thread.
If you accept other programs, grc and ccze are able to colorize streams.

A: I like it short and without a lot of hacking or external scripts.
You can run this oneliner from ex (whithin vim) when needed (or put each command in vimrc, for when log-files are opened.)
:set autoread | au CursorHold * checktime | call feedkeys("lh")

and additionally you can :set syntax=logtalk to color the log
(if you would want to jump (nearly) to the end of the file, just use "G" instead of "lh" with feedkeys)
Explanation:

*

*autoread: reads the file when changed from the outside (but it doesnt work on its own, there is no internal timer or something like that. It will only read the file when vim does an action, like a command in ex :!

*CursorHold * checktime: when the cursor isn't moved by the user for the time specified in updatetime (which is 4000 miliseconds by default) checktime is executed, which checks for changes from outside the file

*call feedkeys("lh"): the cursor is moved once, right and back left. and then nothing happens (... which means, that CursorHold is triggered, which means we have a loop)

To stop the scrolling when using call feedkeys("G"), execute :set noautoread - now vim will tell, that the file was change ans ask if one wants to read the changes or not)
I like the idea to watch logfiles in vim (instead of tail -f), e.g. when you are working in an ssh session without screen/tmux. Additionally you can copy directly from the logfile, if needed, or save the output directly or ... whatever you can do with vim :)
*from this answer (refering to an answer by PhanHaiQuang and a comment by flukus)


text:
Q: Subsonic MySQL Version I understand that Subsonic 2.2 requires the MySQL.data  5.2.3 dll.  I'm trying to integrate a subsonic DAL for a VB project in Visual Studio.  The project already uses a lot of datasets.  Because of this, Visual Studio requires that I have the MySQL NET connector software installed, which automatically throws its own MySQL dll deep into my system.
The problem is that with the MySQl NET Connector installed on my system, I can't include the MySql.data 5.2.3 dll with my project because it complains that I have two conflicting versions of the same dll.
The closest Net Connector version I can find to install is 5.2.6.  Subsonic demands 5.2.3.  I can't seem to use both in the project.  What the heck am I supposed to do?

A: You can try to build SubSonic from source using the MySql.dll that you are using in your project.  Thats what I did once.


text:
Q: Inconsistent boundary and initial conditions when solving sine Gordon equation I have been trying to solve the following sine Gordon equation
$\partial_{x,x} u(x,t) - \partial_{t,t} u(x,t) - \sin (u(x,t)) - \alpha \partial_t u(x,t) + \gamma = 0$,
for $x \in [0,15]$ and $t \in [0,20]$ with the boundary conditions
$\partial_x u(x,t)\vert_{x=0} = h, \hspace{2cm} \partial_x u(x,t)\vert_{x=15} = h + a_{\mathrm{ext}} \sin(\omega_{\mathrm{ext}}t), $
and the initial conditions
$\partial_t u(x,t)\vert_{t=0} = 0, \hspace{2cm} u(x,t)\vert_{t=0} = h x$.
Here is my Mathematica code
const = {al -> 0.08, \[Gamma] -> 0.01, h -> 6,  ax -> 2.5, \[Omega]x -> 1.4};

NDSolveValue[({D[u[x, t], x, x] - D[u[x, t], t, t] - Sin[u[x, t]] - al D[u[x, t], t] + \[Gamma] == 0,

(D[u[x, t], x] /. {x -> 0}) == h, (D[u[x, t], x] /. {x -> 15}) == h +  ax Sin[\[Omega]x  t],
    u[x, 0] == h*x, (D[u[x, t], t] /. {t -> 0}) == 0} /.const), u, {x, 0, 15}, {t, 0, 20},

 Method -> {"PDEDiscretization" -> {"MethodOfLines",
     "SpatialDiscretization" -> {"TensorProductGrid",
       "MinPoints" -> 200}}}]

The code works and gives a solution, but there appears an error message like this
NDSolveValue::ibcinc: Warning: boundary and initial conditions are inconsistent.

From the second initial condition we have $\partial_x u(x,0) = h$, which are consistent with the two boundary conditions at $t=0$. So I don't understand why the above error occurs.
I have read many posts related to this problem. One of the solutions is to increase the "MinPoints" in the "Method". I tried so, but it still did not not get rid of the error.
Any advice is very much appreciated.
Dat.


text:
Q: Difference between SQL Server Azure and SQL Server 200x I'm a SQL Server DBA and I can understand the logic behind logins users roles and etc ( login for server access, user for databases and etc ).
I've asked some questions here but I think I need to choose better how to ask this.
I'm using SQL Server for 5 years+ and now I'm trying to use some azure servers and databases.
I have some doubts about how it works, why I need to use master to create a login, where can I find a list of roles for azure?
AS I can understand now, to create a Login I need to use master and then create a login. then I change to the database I want to use and then I create a user there pointing to the login. Ok.
My question is, how can I create a sysadmin login like we have in SQL Server? I would like to create myself a login that can do everything. what role should I assign my login? I've seen to crate databases and etc but not "do everything you want mr. DBA".
Does azure uses Contained users? That's why I need to create first a login inside Master and then a user inside a database?
Please have in mind that I've read a lot of official microsoft sites related to logins, but I still can't understand what is simple.
I would really like to understand something like "when you create a login, you are creating....then when creating a user, it means..."
With SQL Server I can create a login, then a user inside databases and assign what I want them to do, but there's not visual info about this with azure.
An example of adding a dbowner:
CREATE LOGIN teste123
    WITH PASSWORD = '12e32d2c23dohdas970h9h&(*H&*(H*&(HG*&bhiuosnad22s23sd23'
GO

Use DatabaseIwant
CREATE USER teste123
    FOR LOGIN teste123
    WITH DEFAULT_SCHEMA = dbo
GO

EXEC sp_addrolemember N'db_owner', N'teste123'
GO

and see? I'm creating a DBO. what should I do to create a sysadmin login? to be able to access all databases, create delete and etc? thats the point. Should I create a login and create a user inside all databases as a DBO? because with SQL Server I can simply create a sysadmin and thats it. I have acces to everything.
Thanks all.
Edit: I think I found a usefull page finally:
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-manage-logins

A: Using logins are discouraged. Logins that will be used by your applications should be contained users and not server logins. Create contained users for your applications and users, place one or more database users into a database role and then assign permissions to the database role.
One common reason to create a database user based on a SQL Database server login is for users that need access to multiple databases. Since contained database users are individual entities, each database maintains its own user and its own password. This can cause overhead as the user must then remember each password for each database, and it can become untenable when having to change multiple passwords for many databases. However, when using SQL Server Logins and high availability (active geo-replication and failover groups), the SQL Server logins must be set manually at each server. Otherwise, the database user will no longer be mapped to the server login after a failover occurs, and will not be able to access the database post failover.
As the Sysadmin fixed role does not exist in SQL Azure, if you want to create a "sysadmin" on SQL Azure, in addition to the sysadmin created on the portal, you  need to add that sysadmin login to the dbmanager database role in the master database.
CREATE LOGIN YourSysadminLogin WITH PASSWORD = 'hSUj4Grd' -- Dec 13, 2018

CREATE USER YourSysadminLogin FROM LOGIN YourSysadminLogin;

ALTER ROLE dbmanager ADD MEMBER YourSysadminLogin;

YourSysadminLogin, as it belongs to dbmanager, it now can perform privileged tasks like been able to create and drop databases.
If you want YourSysadminLogin to manage logins also (create/alter/drop logins) add it to the loginmanager database role in the master database.
ALTER ROLE loginmanager ADD MEMBER YourSysadminLogin;

Create your YourSysadminLogin as a user on user databases and assign it db_owner.
CREATE USER YourSysadminLogin FROM LOGIN YourSysadminLogin;
GO
ALTER ROLE db_owner ADD MEMBER YourSysadminLogin;
GO

Now you have created a sysadmin.


text:
Q: Primes in arithmetic progression $a \pmod q$ Can we prove the "Bertrand postulate" for primes $a \pmod q$, namely: there is always a prime number $p\equiv a \pmod q$ betwen $nq$ and $nq^2$ for every $n>0$ and $(a,q)=1$. (This would mean that between $nq$ and $nq^2$ there are always at least $\varphi(q)$ primes, each belonging to a different residue class modulo $q$.)

A: Given a fixed $a$ and $q$, this should be true for sufficiently large $n$ by the explicit versions of Dirichlet's theorem on arithmetic progressions. We cannot prove that this is true for every $n$. The best we have is variants of Linnick's theorem, which just tells us that there are  constant $L$ and , such that for any such $q$ and $a$, there is a prime $p$ with $p \equiv a$ (mod $q$), and $p < cq^L$. The best known such constant for $L$ currently is a little larger than 5. Your claim is much stronger; even if one has $n=1$ fixed, you would be asking us to prove $L=2$, $c=1$ and want also that one can find such a $p$ where $p$ also obeys the lower bound $p > q$. Your claim if I understand it is an interesting one, and is strong enough that we're nowhere near proving it if it is true. I'm not sure I'd conjecture either way whether your claim is true or not. If it is false, I suspect that counterexamples can be found with small amounts of computation.

A: This question appears to have been addressed by P. Moree in this paper. In the notation of that paper, he defines
$$\displaystyle B_m(z,d) = \liminf \{c : \forall x \geq c, (x,zx) \text{ contains at least } m \text{ primes}  $$
$$\displaystyle \text{ congruent to } a \pmod{d} \text{ for all } \gcd(a,d) = 1\}.$$
In particular, he proves that provided the quantity $\sigma(d)$ defined to be
$$\displaystyle \sigma(d) =  \sum_{\substack{p \leq d \\ p \nmid d}} \frac{1}{p}$$
is strictly less than one, then one can obtain an explicit estimate for $B_m(z,d)$ whenever
$$\displaystyle z > \frac{d}{(d-1)(1 - \sigma(d))}.$$
His methods generalize an elementary argument of Erdos (who gave an elementary proof of the original Bertrand's postulate), and so do not run into the problems that one encounters when attempting to use the known analytic theorems to attack the problem (i.e., possible existence of Siegel zeroes, etc.). Unfortunately, by Mertens' theorem the hypothesis that $\sigma(d) < 1$ is extremely strict: indeed, Moree shows that $\sigma(d) < 1$ implies that $d \leq 840$.
In principle, one can approach the problem by obtaining a reasonably explicit lower bound for the number of primes in an arithmetic progression, up to some bound $x$. For each pair $(a,q)$ with $\gcd(a,q) = 1$ define $N(a,q)$ to be a positive number with the property that whenever $x > N(a,q)$ we have
$$\pi(x; a,q) > \frac{2x}{3 \phi(q) \log x},$$
say. Then for $q \geq 2$ and $nq > N(a,q)$ there will always be a prime congruent to $a \pmod{q}$ in the interval $(nq, nq^2)$, since by the Brun-Titchmarsh theorem we have
$$\displaystyle \pi(x; a,q) \leq \frac{2x}{\phi(q) \log (x/q)}$$
for all $x \geq q \geq 2$. In particular,
$$\displaystyle \pi(nq^2; a, q) - \pi(nq; a, q) > \frac{2nq^2}{3\phi(q) \log(nq^2)} - \frac{2nq}{\phi(q) \log(n)}$$
$$ = \frac{2nq}{3\phi(q)} \left(\frac{(2q -3) \log n - 6 \log q}{\log n(\log n + \log q^2)} \right)$$
which is positive. Calculating $N(a,q)$ however seems to be a very hard problem.


text:
Q: CGAL 3.4: How do I get end vertex co-ordinates from a Finite_edges_iterator? Here is some code:
struct K : CGAL::Exact_predicates_inexact_constructions_kernel {};

typedef CGAL::Triangulation_vertex_base_2<K>               Vb;
typedef CGAL::Constrained_triangulation_face_base_2<K>     Fb;
typedef CGAL::Triangulation_data_structure_2<Vb,Fb>        TDS;
typedef CGAL::Exact_predicates_tag                         Itag;
typedef CGAL::Constrained_triangulation_2<K, TDS, Itag>    CT;
typedef CT::Point                                          Point;

for (CT::Finite_edges_iterator eit = ct.finite_edges_begin();
    eit != ct.finite_edges_end(); ++eit){
    // TODO: list vertex co-ordinates here
}

From the manual:
"The edges are not explicitly represented, they are only implicitly represented through the adjacency relations of two faces. Each edge has two implicit representations: the edge of a face f which is opposed to the vertex indexed i, can be represented as well as an edge of the neighbor(i) of f."
That's fine by me... but how do I get the end vertices of the edge using a CT::Finite_edges_iterator in the code given above?
Update:
I managed to come up with this solution:
Segment s = ct.segment(eit);
const Point& p1 = s.point(0);
const Point& p2 = s.point(1);

I am still looking for a better way to do this.

A: I managed to come up with this solution:
Segment s = ct.segment(eit);
const Point& p1 = s.point(0);
const Point& p2 = s.point(1);

I am still looking for a better way to do this.

A: I have using something like
Triangulation::Vertex_handle fVertex = eit->first->vertex(Triangulation::ccw(eit->second));
Triangulation::Vertex_handle sVertex = eit->first->vertex(Triangulation::cw(eit->second));

A: The edges provide the indices of the vertices on the face. The face of a triangulation has only 3 vertices in CGAL. Edges are a triplet; (face, i, j). You can get the i-th (either 0, 1, or 2) vertex of a face using the vertex(i) method.. So, to get the vertices, use:
v1 = eit->first->vertex(eit->second);
v2 = eit->first->vertex(eit->third);


text:
Q: How do I remove a choice conflict in JavaCC? My production rules are as follows:
OtherNonTerminal := NonTerminal | {}
NonTerminal := <TOKEN>:A() | <TOKEN>:A(), Nonterminal()

In JavaCC, NonTerminal has a choice conflict:
void OtherNonTerminal() : {}
{
    Nonterminal() | {}
}

void Nonterminal() : {}
{
    <TOKEN> <COLON> A()
|
    <TOKEN> <COLON> A() <COMMA> Nonterminal()
}

Would this be one way to get rid of the choice conflict and will the program worked as specified like my NonTerminal production rule?
void Nonterminal() : {}
{
    <TOKEN> <COLON> A() (<COMMA> NonTerminal())?
}

A: Why is there a problem
In JavaCC, the default method of deciding which branch to take is by looking at the next token.  It that token is compatible with the first choice, the first choice is taken and that decision is not reversible.  There is no backtracking.
So look at the choice
void Nonterminal() : {}
{
    <TOKEN> <COLON> A()
|
    <TOKEN> <COLON> A() <COMMA> Nonterminal()
}

and suppose the next token in the input is <TOKEN>. The first choice will be taken regardless of whether there is a <COMMA> later on. In other words
  <TOKEN> <COLON> A()
| <TOKEN> <COLON> A() <COMMA> Nonterminal()

is equivalent to
  <TOKEN> <COLON> A()

Except the first will produce a warning message since JavaCC sees that what you have written doesn't make sense.

A good solution
The answer to your question is "yes".  One solution is to do what you did and factor out the common prefix
void Nonterminal() : {}
{
    <TOKEN> <COLON> A() (<COMMA> NonTerminal())?
}

A solution that might be better, depending
If, for some reason, you really don't what to factor, you can also do the following
void Nonterminal() : {}
{
    LOOKAHEAD( <TOKEN> <COLON> A() <COMMA>)
    <TOKEN> <COLON> A() <COMMA> Nonterminal()
|
    <TOKEN> <COLON> A()
}

Here, the parser will look ahead in input stream.  If it sees the comma, the first choice is taken.  Otherwise, the second.
This might be useful if the semantic actions are different in the two cases.  E.g.
  LOOKAHEAD( <TOKEN> <COLON> A() <COMMA>)
  <TOKEN> {doSomething();} <COLON> A() <COMMA> Nonterminal()
|
  <TOKEN> {doSomethingDifferent();} <COLON> A()

A nonrecursive solution.
A third alternative is
void Nonterminal() : {}
{
    Foo() (<COMMA>  Foo() )*
}

void Foo() : {}
{
    <TOKEN> <COLON> A()
}


text:
Q: OnKey and SendKeys starts a recursive loop, why? Every key pressed a-z A-Z 0-9 starts a macro called LetterPress with the key pressed as a parameter. Basically I have an Application.OnKey for every key a-z A-Z 0-9
If the active cell is a certain cell I want to start a sub, else I just want to send the key like normal. That starts a recursive loop that doesn't end. This was the original code:
Sub LetterPress(B as String)
If Application.ActiveCell.Row = 3 And Application.ActiveCell.Column = 5 And Application.ActiveSheet.Name = "Search" And Not IsNumeric(B) Then
    Call Search1(B)
Else
    Application.SendKeys B       'This line starts a recursive loop
End if

I tried to reset OnKey, send the key and then assign the key back to the macro. But the last row (the assign bit) still starts a recursive loop.
Sub LetterPress(B as String)
If Application.ActiveCell.Row = 3 And Application.ActiveCell.Column = 5 And Application.ActiveSheet.Name = "Search" And Not IsNumeric(B) Then
    Call Search1(B)
Else
    Application.OnKey B          'Reset Application.OnKey so a recursive loop doesn't start. This line works.
    Application.SendKeys B       'Send the string B (a letter). This works too.
    Application.OnKey B, "'LetterPress """ & B & """'"      'Assign whatever is in string variable B back to the
End if                                                      'macro, with it self as the parameter.
                                                            'This line somehow triggers B and starts the
                                                            'recursive loop.

Anyone knows why?

A: This may work:
Sub LetterPress(B as String)
If Application.ActiveCell.Row = 3 And Application.ActiveCell.Column = 5 And Application.ActiveSheet.Name = "Search" And Not IsNumeric(B) Then
    Call Search1(B)
Else
    Application.OnKey B          'Reset Application.OnKey so a recursive loop doesn't start. This line works.
    Application.SendKeys B       'Send the string B (a letter). This works too.
    Application.DoEvents
    Application.OnKey B, "'LetterPress """ & B & """'"      'Assign whatever is in string variable B back to the
End if                                                      'macro, with it self as the parameter.
                                                            'This line somehow triggers B and starts the
                                                            'recursive loop.

That being said; I have never actually tried using DoEvents() function. Let me know if it works.

A: Your attempt is not that bad. The problem is that with Application.SendKeys B, you are sending the key, but it is not processed. First your code is executed until the very end, then Excel gets back the control and can process the key stroke. At that time, your OnKey-definition is already active.
There is, however, a simple solution: Give Excel the opportunity to do the work. You can do so with DoEvents.
Application.OnKey B
Application.SendKeys B
DoEvents
Application.OnKey B, "'LetterPress """ & B & """'"

I did a test and at least it worked for me - I am curious if you can confirm.


text:
Q: Tikz: fade out edge through dots halfway through I have an edge from node A to node B:
\draw[] (A) edge (B);

This creates an edge as follows:
A --------------------------------- B

I would like to know what properties I have to fill inside [] such that the edge looks as follows:
A -------- - - -                     B

In other words, the edge should only be visible until the half of the path between A and B (or until some fixed distance would be fine too), and the edge should fade out trough dots.

A: Not exactly fading, but would this be sufficient? Using calc:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}[
    thick]
    \node (A)  at (0,0)  {A};
    \node (B)  at (5,0) {B};
    \draw[] (A) edge ($(A)!0.45!(B)$) edge [dotted] ($(A)!0.55!(B)$);
\end{tikzpicture}
\end{document}

basically, it's drawing a plain edge between A and 45% of the path from A to B, and then adds a 10% lenght of dotted path. You can clearly change the numbers (or add more sections, like another one with more spaced dots, or with gray dots, you got the idea).
You can use absolute distances on the line (see section 13.5.4 of the tikz manual, "The Syntax of Distance Modifiers"):
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}[
    thick]
    \node (A)  at (0,0)  {A};
    \node (B)  at (5,3) {B};
    \draw[] (A) edge ($(A)!3cm!(B)$) edge [dotted] ($(A)!3.4cm!(B)$);
\end{tikzpicture}
\end{document}


text:
Q: Why would I want to upgrade an iMac graphics? I'm considering getting a new iMac and am wondering about upgrading the video card to the ATI Radeon HD 4670. Gaming would obviously benefit from the upgraded video capabilities but what else?
Video Editing (iMovie vs Final Cut Express/Pro)?
Image Editing?
Viewing movies (720p vs 1080p)?
Converting videos to a different format?
Anything else?

A: Everything openCL-aware. You can consider this as an investment for the future.


text:
Q: Laravel 5.4 - Passing Data from Controller to Artisan Handle To get things started, I made a custom Artisan Command called MySqlRestore.
It simply restores the database using the dumped sql file.
Here's my MySqlRestore code:
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class MySqlRestore extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'db:restore';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Restores database using info from .env';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $sqlfile = //data from controller;

        $ds = DIRECTORY_SEPARATOR;
        $host = env('DB_HOST');
        $username = env('DB_USERNAME');
        $password = env('DB_PASSWORD');
        $database = env('DB_DATABASE');

        $mysqlpath = 'C:\xampp\mysql\bin\mysql';
        $path = 'C:\salesandinventory\Backups\\';

        $command = sprintf($mysqlpath . ' --user=' . $username . ' --password=' . $password . ' --host=' . $host . ' ' . $database . ' < ' . $path . $sqlfile);

        exec($command);
    }
}

Now on this line $sqlfile = //data from controller;, I need the data from my controller.
Here's how my controller looks like:
<?php

namespace App\Http\Controllers;

use App\Database;
use Illuminate\Http\Request;
use Artisan;

class DatabaseController extends Controller
{
    public function index()
    {
        return view('database.index');
    }
    public function restoreDatabase(Request $request)
    {
        $sqlfile = $request->sqlfile; // the data I need.

        Artisan::call('db:restore');
        return view('database.index');
    }
}

Now I don't have any idea how to pass $sqlfile = $request->sqlfile; this data from my controller into my Artisan handle function.

A: Data's are passed through the protected $signature using curly braces {dataName}
e.g
protected $signature = 'db:restore {dataName}'

and it is called using
$this->argument('dataName');

In your controller
Artisan::call('db:restore',['test'=> $test]);

namespace App\Console\Commands;

use Illuminate\Console\Command;

class MySqlRestore extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'db:restore {test}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Restores database using info from .env';

    public $sqlFile;
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $sqlfile = $this->argument('test');

        $ds = DIRECTORY_SEPARATOR;
        $host = env('DB_HOST');
        $username = env('DB_USERNAME');
        $password = env('DB_PASSWORD');
        $database = env('DB_DATABASE');

        $mysqlpath = 'C:\xampp\mysql\bin\mysql';
        $path = 'C:\salesandinventory\Backups\\';

        $command = sprintf($mysqlpath . ' --user=' . $username . ' --password=' . $password . ' --host=' . $host . ' ' . $database . ' < ' . $path . $sqlfile);

        exec($command);
    }
}

Call it like this

Artisan::call('db:restore',['test'=> $test]);

A: <?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class MySqlRestore extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'db:restore';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Restores database using info from .env';

    public $sqlFile;
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct($sqlFile)
    {
        $this->sqlFile = $sqlFile;
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $sqlfile = $this->sqlFile;

        $ds = DIRECTORY_SEPARATOR;
        $host = env('DB_HOST');
        $username = env('DB_USERNAME');
        $password = env('DB_PASSWORD');
        $database = env('DB_DATABASE');

        $mysqlpath = 'C:\xampp\mysql\bin\mysql';
        $path = 'C:\salesandinventory\Backups\\';

        $command = sprintf($mysqlpath . ' --user=' . $username . ' --password=' . $password . ' --host=' . $host . ' ' . $database . ' < ' . $path . $sqlfile);

        exec($command);
    }
}

Controller
<?php

namespace App\Http\Controllers;

use App\Database;
use Illuminate\Http\Request;
use Artisan;

class DatabaseController extends Controller
{
    public function index()
    {
        return view('database.index');
    }
    public function restoreDatabase(Request $request)
    {
        $sqlfile = $request->sqlfile; // the data I need.

        Artisan::call('db:restore',['sqlFile'=>$sqlFile]);
        return view('database.index');
    }
}

A: Your controller should not be executing Artisan commands, especially potentially long-running ones like executing a database back-up.
Instead, consider dispatching a queued job that performs the restore. You can then return control to the user and they can get on with things they need to do, instead of keeping a web page open that could possibly timeout and leave the database in a corrupt state.
class DatabaseRestoreController extends Controller
{
    public function store(Request $request)
    {
        dispatch(new RestoreDatabaseJob($request->input('filename')));

        return redirect()->back()->withSuccess('Restoring database.');
    }
}

And the job class itself:
class RestoreDatabaseJob implements ShouldQueue
{
    use InteractsWithQueue;

    public $filename;

    public function __construct($filename)
    {
        $this->filename = $filename;
    }

    public function handle()
    {
        Artisan::call('db:restore', [
            'filename' => $this->filename,
        ]);

        // You can notify user restore completed
        // Send email, SMS via notification etc.
    }
}


text:
Q: angular-file-upload to nodejs backend unable to read file contents I'm using angular file upload which previously did work when I used Laravel Lumen for the backend but I've moved to Node and unable to return the file contents of an upload.
FRONT END ANGULAR
$scope.upload = Upload.upload({
    url: ENV.apiEndpoint + '/upload',
    method: 'POST',
    data: {
        fname: $scope.fname
    },
    file: file
}).progress(function(evt) {

}).success(function(data, status, headers, config) {
});

BACK END NODE
upload/index.js
'use strict';

var express = require('express');
var controller = require('./upload.controller');

var router = express.Router();
var multer = require('multer');

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './my-uploads');
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now());
  }
})

var upload = multer({ storage: storage });

router.post('/', upload.single('file'), controller.index);

module.exports = router;

upload/upload.controller.js
'use strict';

var _ = require('lodash');
var db = require('../../db');
var https = require('https');
var Q = require('q');
var fs = require('fs');
var multer = require('multer');

exports.index = function(req, res, next) {
    console.log(req.files.file);
    res.status(204).end();
};

Old Laravel Lumen Request
public function data(Request $request) {

    $path_parts = pathinfo($_FILES["file"]["name"]);
    $extension = $path_parts['extension'];
    $contents = file_get_contents( $_FILES['file']['tmp_name'] );
    return response()->json(['type'=> $extension, 'content'=> $contents]);
}

All I'm looking to do is upload a file but only return the contents of the file to the front end again I dont want the file to be stored.

A: Here you have an example, you have a couple of things wrong. Check it out
 var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public/images/banks')
  },
  filename: function (req, file, cb) {
    crypto.pseudoRandomBytes(16, function (err, raw) {
      cb(null, raw.toString('hex') + path.extname(file.originalname));
    });
  }
});
var upload = multer({storage: storage});

router.post('/uploadImage', upload.single('file'), function (req, res, next) {
  if(!req.file) {
    res.status(400);
    res.send({error: 'No se pudo subir el archivo'});
  }

  res.send({filename: req.file.filename});
});


text:
Q: How to create animation on asp:Image control? I actually have a header banner on my page which randomly changes every 9 seconds. But changes happen in a flash. I would like to add a fade animation effect or any smooth effect while the banner image changes.
I have asp.net code below for this purpose-
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
    <asp:Timer ID="Timer1" runat="server" Interval="9000" Enabled="True"></asp:Timer>
    <asp:Image ID="Image1" runat="server" CssClass ="slider"/>
</ContentTemplate>

My vb code page has below code-
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        SetImageUrl()
    End If
End Sub

'Image slide show
Private Sub SetImageUrl()
    Dim _rand As New Random()
    Dim i As Integer = _rand.[Next](1, 6)
    Image1.ImageUrl = "~/images/banner/" & i.ToString() & ".jpg"
End Sub

Protected Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    SetImageUrl()

End Sub

Can anyone please give me any solution that might work with this code setup?

A: So here's the solution which i'm using now. I have completely removed ajax and asp.net controls and instead used html  with jQuery cycle http://jquery.malsup.com/cycle/ Thanks to TasosK for the heads up. I somehow lost the actual link of stack from where i borrowed few lines of code-


text:
Q: Generating YAML file from existing JAVA Spring API Is there any way of generating YAML file from existing Soap based API build in JAVA Spring ?
I need to generate swagger definition file (YAML file) from existing Java spring API.

A: You can create Rest API above your Soap client and then just enable Swagger in the project. Here you can see how to add Swagger in your application Setting Up Swagger 2 with a Spring REST API.


text:
Q: how do I get the EXACT number of months between two dates? DATEDIFF(MONTH, '1/1/2014', '12/31/2014') + 1

This will give me 12.
What if I do this:
DATEDIFF(MONTH, '1/1/2014', '12/30/2014') + 1

It should give me 11 point something. How do I go about getting the exact number of months between these two dates? This needs to work for any combination of dates (any month of the year for any year).

A: You could do the calculation yourself in the following way:
DECLARE @startdate date = '1/1/2014'
DECLARE @enddate date = '12/30/2014'

DECLARE @startday int = DATEPART(DAY, @startdate)
DECLARE @endday int = DATEPART(DAY, @enddate)
DECLARE @startdateBase date = DATEADD(DAY, 1 - @startday, @startdate)
DECLARE @enddateBase date = DATEADD(DAY, 1 - @endday, @enddate)

DECLARE @deciMonthDiff float = CAST(DATEDIFF(MONTH, @startdate, @enddate) AS float) -
  (@startday - 1.0) / DATEDIFF(DAY, @startdateBase, DATEADD(MONTH, 1, @startdateBase)) +
  (@endday - 1.0) / DATEDIFF(DAY, @enddateBase, DATEADD(MONTH, 1, @enddateBase))

SELECT @deciMonthDiff

This calculates the @deciMonthDiff to be 11.935483870967.
Of course you can "inline" this as much as you want in order to avoid all the middle declarations.
The idea is to calculate the total month diff, then subtract the relative part of the first & last month depending on the actual day.

A: DATEDIFF with the MONTH option only returns an integer value. Using days or years would give you a rough "guesstimate" but still not exactly right (different number of days in a month/year so you can't just divide the days difference by 30).
If you want exact you would need to write your own function to walk through the months from start until end and account for how many days are in each month and get a percentage/factor of that month covered.

A: DECLARE @startdate date = '1/1/2014'
DECLARE @enddate date = '12/30/2014'

select  case when  DATEPART(DAY, @startdate) <=  DATEPART(DAY, @enddate)
    then datediff(month, @startdate, @enddate)
    else datediff(month, @startdate, @enddate) -1
    end

from Chris The Jedi of T-SQL


text:
Q: Book with a concept about accepting a bribe What I remember about this book is:
I probably read it in the late '70s or anytime in the '80s.
It's set in the future, I seem to remember there being multiple planets.
The political situation is that things seem to have settled down: no great political agitation, everything just going along.
There is a universal basic income, so lots of people just live off that, sit around watching TV etc. all day.
A group of friends decide to start a new political party to shake things up and have some fun etc. It succeeds rather better than they had thought it would.
One very specific issue is that they made a rule, right in the beginning, that they would accept bribes and make them part of the general fund. They go on to make a lot of money for their new party doing this.

A: Thanks to @Lorendiac for the answer. This is Trample an Empire Down (1978), by Mack Reynolds.