text:
Q: How to view all xml_nodeset class object (output of rvest::html_nodes) in R? If we create an object of class xml_nodes using rvest's html_nodes(), how can we view all of the output in the R console
Example
library(rvest)
library(dplyr)

# Generate some sample html
a <- rep("

", 200) %>% paste0(collapse="")

a <- a %>% read_html %>% html_nodes("p")

a %>% length
# 200

# But only see first 20 (want to see all)

A: You can type in print.AsIs(a) to print the entire list.
(Truncated for brevity.)
library(rvest)
#> Loading required package: xml2
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union

# Setup data
a <- rep("

", 200) %>% paste0(collapse="")
a <- a %>% read_html %>% html_nodes("p")

# Print everything
print.AsIs(a)
#> [[1]]
#> {html_node}
#>

#>
#> [[2]]
#> {html_node}
#>

#>
#> [[3]]
#> {html_node}
#>

...
#>
#> [[197]]
#> {html_node}
#>

#>
#> [[198]]
#> {html_node}
#>

#>
#> [[199]]
#> {html_node}
#>

#>
#> [[200]]
#> {html_node}
#>

#>
#> attr(,"class")
#> [1] "xml_nodeset"

Created on 2019-11-13 by the reprex package (v0.3.0)
You can also alter the print() function to print everything in a condensed way.
(Also truncated for brevity.)
# Alternative condensed printing
print(a, max_n = 200)
#> {xml_nodeset (200)}
#>   [1]

\n
#>   [2]

\n
#>   [3]

\n
...
#> [198]

\n
#> [199]

\n
#> [200]

Created on 2019-11-13 by the reprex package (v0.3.0)


text:
Q: Catboost Regression. Function Extrapolation I'm new at ML and have a problem with catboost. So, I want to predict function value (For example cos | sin etc.).
I went over everything but my prediction is always straight line
Is it possible and if it is, how i can issue with my problems
I will be glad to any comment ))
train_data = np.array(np.arange(1, 100, 0.5))
test_data = np.array(np.arange(100, 120, 0.5))

train_labels = np.array(list(map(lambda x : math.cos(x), np.arange(1, 100, 0.5))))

model = CatBoostRegressor(iterations=100, learning_rate=0.01, depth=12, verbose=False)
model.fit(train_data, train_labels)
preds = model.predict(test_data)

plt.plot(preds)
plt.show()

This picture shows what i want:

A: The underlying model of CATBoost is decision trees. Outside of the domain they have been trained on, their continuation is a straight line. So there is no way for it to generate other results for values outside of the range seen during training. It also cannot learn the periodicity of your function.
A polynomial kernel model (with SVM) might do a bit better, but also likely to diverge quickly outside the training domain. In general, avoid extrapolation with machine learning, if you can.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Re-mounting a live OS filesystem I'm running Debian live on a USB flash storage device and I accidentally removed the drive.
Now I keep getting input/output errors:
bash:     /usr/bin/xyz: Input/output error.

*

*The drive originally mounted as: /dev/sdb1.

*But now it's auto-mounting as: /dev/sdc1.

How do I get it to mount as: /dev/sdb1 again, so I can avoid a reboot?
FYI: The device is identifiable as:
/dev/disk/by-label/Debian\x20Live.


text:
Q: GetValue always getting null/default regardless of type I noticed that the following statement produces a discrepancy.
public static string GetValidation(this IConfiguration self, string key)
{
  IConfigurationSection section = self.GetSection(key);

  string value1 = section.Value;
  string value2 = section.GetValue<string>(key);

  return "";
}

The corresponding section in the config has correctly set value and is correctly located using the specified path.
...
"SomePath": "Some value",
"AlsoTried": 13,
"AndEven": true,
...

The first value is as expected, the content of the node. The second is null. When I tried typing to integers and booleans, I got zero and falsity, i.e. defaults (of course I changed the value in the config file to non-string, e.g. 13 and true respectively.
I've scrutinized the docs and googled the issue, coming up with nothing useful.
What am I missing here (because I'm sure like a rat's behind it's not a bug in .NET, hehe)?

A: I'm going to assume you are passing test:SomeValue as your key and you configuration looks like:
"test": {
    "SomePath": "Some value",
    "AlsoTried": 13,
    "AndEven": true
}

Your call to self.GetSection(key); is returning the specific value you have asked for e.g.
var section = self.GetSection("test:SomePath");

This means section is now the "value" of that path e.g. Some value, which is why the section.Value property returns the correct data. But when you call section.GetValue<string>("test:SomePath") or just section.GetValue<string>("SomePath") then section does not contain a KeyValuePair for "SomePath", so you get null.
If you call GetValue<string>(key) on self it will return the correct value:
var section = self.GetValue<string>(key);

A: the values in your configuration should be all strings. Use GetValue to convert them to their proper formats. Configuration is supposed to be a dictionary of < string Key, string Value>.
"SomePath": "Some value",
"AlsoTried": "13",
"AndEven": "true",

with the following commands, you should get the proper values and their types
section.GetValue<int>("AlsoTried"); // out type will int and value 13.
section.GetValue<bool>("AndEven"); // out type will be bool and value true

hope it helps.
Found this URL that explains about Configuration and data retrieval as well. Good read.


text:
Q: close button overlap scrollbar (position:fixed)

I'd like to fixed position right of the div inside the scrollable div.
But the fixed div just overlaps the parent div's scrollbar!
How to fix it?
(must be fixed, only css)
div {
    position:fixed;
    left:0;
    top:0;
    width:100%;
    height:100%;
    overflow-y:auto
}

div a {
    position:fixed;
    right:15px;
    top:15px;
    width:30px;
    height:30px;
    background-color:red;
    border-radius:100%
}

A: You just need to increase your right pixels little more to move the button. Here is the updated CSS for your reference.

div {
    position:fixed;
    left:0;
    top:0;
    width:100%;
    height:100%;
    overflow-y:auto
}

div a {
    position:fixed;
    right:25px;
    top:15px;
    width:30px;
    height:30px;
    background-color:red;
    border-radius:100%
}

A: If the scroll bar is on the body (which is the default behaviour when the page content is long), the fixed position div will not overlap on the scroll bar.
In your case, most likely the scroll bar is of one of the elements with overflow: scroll; or overflow: auto; or alike, that's why that div is overlapping.
Since we don't know what's your full HTML/CSS, we cannot tell which one is causing the issue or how to fix it.


text:
Q: Forever log and logrotate I use forever to launch my nodeJs server and I choose the log file :
forever -l /home/api/log/api_output.log start server.js
I use logrotate to move logfile every day (like advise here : NodeJS/Forever archive logs), after one day my directory is like this :
-rw-r--r--  1 root root     0 avril 18 12:00 api_output.log
-rw-r--r--  1 root root 95492 avril 18 12:01 api_output.log-20140418
So, rotation is working, but the logs messages are now written in api_output.log-20140418, instead of api_output.log
Maybe somebody can help me ?

A: I forgot copytruncate option in my config file, now it's working :
/etc/logrotate.d/api :
/home/api/log/api_output.log {
  #size 50k
  daily
  dateext
  missingok
  rotate 7
  compress
  delaycompress
  notifempty
  #create 644 root
  copytruncate
}

A: i think it's because of living stream between forever and the log file.
forever use file stream to log file. and you renamed this file by logrotate. but stream don't change.
so log messages were written in api_output.log-20140418.
if you want to change stream, you should rotate by node.js code, or use pipeline.


text:
Q: iOS 10 - Repeating notifications every "x" minutes In iOS 10, how can I set local notifications to repeat in minutes starting from a particular date/time.
For example, trigger local notification every 15 minutes starting from 11 AM on 8th September? Assume that, below, dateTimeReminder.date has 09/08 11 AM.
let dateStart = self.dateTimeNotif.date
let notifTrigger = UNCalendarNotificationTrigger.init(dateMatching: NSCalendar.current.dateComponents([.day, .month, .year, .hour, .minute], from: dateStart), repeats: true)
let notificationRequest = UNNotificationRequest(identifier: "MYNOTIF", content: notifContent, trigger: notifTrigger)

UNUserNotificationCenter.current().add(notificationRequest, withCompletionHandler: nil)

With the above code, I have a possibility to schedule at a particular minute of every hour, at a particular hour of each day and so on. But how do I turn it into "every "x" minutes"? Any help is appreciated.
Similar question - How do I set an NSCalendarUnitMinute repeatInterval on iOS 10 UserNotifications?

A: Swift 3/4 and iOS 10/11:
According with this bug seems there is no way to use DateComponents() to repeat correctly a local notification.
Instead of this method you can change your trigger with TimeInterval (this method works if you interval is major than 60 seconds):
let thisTime:TimeInterval = 60.0 // 1 minute = 60 seconds

// Some examples:
// 5 minutes = 300.0
// 1 hour = 3600.0
// 12 hours = 43200.0
// 1 day = 86400.0
// 1 week = 604800.0

let trigger = UNTimeIntervalNotificationTrigger(
            timeInterval: thisTime,
            repeats: true)

A: As you are already aware, you can schedule maximum of 64 notifications per app. If you add more than that, the system will keep the soonest firing 64 notifications and will discard the other.
One way to make sure all notifications get scheduled is to schedule the first 64 notifications first, and then on regular time intervals (may be on every launch of the app or each time a notification fires) check for the number of notifications scheduled and if there are less than 64 notifications, lets say n notifications, then schedule the next (64 - n) notifications.
int n = [[[UIApplication sharedApplication] scheduledLocalNotifications] count];
int x = 64 - n;
// Schedule the next 'x' notifications

for rest add a NSTimer for X minutes to come and set the notification.
override func viewDidLoad() {
    super.viewDidLoad()
    //Swift 2.2 selector syntax
    var timer = NSTimer.scheduledTimerWithTimeInterval(60.0, target: self, selector: #selector(MyClass.update), userInfo: nil, repeats: true)
    //Swift <2.2 selector syntax
    var timer = NSTimer.scheduledTimerWithTimeInterval(60.0, target: self, selector: "update", userInfo: nil, repeats: true)
}

// must be internal or public.
func setNotification() {
    // Something cool
}

Make sure you remove old and not required notifications.

A: After searching around quite a bit, I've come to the conclusion that Swift 3, at this point, doesn't support this feature. For everyone looking for this functionality, I'd suggest using UILocalNotification for now (although deprecated in iOS 10), but later migrate to UNUserNotification once it supports this feature. Here are some additional questions and resources that have helped me to reach this conclusion. Also, please follow all the answers and comments in this thread to get more insight into which particular scenario it talks about.

*

*It is usually a bad idea to use deprecated APIs. As a general practice, migrate to new APIs as soon as possible. The above solution is NOT recommended as a permanent solution.

Local Notification every 2 week
http://useyourloaf.com/blog/local-notifications-with-ios-10/
https://github.com/lionheart/openradar-mirror/issues/14941

A: This is how I set local notification based on time interval repeatedly and executed  method customized snooze and delete
let content = UNMutableNotificationContent()
content.title = "Time Based Local Notification"
content.subtitle = "Its is a demo"
content.sound = .default
content.categoryIdentifier = "UYLReminderCategory"
//repition of time base local notification in foreground, background, killed
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
let request = UNNotificationRequest(identifier: "IOS Demo", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: [])
let deleteAction = UNNotificationAction(identifier: "UYLDeleteAction", title: "Delete", options: [.destructive])
let cat = UNNotificationCategory(identifier: "UYLReminderCategory", actions: [snoozeAction, deleteAction], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([cat])

A: I think this thread has what you're looking for.
Do something every x minutes in Swift
The '60.0' represents seconds between the code running. Simply change that to x minutes * 60

A: The link you shared and the new details you added you need to save the last hour and minute of time for which notification got scheduled. Then when the timer ticks to next minute, there change the hour and minute
var date = DateComponents()
date.hour = 8
date.minute = 30

let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
let content = UNNotificationContent()
// edit your content

let notification = UNNotificationRequest(identifier: "myNotification", content: content, trigger: trigger)

A: You can first use the UNCalendarNotificationTrigger to trigger the notification at a particular date and set its repeat property to false so that it notifies only once. When you receive that notification, use the UNTimeIntervalNotificationTrigger API to set the time interval at which you want to trigger the local notification


text:
Q: After installing Ubuntu, partitions do not match mounted directories I installed an Ubuntu server in a virtual machine. What I really don't understand is the differences between parted and the mounted file system.
I allocated a 100GB disk in vmware and it seems to be split in 3.
Can someone explain this ?
$ cd /
$ sudo df -h

Filesystem                     Size  Used Avail Use% Mounted on
/dev/mapper/hostname--vg-root   36G  1.7G   32G   6% /
udev                            32G  4.0K   32G   1% /dev
tmpfs                          6.3G  240K  6.3G   1% /run
none                           5.0M     0  5.0M   0% /run/lock
none                            32G     0   32G   0% /run/shm
/dev/sda1                      236M   33M  191M  15% /boot

$ sudo parted
GNU Parted 2.3
Using /dev/sda
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) p
Model: VMware Virtual disk (scsi)
Disk /dev/sda: 107GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start   End    Size   Type      File system  Flags
 1      1049kB  256MB  255MB  primary   ext2         boot
 2      257MB   107GB  107GB  extended
 5      257MB   107GB  107GB  logical                lvm

is it related to LVM stuff?
I asked the installer to use the entire disk, but I don't remember if I asked to setup LVM's maybe I should not have.

A: This configuration works but it's a bit messed up.
The output of parted shows that you have just 2 usable partitions:
 1      1049kB  256MB  255MB  primary   ext2         boot

This is the boot partition.
 2      257MB   107GB  107GB  extended
 5      257MB   107GB  107GB  logical                lvm

This is the main (root) partition, using LVM, contained inside an extended partition. It was unnecessary to create it as such -- you could have created it as a primary partition, especially since it uses LVM so you aren't limited by the "only 4 primary partitions" rule.
There's a Logical Volume of 36G that has been created inside the Volume Group that includes the 107-Gb Physical Volume. The rest of the space in the Volume Group hasn't been used and is wasted; you should either increase the size of the existing LV, or create another LV e.g. to mount in /home.
The output of df shows that the boot partition and the Logical Volume are respectively mounted on /boot and /, as it should be:
/dev/sda1                      236M   33M  191M  15% /boot
/dev/mapper/hostname--vg-root   36G  1.7G   32G   6% /

and the other entries are just pseudo filesystems in RAM:
udev                            32G  4.0K   32G   1% /dev
tmpfs                          6.3G  240K  6.3G   1% /run
none                           5.0M     0  5.0M   0% /run/lock
none                            32G     0   32G   0% /run/shm


text:
Q: configuring linux server to send traffic to local machines using local IP address Two linux servers, server1 and server2, are on the same local network (they also have access to an external network).
Server2 has a local IP of 192.168.0.2 and a host name of host2.mydomain.com.
QUESTION 1: If an application on server1 sends traffic to server2 using a host name of host2.mydomain.com, what determines whether this traffic is routed to server2 using the local or external network?
QUESTION 2: To ensure that all traffic sent from server1 to server2 always uses the local network, could I simply include in the server1 /etc/hosts file the following?
192.168.0.2 host2.mydomain.com

...the thinking being, if the servers are always on the same network there should never be a need for server2 to send traffic to server1 via the external network (that I can think of anyway). Is this done in practice, or is some other method preferred?

A: Your question 2 is actually the correct answer, but doublecheck that you have:
hosts: files dns
in your /etc/nsswitch.conf
just to be sure.
generally external dns should be in your dns record, but in server1, files (which means /etc/hosts in this case) will take precedence and thus used to resolve the host to the internal ip, while the rest of internet will resolve the same hostname to the external ip.
the usual practice though is to use an internal domain altogether if you have to use dns name (mydomain.local for example).

A: As long as that host/DNS record is a private IP it will never route though the internet. You can view the routing table using route -n. The routing table will show you the path it takes to the destination network. If it the name resolved to an IP that was on another subnet (ie the internet) than it would route the traffic there accordingly
For your second question, if you add the 192.x.x.x HOSTNAME to the /etc/hosts file then it will always resolve to that. The DNS query would first look there, local cache, and if it's in neither then it will go thru name servers for resolution.


text:
Q: When is the ideal time to hold a chat room event to accommodate the most users, in particular users with close vote privileges? I wanted to run a weekly, 1-hour event, and initially set the time, somewhat haphazardly, to my lunch hour, 9:00pm UTC (as I expected to be alone in participation at first anyway).
However, several users indicated interest, and one user expressed not being able to participate because 9:00pm UTC meant 2:30am IST (India Standard Time; and I imagine we have a lot of SO users there).
When is the ideal time to hold a 1-hour chat room event, to accommodate the most SO users?
Of course, this depends on the type(s) of users one wishes to attract. For example, for my event, I'd be ecstatic to learn

*

*which hour on a typical weekday has the most activity from users with >3k rep, or

*which hour on a typical weekday has the most moderation activity,

as these would correlate best to the type(s) of users I wish to attract.
* However one defines "activity"—whether "votes cast per hour" or "pages visited per hour," I have a feeling the results of most definitions would correlate well enough to determine an hour that's most likely to work well.
I might attempt to write some Stack Exchange Data Explorer queries, but besides that my T-SQL isn't too great, I'm under the impression that these kinds of entire-site-wide/entire-user-wide queries are likely to time out. Perhaps though there'll be ways to restrict the queries enough to produce meaningful results.

A: Here's a query that counts the number of 3k+ users active on any given hour (ignoring the day) since '2013-10-01'.
Here's the same query, but distinguishing activity based on the day.
These queries are largely unoptimized - they're just the first way of doing it that came to mind. There could be plenty of ways of getting more in-depth results - feel free to extend it appropriately, I just provided the basic query.
The results show that the ideal time is largely focussed around 15:00 - 16:00 (UTC apparently), but the deviation in the intervals around that interval is not too great.
By just changing the ORDER BY, I get a nice little graph:

(x-axis is hour, y-axis is number of users)

A: tl;dr
1:30pm UTC to 2:30pm UTC might be the ideal time to hold a chat room event centered around moderation activity. (See the conclusion for a more qualified answer.)

Background
To make the event widely to users who review the close votes queue, an ideal solution might have come from being able to query for data on close vote reviews. However, that data isn't yet available, though possibly underway (see @Emracool's request and @Shog9's proposal). Data on close and reopen votes seemed a promising proxy, but I found not only that full timestamps weren't available on the Votes table, but also that this data stopped being available after June 25th, 2013 (due to internal refactoring).
So, what to use as a metric on activity?
@juergend, @rene, and @Dukeling all proposed some nice answers—measuring activity based on posts. @Dukeling also grouped his results by distinct users, which I thought was an insightful addition, since I'm looking to maximize exposure to active users, not just the busiest active users. I wasn't convinced though, about basing the metric on posts. Like @Dukeling commented himself, for example, higher rep users probably don't ask as many questions; and personally, while I agreed that answers and comments were good indicators of activity, I wasn't sure they'd correlate as well to moderation activity.
Suggested Edits
What about suggested edits (approvals and rejections)? After all, the suggested edits queue is the most popular of the queues (next to the close votes one), and it's strictly a moderation activity. Here's a plot of suggested edits approvals and rejections in 10-minute buckets:
SELECT
  Time,
  COUNT(*) Activity
FROM
(
  SELECT
    UserId,
    DATEADD(mi, DATEPART(hh, v.CreationDate)*60
      + DATEPART(mi, v.CreationDate)/30*30, 0) AS Time
  FROM SuggestedEditVotes v
  INNER JOIN Users ON Users.Id = v.UserId
  WHERE Users.Reputation >= 3000
) X
GROUP BY Time
ORDER BY Time

Suggested edits: approvals and rejections by >3k rep users per 30-minute window:

Interesting! Using suggested edits activity as a proxy for moderation activity, it appears the busiest window of time for moderation is between approximately 9:00am UTC and 2:00pm UTC!
At least two further adjustments can be made.
First, while doing some related research, I noticed a pattern: not only are there distinct slumps in moderation activity over the weekends, but hour-by-hour shapes on the weekend look different, too:
SELECT TOP 30
  CAST(CreationDate AS DATE) AS Date,
  MAX(Count(*)) OVER(PARTITION BY CAST(CreationDate AS DATE)) as Activity
FROM SuggestedEditVotes
GROUP BY CAST(CreationDate AS DATE)
ORDER BY Date DESC

Suggested edits: approvals and rejections per day:

Code omitted due to length. See query here.
Suggested edits: approvals and rejections by >3k rep users per 30-minute window:

So, first, let's filter out the weekend data, since I only plan to run my event on weekdays:
Suggested edits: approvals and rejections by >3k rep users per 30-minute window (weekdays):

Second, as @Dukeling first demonstrated, let's count distinct users, rather than distinct actions:
Distinct >3k rep users approving and rejecting suggested edits per 30-minute window (weekdays):

The queries are available here and here, respectively.
Conclusion
Analyzing only weekdays and the actions of users with >3k rep, it appears that

*

*11:30 UTC to 12:30 UTC sees the greatest number of suggested edits approvals/rejections.

*13:30 UTC to 14:30 UTC sees the greatest number of users approving/rejecting suggested edits.

Using suggested edits approvals and rejections as a proxy for moderation activity, these times seem ideal for holding a chat room event centered around moderation activity.

A: Based on this query only looking at new questions
select top 1 *
from
(
select datename(dw,creationdate) as dayofweek
, datepART(hh,creationdate) as hour
, count(*) as numofposts
from posts
where id > 15000000 -- limit due to timeouts
and posttypeid = 1 -- only questions
-- and creationdate > '2013-10-01' -- last month rougly
group by   datename(dw, creationdate)
, datepart(hh, creationdate)
) as t
order by 3 desc

the outcome is:
'Thursday' from 15:00 to 15:59 (I assume that is GMT/UTC...)


text:
Q: Other way for Jsoup.connect().get to prevent UI blocking I'm running the Jsoup.connect().get in an Asynctask to prevent network on main thread but this method also blocks the UI because of the get(). Any suggestions to prevent or maybe minimize the blocking?
@Override
protected Document doInBackground(String... strings) {
    Document doc = null;
    try {
        doc = Jsoup.connect(strings[0]).get();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return doc;
}

A: From your comments you have
 task.execute(url).get();

to
task.execute(url);

Calling get does not make it Asynchronous any more. It will wait for the result blocking the ui thread. Just use .execute
http://developer.android.com/reference/android/os/AsyncTask.html
public final Result get ()

Added in API level 3
Waits if necessary for the computation to complete, and then retrieves its result.

Returns
The computed result.


text:
Q: JPA: How to associate entities with relationship attributes? We can always do :
EntityA @OneToOne EntityB

@OneToOne
@JoinTable(name="table_name")
private EntityB b;

How will you ?
EntityC @OneToMany EntityD ( But this time I also have EntityType information on join )
But what if you have relationship properties associated ?
Like:
EntityC  -- JoinTable -- EntityD
                |
                |
              EntityType

Now in this case my join table has 3 ids ( EntityC_id, EntityType_id, EntityD_id )
How can I create an association with EntityC and EntityD ( With EntityType ) ?

A: I believe the standard way is to create an entity representing JoinTable with @OnetoMany references from your EntityC and EntityD. JoinTable then has its own inverse @ManyToOne references. Such as (from the JPA wikibook on M:N with additional columns):
@Entity
public class EntityC {
  @Id
  private long id;
  ...
  @OneToMany(mappedBy="entityC")
  private List<JoinTable> entityDs;
  ...
}

@Entity
public class EntityD {
  @Id
  private long id;
  ...
  @OneToMany(mappedBy="entityD")
  private List<JoinTable> entityCs;
  ...
}

Your association table is then managed as a separate entity, mapping these two entities to each other:
@Entity
@IdClass(JoinTableId.class)
public class JoinTable {
  @Id
  private long entityCId;
  @Id
  private long entityDId;
  ...
  private int entityTypeId;     //your relationship-attribute
  ...
  @ManyToOne
  @JoinColumn(name="entityCId", referencedColumnName="id", updatable="false", insertable="false")
  private EntityC entityC;
  @ManyToOne
  @JoinColumn(name="entityDId", referencedColumnName="id", updatable="false", insertable="false")
  private EntityD entityD;
  ...
}

public class JoinTableId implements Serializable {
    private long entityCId;
    private long entityDId;
    ...
    //hashCode()
    //equals(...)
}

Note that this is criticised for its duplication and redundancy of id fields across the JoinTable class and its id class, which is required by JPA. See Giannigar's blog  for an alternative suggestion (with credits).
N.B. I've hand edited a lot of this so apologies for any typos.


text: Q: Conditional methods based on reference assembly version in C# I have a project where a reference is going to be updated. Now the new reference has some API that the existing one doesn't have. And this reference is also not entirely backwards compatible with the existing reference. So I want my project to compile certain methods in a class using the [Conditional] attribute based on the reference that has been included in the build. Is it possible to do this in C#, if so how can I do this at compile time?


text:
Q: SQL order by specific values I have the following data in SQL SERVER DB

on which an ordering is needed.
The ordering is to be done on specific value of priority

*

*First ascending value of priority 1,2,3,...

*Second the row with priority 0 is shown last

After ordering on priority, rows with the same priority will be ordered alphabetically
So the expected output is

I have done the following code
SELECT SERVICELONGNAME,SERVICEPRIORITYID FROM SERVICE

ORDER BY

  CASE
            WHEN SERVICEPRIORITYID > 0 THEN 0 ELSE 1
            END
,SERVICELONGNAME ASC
enter code here

But in this case the rows with priority 0 is shown at the bottom but for SERVICEPRIORITYID  1,2,3,4 it is jumbled up.
Please can someone tell me what changes are required to match with the required output?

A: Try this
SELECT SERVICELONGNAME
    ,SERVICEPRIORITYID
FROM SERVICE
ORDER BY CASE
        WHEN SERVICEPRIORITYID > 0
            THEN SERVICEPRIORITYID
        ELSE 2147483647 -- Int max value
        END
    ,SERVICELONGNAME ASC enter code here

When SERVICEPRIORITYID is greater then 0 order by SERVICEPRIORITYID else order by int max value.

A: You can try the below -
SELECT SERVICELONGNAME,SERVICEPRIORITYID
FROM SERVICE
ORDER BY  CASE
            WHEN SERVICEPRIORITYID=0 THEN 1 ELSE 0 END,SERVICELONGNAME ASC


text:
Q: How do i make a GIT credential helper? The original question has been edited for clarity:
I have a main project that does a git clone https://my.repo.project.git.  The project has 2 targets (main target and password helper target). The repository is password protected and will ask for username, followed by a password. The main app calls the git command via the NSTask object.
NSDictionary *environmentDict = [[NSProcessInfo processInfo] environment];

[task setLaunchPath:gitExecutableLaunchPath];
[task setArguments:[NSArray arrayWithObjects:@"clone", @"https://my.repo.project.git"];
[task setCurrentDirectoryPath:path];
[task setEnvironment:environmentDict];

I have followed the concept from this project to enable my password helper target to run automatically when the main target does not have the git credentials stored in the keychain for the repo. All this secondary password helper target does is the following code (for simplicity):
int main (int argc, const char * argv[]) {
    @autoreleasepool {
        NSLog(@"Password helper has been launched");

        char *username = "my_username";
        char *password = "my_password";
        printf("%s\n", username);
        printf("%s\n", password);
    }
    return 0;

I can see in the logs that the password helper app has been launched, but i always get an "Authentication Failed message".  Any idea what i am doing wrong? My goal is to develop a credential helper App much like git's git-credential-osxkeychain app. Any help is much appreciated

A: Found the solution. Upon checking the console, i notice that that the Askpass target was being called twice. It seems that this was called the first time for the username, and the second time for the password. I used the following code to determine the reason the Askpass target was being called and responded with the appropriate value.
NSArray *args = [[NSProcessInfo processInfo] arguments];


text:
Q: Is string is number? I have simple function checking if string is number or not.
Suddenly I discovered that it don't work with "0" or "00".
Tell me why, please! And how to make it works?
string num = "00";
Int32.TryParse(num, out int n);
if (n > 0) return true; // It works nice on any digits except 0 and 00.

Also I tried:
double.TryParse(num, out double n);

But don't work too.
So I went in such way:
if ((n > 0) | (num == "0") | (num == "00")) return true;

A: Of course 0 is not greater than 0, what did you expect? :)
int.TryParse returns a boolean letting you know if parsing the number was successful:

Returns
Boolean
true if s was converted successfully; otherwise, false.

So what you oughta do is the following:
return int.TryParse(num, out int _);

A: You can create a function and call it to check if it is a number or not.
class Program
{
    static void Main(string[] args)
    {
        string num = "00";
        if (IsNumber(num))
            Console.WriteLine($"'{num}' is a number");
        else
            Console.WriteLine($"'{num}' is not a number");
    }

    private static bool IsNumber(string num)
    {
        return int.TryParse(num, out _);
    }
}

Update:
With decimal.TryParse(num, out _) you can check if a string is an integer, double or decimal number.
class Program
{
    private static void Main(string[] args)
    {
        var num = "0.07";
        Console.WriteLine(IsNumber(num) ?
            $"'{num}' is a number" :
            $"'{num}' is not a number");
    }
    private static bool IsNumber(string num) =>
        decimal.TryParse(num, out _);
}

Demo: https://dotnetfiddle.net/9LgobJ


text:
Q: How to make time picker dialog for timer Can anyone help me make timepicker dialog look like this?
I maked full layout like this and just need to know how to make selection area
in the center of listview also i set infinite loop in the listview.

here is code->
class TimePicker : AppCompatActivity(){

    private val timeSecondsAndMinutes = arrayOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
            "10", "11", "12", "13", "14", "15" , "16", "17", "18", "19", "20", "21", "22", "23",
            "24", "25", "26", "27", "28", "29" , "30", "31", "32", "33", "34", "35", "36", "37",
            "38", "39", "40", "41", "42", "43" , "44", "45", "46", "47", "48", "49", "50", "51",
            "52", "53", "54", "55", "56", "57" , "58", "59")

    private val timeHours = arrayOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9","10","11",
            "12", "13", "14", "15" ,"16", "17", "18", "19", "20", "21", "22", "23", "24", "25",
            "26", "27", "28", "29" ,"30", "31", "32", "33", "34", "35", "36", "37", "38", "39",
            "40", "41", "42", "43" ,"44", "45", "46", "47", "48", "49", "50", "51", "52", "53",
            "54", "55", "56", "57" ,"58", "59","60","61","62","63","64","65","66","67","68","69",
            "70","71","72","73","74","75","76","77","78","79","80","81","82","83","84","85","86",
            "87","88","89","90")

    private var hoursListView   : ListView? = null
    private var minutesListView : ListView? = null
    private var secondsListView : ListView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_time_picker)

        InitializeListView()
    }

    private fun InitializeListView()
    {
        hoursListView = findViewById(R.id.HoursListView) as ListView
        minutesListView = findViewById(R.id.MinutesListView) as ListView
        secondsListView = findViewById(R.id.SecondsListView) as ListView

        hoursListView!!.setSelector(R.color.ListViewItemsColor)
        minutesListView!!.setSelector(R.color.ListViewItemsColor)
        secondsListView!!.setSelector(R.color.ListViewItemsColor)

        val hoursAdapter = ArrayAdapter(this, R.layout.layout_for_listview_elements, timeHours)
        val secMinAdapter = ArrayAdapter(this, R.layout.layout_for_listview_elements, timeSecondsAndMinutes)

        val circularHoursAdapter = CircularListAdapter(hoursAdapter)
        val circularMinSecAdapter = CircularListAdapter(secMinAdapter)

        hoursListView!!.adapter = circularHoursAdapter
        minutesListView!!.adapter = circularMinSecAdapter
        secondsListView!!.adapter = circularMinSecAdapter

        hoursListView!!.setSelection(544)
        minutesListView!!.setSelection(358)
        secondsListView!!.setSelection(358)

    }

A: Use this code when click on edittext to choose the time from time picker dilog.
eReminderTime.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Calendar mcurrentTime = Calendar.getInstance();
            int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
            int minute = mcurrentTime.get(Calendar.MINUTE);
            TimePickerDialog mTimePicker;
            mTimePicker = new TimePickerDialog(AddReminder.this, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                    eReminderTime.setText( selectedHour + ":" + selectedMinute);
                }
            }, hour, minute, true);//Yes 24 hour time
            mTimePicker.setTitle("Select Time");
            mTimePicker.show();

        }
    });

A: Thanks to all of you guys i find the solution.
class TimePicker : AppCompatActivity(), AbsListView.OnScrollListener {

    private val timeSecondsAndMinutes = arrayOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
            "10", "11", "12", "13", "14", "15" , "16", "17", "18", "19", "20", "21", "22", "23",
            "24", "25", "26", "27", "28", "29" , "30", "31", "32", "33", "34", "35", "36", "37",
            "38", "39", "40", "41", "42", "43" , "44", "45", "46", "47", "48", "49", "50", "51",
            "52", "53", "54", "55", "56", "57" , "58", "59")

    private val timeHours = arrayOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9","10","11",
            "12", "13", "14", "15" ,"16", "17", "18", "19", "20", "21", "22", "23", "24", "25",
            "26", "27", "28", "29" ,"30", "31", "32", "33", "34", "35", "36", "37", "38", "39",
            "40", "41", "42", "43" ,"44", "45", "46", "47", "48", "49", "50", "51", "52", "53",
            "54", "55", "56", "57" ,"58", "59","60","61","62","63","64","65","66","67","68","69",
            "70","71","72","73","74","75","76","77","78","79","80","81","82","83","84","85","86",
            "87","88","89","90")

    private var hoursListView   : ListView? = null
    private var minutesListView : ListView? = null
    private var secondsListView : ListView? = null

    private var selectedItemHoursL : View? = null
    private var selectedItemMinutesL : View? = null
    private var selectedItemSecondsL : View? = null
    private var linearLayout : LinearLayout? = null

    private var oneTimeH : Boolean = true
    private var oneTimeM : Boolean = true
    private var oneTimeS : Boolean = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_time_picker)

        AdjustLayoutSize()
        InitializeListView()
    }

    private fun InitializeListView()
    {
        hoursListView = findViewById(R.id.HoursListView) as ListView
        minutesListView = findViewById(R.id.MinutesListView) as ListView
        secondsListView = findViewById(R.id.SecondsListView) as ListView

        hoursListView!!.setSelector(R.color.ListViewItemsColor)
        minutesListView!!.setSelector(R.color.ListViewItemsColor)
        secondsListView!!.setSelector(R.color.ListViewItemsColor)

        hoursListView!!.setOnScrollListener(this)
        minutesListView!!.setOnScrollListener(this)
        secondsListView!!.setOnScrollListener(this)

        val hoursAdapter = ArrayAdapter(this, R.layout.layout_for_listview_elements, timeHours)
        val secMinAdapter = ArrayAdapter(this, R.layout.layout_for_listview_elements, timeSecondsAndMinutes)

        val circularHoursAdapter = CircularListAdapter(hoursAdapter)
        val circularMinSecAdapter = CircularListAdapter(secMinAdapter)

        hoursListView!!.adapter = circularHoursAdapter
        minutesListView!!.adapter = circularMinSecAdapter
        secondsListView!!.adapter = circularMinSecAdapter

        hoursListView!!.setSelection(544)
        minutesListView!!.setSelection(358)
        secondsListView!!.setSelection(358)
    }

    override fun onScroll(listViewSelected: AbsListView?, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int)
    {
        if(firstVisibleItem != 0 && visibleItemCount != 0)
        {
            if (listViewSelected!!.id == hoursListView!!.id) {
                 if(oneTimeH){
                     SelectionNumberBackground(listViewSelected, hoursListView, R.drawable.selecteditem_hhss_bg)
                     oneTimeH = false
                }
            } else if (listViewSelected.id == minutesListView!!.id) {
                if(oneTimeM) {
                    SelectionNumberBackground(listViewSelected, minutesListView, R.drawable.selecteditem_mm_bg)
                    oneTimeM = false
                }
            } else if (listViewSelected.id == secondsListView!!.id) {
                if(oneTimeS) {
                    SelectionNumberBackground(listViewSelected, secondsListView, R.drawable.selecteditem_hhss_bg)
                    oneTimeS = false
                }
            }
        }
    }

    override fun onScrollStateChanged(p0: AbsListView?, p1: Int)
    {
        ChangeSelectionInList(p0)

        if (p1 == AbsListView.OnScrollListener.SCROLL_STATE_IDLE)
        {
            if(p0!!.id == hoursListView!!.id) {
                SelectionNumberBackground(p0, hoursListView,R.drawable.selecteditem_hhss_bg)
            }
            else if(p0.id == minutesListView!!.id){
                SelectionNumberBackground(p0,minutesListView,R.drawable.selecteditem_mm_bg)
            }
            else if(p0.id == secondsListView!!.id){
                SelectionNumberBackground(p0,secondsListView,R.drawable.selecteditem_hhss_bg)
            }
        }
    }

    private fun SelectionNumberBackground(p0 : AbsListView?, MainListView : ListView?, background : Int)
    {
        p0!!.setSelection(p0.firstVisiblePosition)
        val middleView = p0.firstVisiblePosition + 2
        val firstView = p0.firstVisiblePosition - MainListView!!.headerViewsCount
        val middleItem = middleView - firstView
        if (middleItem < 0 || middleItem >= p0.childCount) {
            return
        }
        val thirdView = p0.getChildAt(middleItem)
        thirdView.setBackgroundResource(background)
        if(p0.id == hoursListView!!.id){
            selectedItemHoursL = thirdView
        }
        else if(p0.id == minutesListView!!.id){
            selectedItemMinutesL = thirdView
        }
        else if(p0.id == secondsListView!!.id){
            selectedItemSecondsL = thirdView
        }
    }

    private fun ChangeSelectionInList(p0: AbsListView?)
    {
        if(p0!!.id == hoursListView!!.id) {
            if (selectedItemHoursL != null) {
                selectedItemHoursL!!.setBackgroundResource(R.color.ListViewItemsColor)
            }
        }
        else if(p0.id == minutesListView!!.id){
            if(selectedItemMinutesL != null){
                selectedItemMinutesL!!.setBackgroundResource(R.color.ListViewItemsColor)
            }
        }
        else if(p0.id == secondsListView!!.id){
            if(selectedItemSecondsL != null){
                selectedItemSecondsL!!.setBackgroundResource(R.color.ListViewItemsColor)
            }
        }
    }

    private fun AdjustLayoutSize()
    {
        //For resolution
        val display = windowManager.defaultDisplay
        val size = Point()
        display.getSize(size)
        //Get DPI
        val displayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)
        //Initialize LinearLayout for changing TimePicker Dialog Size;
        linearLayout = findViewById(R.id.TimePickerLayout) as LinearLayout
        val layoutParams = linearLayout!!.layoutParams as ViewGroup.MarginLayoutParams
        //Nexus 5X device 420dpi 1080x1920 == 1794
        if(size.y >= 1794 && size.y < 1920){
            layoutParams.topMargin = 656
            layoutParams.rightMargin = 80
            layoutParams.leftMargin = 80
        }
        //Redmi note 3 DPI 480 1080x1920
        else if(size.y == 1920){
            layoutParams.topMargin = 630
            layoutParams.rightMargin = 80
            layoutParams.leftMargin = 80
        }
        //Pixel XL device 480dpi 1440x2560 == 2416
        else if(size.y > 1920 && displayMetrics.densityDpi >= 480){
            layoutParams.topMargin = 1098
            layoutParams.rightMargin = 125
            layoutParams.leftMargin = 125
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        finish()
        overridePendingTransition(R.anim.top_to_bottom1,R.anim.top_to_bottom2)
    }
}


text:
Q: How to be more rigorous in re-defining a nested function $f(y) = e^{g(y)}$ Suppose that I am doing some sort of derivation when I have reached an expression
$$f(y) = e^{y^2}$$
At this point I would like to define $g(y) = y^2 = x$, then
$$f(y) = e^{g(y)}$$

Can I say that: "$f(x) = e^x$ under the change of variable $x
 := g(y)$"?

I am asking because technically $f$ is not a function of $g(y)$ but a function of $y$, I would be more comfortable if I had $f(g(y)) = e^{g(y)}$, then letting $x = g(y)$ we have $f(x) = e^x$. What is the best way to redefine $f(y)$ in terms of $x$?

A: $f$ is a function of $g(y)$ in the $y$ and $f(y)$ coordinate system.  But in the $x$ and $f(x)$ coordinate system then $f$ is a function of $x$.  When you say $f(x)$ you mean that you are going to write $f$ in terms of $x$ in this case $f(x) = e^x$ but $x=x(y)$ so you can also write this more explicitly as $$f(x(y))=e^{x(y)}$$.
The use of $g$ is superfluous.


text:
Q: Solve differential equation using 'variation of parameters' Given the differential equation $L \ u = f$, with $$L \ u = a_2(t) \frac{d^2u}{dt^2}+a_1(t)\frac{du}{dt}+a_0(t)u$$
with $a_i(t)$ sufficiently smooth and $a_2(t) \neq 0$ for every $t$.
Suppose that $u_0$ is a solution to the homogenenous equation $L \ u=0$, with $u_0(t)\neq0$ for every $t$.
 How can I then use the variation of parameters method by Lagrange to find the solution $u =u_0v$ ? And how can I find the general solution if the equation isn't homogeneous?
Update: I've substituted $u=u_0v$ into the equation and found a new $2^{nd}$ order differential equation of the form
$$f = \frac{d^2v}{dt^2}(a_2(t)u_0)+\frac{dv}{dt}(2a_2(t)u_0'+a_1(t)u_0)+va_0(t)u_0$$ which I'm supposed to solve for $w$ using $w=v'$. But I don't seem to be able to proceed as I'm not sure how to solve the system
$$\begin{equation}
\begin{split}
w =&\ v'\\
w'a_2(t)u_0+w(2a_2(t)u_0'+a_1(t)u_0)+v(a_0(t)u_0)=&\ f\ \\
\end{split}
\end{equation}$$

A: Here is how we can solve the homogeneous equation $ L u = 0$. Once we have both solutions of this equation, we can use the method of variation of parameters to find a solution to $ L u = f $.
First we calculate derivatives of the solution $ u = u_0 v $ that you suggested:
$$ u' = u_0' v + u_0 v' $$
$$ u'' = u_0'' v + 2 u_0' v' + u_0 v'' $$
Next, because $ u = u_0 v $ is a solution to the homogeneous equation $ a_2(t) u'' + a_1(t) u' + a_0(t) u = 0 $ we have:
$$ a_2(t) (u_0'' v + 2 u_0' v' + u_0 v'') + a_1(t) (u_0' v + u_0 v') + a_0(t) u_0 v = 0 $$
We can re-arrange the terms and the equation in terms of $ v $ and its derivatives:
$$ a_2(t) u_0 v'' + (2 a_2(t) u_0'  + a_1(t) u_0) v' + (a_2(t) u_0'' + a_1(t) u_0' + a_0(t) u_0) v = 0 $$
Now, because $ u_0 $ satisfies the equation $ L u = 0 $ , the coefficient of $ v $ is zero, and the equation becomes:
$$ a_2(t) u_0 v'' + (2 a_2(t) u_0'  + a_1(t) u_0) v' = 0 $$
This looks like a second order equation, but it can be solved as a first order equation, if we take $ w = v' $ :
$$ a_2(t) u_0 w' + (2 a_2(t) u_0'  + a_1(t) u_0) w = 0 $$
From here, we solve this equation for $ w $, calculate the integral of $ w $ to find $ v $, and multiply $ v $ by $ u_0 $ to find the solution $ u $.

A: With
$$
L(u) = u''+\frac{a_1}{a_2} u'+\frac{a_0}{a_2} u=u''+b_1 u'+b_0 u
$$
given a non null $u_0(t)$ such that $L(u_0) = 0$ being a second order $L$, we can obtain another independent solution $L(u_1) = 0$ as follows: if $c_0$ is a generic constant then $L(c_0u_0) = 0$ so choose $u_1 = c_0(t)u_0$ then we have
$$
L(c_0(t)u_0) = c_0(t)L(u_0) + u_0c''_0+(b_1u_0+2u'_0)c'_0=u_0c''_0+(b_1u_0+2u'_0)c'_0=0
$$
making $\phi = c'_0$ we have a first order DE as $\frac{\phi'}{\phi} + \frac{u_0}{(b_1u_0+2u'_0)}=0$ so obtaining $\phi\to u_1$ is direct.
Having $u_0, u_1$ for the homogeneous case, let us approach the case $L(u) = \frac{f}{a_2(t)}$. The method of variation of constants now will be applied to
$$
L(c_0(t)u_0+c_1(t)u_1)=\frac{f}{a_2(t)}
$$
so developing
$$
L(c_0(t)u_0+c_1(t)u_1)=c_0L(u_0)+c_1L(u_1) + u_0c''_0+(b_1u_0+2u'_0)c'_0+c''_1u_1+(b_1u_1+2u'_1)c'_1-\frac{f}{a_2(t)}=0
$$
Here as $c_0, c_1$ are independent we can choose them as
$$
\cases{
u_0c''_0+(b_1u_0+2u'_0)c'_0-\frac{f}{a_2(t)}=0\\
c''_1u_1+(b_1u_1+2u'_1)c'_1=0
}
$$
finally determining $c_1(t), c_2(t)$ for the non-homogeneous case.


text:
Q: How to run resque-scheduler in production with remote DB? Hi I'm finding this hard to figure out as.
I'm deploying using Capistrano, and I have quite a few recurring scheduled tasks that I'm using resque-scheduler to run.
On my local environment I would run:
QUEUE=* rake environment resque:work

to start resque and to start resque-scheduler:
rake environment resque:scheduler

this is my resque.rake file:
require 'resque/tasks'
require 'resque/scheduler/tasks'

namespace :resque do
  task :setup do
    require 'resque'
    Resque.redis = ENV['REDIS_SERVER']
  end
  task :setup_schedule => :setup do
    require 'resque-scheduler'
    Resque.schedule = YAML.load_file("#{Rails.root}/config/resque_schedule.yml")
  end

  task :scheduler_setup => :setup_schedule
end

So what I'm trying to figure out is how I get this working in production? I assume I first need to install redis on my server even though I have a remote Redis DB? Then I need to make a capistrano task, or something that make it run?

A: *

*To connect to remote redis replace Resque.redis value with
uri = URI.parse('redis://redistogo_url:9918/')
Resque.redis = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)

*You don't need to install `redis' server just the normal gem


text:
Q: SQL - Adding a blank row I'm dealing with software that will use the query I'm building to get data from the database. The problem is that the software doesn't have tools to determine the table size, so I need to add a blank row after the last row of data, so the software can recognize the end of the table.
Here's an example of what the query would give:

And here's an example of what I need to get from the query:

I know it would be better to solve it in the application, but in this case I need to change my query. Is it possible?
Edit: I'm using SQL Server 2014, the database name is Test and the table name is Table2.

A: A simple method is:
select t.*
from t
union all
select t.*
from (select 1 as x) x left join
     t
     on 1 = 0   -- always fails
order by (case when fieldA is not null then 1 else 2 end)

This returns one additional row with all columns being NULL.
Note:  SQL tables represent unordered sets, so you need an order by.  The above assumes that the first column is never NULL.

A: Use UNION ALL after your query to add the blank row:
select t.* from (
  select FieldA, FieldB
  from Table2
  ..........
  union all
  select null, null
) t
order by case when coalesce(t.FieldA, t.FieldB) is null then 1 else 0 end

or:
select t.FieldA, t.FieldB from (
  select 0 as isblankrow, FieldA, FieldB
  from Table2
  ..........
  union all
  select 1, null, null
) t
order by isblankrow

A: I have full solution available on dbfiddle for SQL Server 2014.
dbfiddlelink
The query should be,
Select *
from (select FieldA,FieldB
      from Table2
      union
      select null,null) tab
 order by FieldA Desc


text:
Q: Using InfoPath Form Web Part to Display Existing Form (not a New One) InfoPath form web part can be used to fill out a published InfoPath form (a new instance). I want to use the web part to open an already filled form to do some modifications. Can this be achieved (using this web part or any other solution)?
The reason behind this requirement is that I want to have multiple web parts in my page, content editor, query string filter and InfoPath web part. I want to use these to open a form (new or existing) in a certain mode / view.
Edit
I will try to simplify:
1- I have an InfoPath form that is saved in a SharePoint library. The form have multiple views.
2- Using a URL like http://mySite/myPage.aspx?form=myForm-20110613.xsn&view=View3, I want the form myForm-20110613.xsn to be opened and switched to View3.
How can I achieve this (preferably without writing any code)?

A: I have done that using a custom application ASPX page. The page has an Iframe that I set its src to the viewing URL as follows
private void SetIFrameSource_View(HtmlControl frame, string libraryName, string formName)
{
    string formServerPage = "http://servername/_layouts/FormServer.aspx";
    string xmlLocation = string.Format("/{0}/{1}", libraryName, formName);
    string source = "http://servername/SitePages/Home.aspx";
    frame.Attributes["src"] = string.Format("{0}?XmlLocation={1}&Source={2}&DefaultItemOpen=1", formServerPage, xmlLocation, source);
}

A: What version of InfoPath are you using? With 2013, you can insert a rule on form opening with no conditions and add action "switch views" to the view you prefer.
Click Data
Form Load
New
Add Action
Switch Views (select view).

A: Create a page and add InfoPath form webpart and save the page. Do not configure any properties for the webpart (library name or content type). Navigate to the page including your existing InfoPath form XmlLocation. eg. http://siteurl/yourpage.aspx?XmlLocation=/sites/teamsites/TestFormLibrary/aaaaa.xml
https://devdotnotes.wordpress.com/2012/01/29/sharepoint-caculated-column-and-hyperlink-no-workflow-or-script-needed/
follow this link if you want to build this url dynamically in your view.

A: You can do this with web part connections.  Watch the following video for details: http://channel9.msdn.com/Blogs/laurhar/InfoPath-2010-Manage-data-in-your-SharePoint-Lists-using-the-InfoPath-Form-Web-Part?format=auto


text:
Q: jQuery - how to write 'if not equal to' (opposite of ==) I need to reverse of the following code. How can I make the animation run if the width is NOT 500px.
$(".image-div").not(this).each(function() {
        if ($(this).css('width') == '500px') {
            $(this).animate({
                    width: '250px'
                }, 500, function() {
                // Animation complete.
            });
        }

    });

In other words, what the opposite of this?: ==
Thanks

A: The opposite of the == compare operator is !=.

A: == => !=
=== => !==
Equal and its opposite

A: if ("one" !== 1 )

would evaluate as true, the string "one" is not equal to the number 1

A: !=

For example,
if ("apple" != "orange")
  // true, the string "apple" is not equal to the string "orange"

Means not. See also the logical operators list. Also, when you see triple characters, it's a type sensitive comparison. (e.g. if (1 === '1') [not equal])


text:
Q: Ruby Net::HTTP::Post submit form I'm working on creating a website scraper. There is a form used to change the current page.
This is the way that I am submitting the form for the POST request, but it seems to be fetching the same page over and over again.
Here is some sample code:
pages = {
 "total_pages" => 19,
 "p1" => '1234/1456/78990/123324345/12143343214345/231432143/12432412/435435/',
 "p2" => '1432424/123421421/345/435/6/65/5/34/3/2/21/1243',
..
..
..
}

idx = 1
p_count = pages["total_pages"]

#set up the HTTP request to change pages to get all the auction results
uri = URI.parse("http://somerandomwebsite.com?listings")
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.request_uri)

p_count.times do
  puts "On loop sequence: #{idx}"
  pg_num = "p#{idx}"
  pg_content = pages["#{pg_num}"]
  req.set_form_data({"page" => "#{pg_num}", "#{pg_num}" => "#{pg_content}"})

  response = http.request(req)
  page = Nokogiri::HTML(response.body)
  idx = idx + 1
end

It looks like page never changes. Is there a way to see what the full request looks like each time I am looking to make sure that the proper params are getting passed? It seems like it's virtually impossible to determine anything about req.

A: A great way to debug HTTP is to take advantage of http://httpbin.org:
require 'net/http'
uri = URI('http://httpbin.org/post')
res = Net::HTTP.post_form(uri, 'q' => 'ruby', 'max' => '50')
puts res.body

Which returns:
# >> {
# >>   "args": {},
# >>   "data": "",
# >>   "files": {},
# >>   "form": {
# >>     "max": "50",
# >>     "q": "ruby"
# >>   },
# >>   "headers": {
# >>     "Accept": "*/*",
# >>     "Accept-Encoding": "gzip;q=1.0,deflate;q=0.6,identity;q=0.3",
# >>     "Content-Length": "13",
# >>     "Content-Type": "application/x-www-form-urlencoded",
# >>     "Host": "httpbin.org",
# >>     "User-Agent": "Ruby"
# >>   },
# >>   "json": null,
# >>   "origin": "216.69.191.1",
# >>   "url": "http://httpbin.org/post"
# >> }

That said, I'd recommend not using Net::HTTP. There are plenty of great HTTP clients for Ruby that will make it easier to write your code. For instance here's the same thing using HTTPClient:
require 'httpclient'
clnt = HTTPClient.new
res = clnt.post('http://httpbin.org/post', 'q' => 'ruby', 'max' => '50')
puts res.body

# >> {
# >>   "args": {},
# >>   "data": "",
# >>   "files": {},
# >>   "form": {
# >>     "max": "50",
# >>     "q": "ruby"
# >>   },
# >>   "headers": {
# >>     "Accept": "*/*",
# >>     "Content-Length": "13",
# >>     "Content-Type": "application/x-www-form-urlencoded",
# >>     "Date": "Thu, 09 Feb 2017 20:03:57 GMT",
# >>     "Host": "httpbin.org",
# >>     "User-Agent": "HTTPClient/1.0 (2.8.3, ruby 2.4.0 (2016-12-24))"
# >>   },
# >>   "json": null,
# >>   "origin": "216.69.191.1",
# >>   "url": "http://httpbin.org/post"
# >> }

This is untested code because you didn't tell us nearly enough, but it's where I'd start doing what you're doing:
require 'httpclient'

BASE_URL = 'http://somerandomwebsite.com?listings'
PAGES = [
 '1234/1456/78990/123324345/12143343214345/231432143/12432412/435435/',
 '1432424/123421421/345/435/6/65/5/34/3/2/21/1243',
]

clnt = HTTPClient.new

PAGES.each.with_index(1) do |page, idx|
  puts "On loop sequence: #{idx}"

  response = clnt.post(BASE_URL, 'page' => idx, idx => page)

  doc = Nokogiri::HTML(response.body)
  # ...
end


text:
Q: How to find the number of rows and columns in a table image with Python OpenCV? How can we get the number of rows and columns in an Image table via OpenCV.
Code for getting boxes in table which I am getting right
contours, hierarchy = cv2.findContours(img_final_bin, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

def sort_contours(cnts, method="left-to-right"):
# initialize the reverse flag and sort index
reverse = False
i = 0
# handle if we need to sort in reverse
if method == "right-to-left" or method == "bottom-to-top":
    reverse = True
# handle if we are sorting against the y-coordinate rather than
# the x-coordinate of the bounding box
if method == "top-to-bottom" or method == "bottom-to-top":
    i = 1
# construct the list of bounding boxes and sort them from top to
# bottom
boundingBoxes = [cv2.boundingRect(c) for c in cnts]
(cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
    key=lambda b:b[1][i], reverse=reverse))
# return the list of sorted contours and bounding boxes
return (cnts, boundingBoxes)

(contours, boundingBoxes) = sort_contours(contours, method="top-to-bottom")

A: Here are two methods: The first uses the structure of the table to determine the number of rows and columns while the second uses cell count.
Method #1: Table structure
The idea is that we can count the number of horizontal and vertical lines of the table to determine the number of rows and columns. For rows, it's rows = horizontal lines - 1 and for columns, it's columns = vertical lines - 1.
Detected horizontal lines in green

Detected vertical lines in green

Result
Rows: 7
Columns: 4

Code
import cv2

# Load image, convert to grayscale, Otsu's threshold
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find number of rows
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (25,1))
horizontal = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
cnts = cv2.findContours(horizontal, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
rows = 0
for c in cnts:
    cv2.drawContours(image, [c], -1, (36,255,12), 2)
    rows += 1

# Find number of columns
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,25))
vertical = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2)
cnts = cv2.findContours(vertical, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
columns = 0
for c in cnts:
    cv2.drawContours(image, [c], -1, (36,255,12), 2)
    columns += 1

print('Rows:', rows - 1)
print('Columns:', columns - 1)

cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.waitKey()

Method #2: Cell count

*

*Obtain binary image. Load image, convert to grayscale, Gaussian blur, then Otsu's threshold.

*Remove text inside cells. Find contours and filter using cv2.contourArea() to remove text by filling in the contours with cv2.drawContours()

*Invert image. We invert the image so the cells are in white and the background in black

*Sort cells and sum rows/columns. We find contours then sort the contours from top-to-bottom using imutils.contours.sort_contours. Next we iterate through contours and find the centroid to obtain the (cX, cY) coordinates. The idea is that we can compare the cY value of each cell to determine if it is a new row or a cell in the same row by using a offset. A cell should be in the same row if the cY value is +/- some offset value. If it is greater then it means the cell is in a new row. We build a model table where the length of the table gives you the rows while the length of any index gives you the number of columns.

Binary image

Removed text contours + inverted image

Here's a visualization of iterating through each cell to count the number of rows and columns

Result
Rows: 7
Columns: 4

Code
import numpy as np
from imutils import contours
import cv2

# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find contours and remove text inside cells
cnts = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    if area < 4000:
        cv2.drawContours(thresh, [c], -1, 0, -1)

# Invert image
invert = 255 - thresh
offset, old_cY, first = 10, 0, True
visualize = cv2.cvtColor(invert, cv2.COLOR_GRAY2BGR)

# Find contours, sort from top-to-bottom and then sum up column/rows
cnts = cv2.findContours(invert, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
(cnts, _) = contours.sort_contours(cnts, method="top-to-bottom")
for c in cnts:
    # Find centroid
    M = cv2.moments(c)
    cX = int(M["m10"] / M["m00"])
    cY = int(M["m01"] / M["m00"])

    # New row
    if (abs(cY) - abs(old_cY)) > offset:
        if first:
            row, table = [], []
            first = False
        old_cY = cY
        table.append(row)
        row = []

    # Cell in same row
    if ((abs(cY) - abs(old_cY)) <= offset) or first:
        row.append(1)

    # Uncomment to visualize
    '''
    cv2.circle(visualize, (cX, cY), 10, (36, 255, 12), -1)
    cv2.imshow('visualize', visualize)
    cv2.waitKey(200)
    '''

print('Rows: {}'.format(len(table)))
print('Columns: {}'.format(len(table[1])))

cv2.imshow('invert', invert)
cv2.imshow('thresh', thresh)
cv2.waitKey()

A: Seems like an easy solution would be to first look left to right and check if each pixel is black (which would indicate that we have found a column. Then do the same for rows (if from top to bottom each pixel is black, it means it has found a row).
One complication is the width of the line which means you will count it as only 1 row/column found until it finds white color.
I could work out the code for this but I'm not at home right now, so maybe someone else can write the code and I will delete my answer later. I know this could be a comment but I don't have 50 reputation.

A: One other approach is first to verify if its a real table or not, For that hough's line transform can be used, once it is done you can use the approach explained above by fellow.


text:
Q: Is it possible to start a thread in Java from the object in its argument? is it possible to do something like this in Java? I'm just wondering.
First, I just create a new thread that has one argument.
Thread thread = new Thread(new Person());

Then, in the constructor of Person() I would like to start that thread.
So is something like this possible?
public Person() {
    // Here belongs some code for the constructor and then
    // I would like to start the thread
}

A: No, you can't. Before Java can call Thread() constructor it first has to eagerly evaluate all arguments, including call to Person() constructor. This means that by the time Person constructor is called, the outer Thread object doesn't even exist or was not yet initialized so you cannot really use it.

A: No.
You do not have the reference to the thread inside Person constructor. So, the thread still does not exist.
Even if you had it, doing something like
 public Person() {
   Thread a = new MyThread(this);
 }

is bad practice, because you are passing an instance (this) that might not have been fully initialized.

A: Is this what you are looking for? Note the use of {start()} which avoids all of the issues with calling start in the constructor.
  new Thread() {
    { start(); }
    public void run() {
     ...
    }
  };

You can see the original here.


text:
Q: Problem with importing configurable products, associated products not shows up I have the problem, that the "Associated Products" not shows up under the configurabel product.
We are using Magento 1.9.1, I did the import over Import, then choose the file.
Here is the file, maybe we forgot to add something:
sku,store,attribute_set,config_attributes,type,category_id,root_category,product_websites,apparel_size,brand_name,color,configurable_products,cost,country_of_manufacture,created_at,custom_design,custom_design_from,custom_design_to,custom_layout_update,description,disable_amazonpayments,featured,gallery,gift_message_available,has_options,image,image_label,manufacturer,media_gallery,meta_description,meta_keyword,meta_title,minimal_price,msrp,msrp_display_actual_price_type,msrp_enabled,name,news_from_date,news_to_date,options_container,page_layout,price,required_options,short_description,size,small_image,small_image_label,special_from_date,special_price,special_to_date,status,tax_class_id,thumbnail,thumbnail_label,updated_at,url_key,url_path,visibility,weight,qty,min_qty,use_config_min_qty,is_qty_decimal,backorders,use_config_backorders,min_sale_qty,use_config_min_sale_qty,max_sale_qty,use_config_max_sale_qty,is_in_stock,notify_stock_qty,use_config_notify_stock_qty,manage_stock,use_config_manage_stock,stock_status_changed_auto,use_config_qty_increments,qty_increments,use_config_enable_qty_inc,enable_qty_increments,is_decimal_divided,_links_related_sku,_links_related_position,_links_crosssell_sku,_links_crosssell_position,_links_upsell_sku,_links_upsell_position,_associated_sku,_associated_default_qty,_associated_position,_tier_price_website,_tier_price_customer_group,_tier_price_qty,_tier_price_price,_group_price_website,_group_price_customer_group,_group_price_price,_media_attribute_id,_media_image,_media_lable,_media_position,_media_is_disabled,_super_products_sku,_super_attribute_code,_super_attribute_option,_super_attribute_price_corr
VX-313011,,Apparel-attribute-set,color,configurable,13/124,Default Category,base,One size,Victorinox,,"VX-313011-01-OS,VX-313011-03-OS,VX-313011-01-OS",,,4/8/2015 23:09,,,,,"With organization for any agenda, this slimline case has protective compartments for both a laptop and an iPad or Kindle
",No,No,,,1,,,,,,,,,,Use config,Use config,Victorinox WT Shopping Tote,,,Product Info Column,,169.99,1,"Interior organization includes a 15.6" (40 cm) laptop compartment, 10" / 25 cm portable electronic device pocket and two mesh peripherals pockets",,,,,,,1,0,,,8/4/2015 19:35,victorinox-303337-werks-professional-advisor,victorinox-303337-werks-professional-advisor.html,1,,0,0,1,0,0,1,1,1,0,1,1,,1,1,0,0,1,0,1,0,0,,,,,,,,,,,,,,,,,88,/1/1/119190.jpg,,1,0,,,,
VX-313011-01-OS,,Apparel-attribute-set,color,simple,13/124,,base,,Victorinox,Black,,,,4/8/2015 23:09,,,,,"With organization for any agenda, this slimline case has protective compartments for both a laptop and an iPad or Kindle
",No,No,,,0,,,,,,,,,,Use config,Use config,"Victorinox WT Shopping Tote, black",,,Product Info Column,,169.99,0,"Interior organization includes a 15.6" (40 cm) laptop compartment, 10" / 25 cm portable electronic device pocket and two mesh peripherals pockets",,,,,,,1,0,,,8/4/2015 19:35,victorinox-303337-werks-professional-advisor-black,victorinox-303337-werks-professional-advisor-black.html,1,2,10,0,1,0,0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,,,,,,,,,,,,,,,,,,,,,,,,,
VX-313011-03-OS,,Apparel-attribute-set,color,simple,13/124,,base,,Victorinox,Grey,,,,4/8/2015 23:09,,,,,"With organization for any agenda, this slimline case has protective compartments for both a laptop and an iPad or Kindle
",No,No,,,0,,,,,,,,,,Use config,Use config,"Victorinox WT Shopping Tote, grey",,,Product Info Column,,169.99,0,"Interior organization includes a 15.6" (40 cm) laptop compartment, 10" / 25 cm portable electronic device pocket and two mesh peripherals pockets",,,,,,,1,0,,,8/4/2015 19:35,victorinox-303337-werks-professional-advisor-olive,victorinox-303337-werks-professional-advisor-olive.html,1,2,10,0,1,0,0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,,,,,,,,,,,,,,,,,,,,,,,,,
VX-313011-06-OS,,Apparel-attribute-set,color,simple,13/124,,base,,Victorinox,Olive,,,,4/8/2015 23:09,,,,,"With organization for any agenda, this slimline case has protective compartments for both a laptop and an iPad or Kindle
",No,No,,,0,,,,,,,,,,Use config,Use config,"Victorinox WT Shopping Tote, olive",,,Product Info Column,,169.99,0,"Interior organization includes a 15.6" (40 cm) laptop compartment, 10" / 25 cm portable electronic device pocket and two mesh peripherals pockets",,,,,,,1,0,,,8/4/2015 19:35,victorinox-303337-werks-professional-advisor-olive,victorinox-303337-werks-professional-advisor-olive.html,1,2,10,0,1,0,0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,,,,,,,,,,,,,,,,,,,,,,,,,


text:
Q: ROR equivalent of Phoenix Mix? Mix command usage looks very similar to rails command.
Are they the same, what are the differences & similarities?

A: mix is the equivalent of several Ruby tools in one. rake is the task runner for Ruby (similar to gulp, grunt, make, etc. in other languages). You generally us it for things like running tests and builds. bundler is the idiomatic dependency management tool for Ruby. It downloads your dependencies and locks them for your project. bundle gem is commonly used for bootstrapping projects (like mix new I think)
Phoenix also integrates with mix and provides tools for starting your server (like rails s) and generating components (like rails generate). One that's a little weird is how you start up a debug shell (iex -S mix phoenix.server vs. rails c). The Elixir approach here requires you to start a server while rails doesn't (there's probably a way to do it without a server in Elixir, but I haven't figured it out yet)
In general Elixir seems to take the best ideas from a lot of popular Ruby libraries and gives them first-class support in the standard library for Elixir
I'd be happy to go into more detail about specific commands or features if you have questions about them


text:
Q: Adjoint Matrix with given Matrix Given matrix $$A =\begin{bmatrix}1 & 2 & 5& 4\\0&-1&-2&-1\\ -1&1&3&0\\0&2&5&3\end{bmatrix}$$
Find matrix $B$ such that $A = adj(B)$.

A:
Notice that the adjugate matrix of matrix $B: 4 \times 4$ is defined such that $$B  A = \left( \frac{1}{\det B} \right)I_4.$$

Now, $A = \text{adj}(B)$ is given by $$A =\begin{pmatrix}1 & 2 & 5& 4\\0&-1&-2&-1\\ -1&1&3&0\\0&2&5&3\end{pmatrix}, $$ with $\det (A) = -1$ hence it is invertible. This gives $$B = \left( \frac{1}{\det B} \right) A^{-1}.$$ Since $\det (A^{-1}) = \frac{1}{\det A} = -1,$ choosing $B = -A^{-1}$ works, because $$BA = (-A^{-1}A) = \frac{1}{\det (-A^{-1})} I_4.$$


text:
Q: Problems with Camera in networking with Unreal engine 4 I am currently working on a project where all my players use different Camera.
I first thought using UCameraComponent, but each camera has to turn around a certain point and not moving with the movement of the pawns.
So I decided to Spawn a Camera Actor in the BeginPlay() of my pawn.
void AMyCharacter::BeginPlay()
{
Super::BeginPlay();
if (!hasCamera) { // Camera not set yet
    FVector vectpos; // Target position of the camera
    vectpos.X = -1130;
    vectpos.Y = 10;
    vectpos.Z = 565;
    FRotator rotation;
    rotation.Pitch = -22;
    rotation.Yaw = 0;
    rotation.Roll = 0;

    APlayerController* controller = Cast<APlayerController>(GetController());

    if (controller == NULL) // When I'm on client, the GetController() return NULL.
    {
    // Trying to find the controller of my client
        for (FConstPlayerControllerIterator Iterator = GetWorld()->GetPlayerControllerIterator(); Iterator; ++Iterator)
        {
            controller = *Iterator;
            //On client, there is only 1 controller according to the documentation.
        }
    }

    if (controller != NULL)
    {
        controller->SetViewTarget(Camera); // Set the view with the new camera
    }
    SetCamera(true); // Call and RPC Function to update the hasCamera variable
}
}

This is working for the first player, and after that it depends. Sometimes, the second player get a camera that works fine, but sometimes, he is viewing through the wrong camera and the Camera variable is not the same one he is looking in. Sometimes, when a new players join the game, it make the first/second player looking through the wrong camera.
Here is the GameInstance Blueprint we use to make the LAN Connection bewteen the clients and the server(the first client to create the game)

If someone can find why the camera is not working as expected , it would be very nice ! Thanks you all in advance for your help.

A: Apparently, You choose the wrong way.
In UE4 'ACharacter' (APawn to be precise) is a character representation in the world, so you will have one for every single player. Thus, it is strange to put your camera code in it.
You should make your own controller (ex. 'AMyPlayerController') and control camera from it. Obviously, only for a local player.


text:
Q: Input files with names which use MakeUppercase I have this simple document:
\documentclass{article}

\newcommand{\inputFile}[2]
{%
    \input{"\MakeUppercase{#1} - \MakeUppercase{#2}"}%
}

\begin{document}
%
\inputFile{a}{b}
%
\end{document}

When I compile it, the error will be:
! Illegal parameter number in definition of \@filef@und.
My files contain spaces in their names (that's why I wrapped the file name in ""). I tried to do something with \@@input, but it didn't work well with files with spaces in their names. How could I deal with this please?

A: Converting to uppercase with \MakeUppercase or \uppercase is not compatible
with the expandable context needed for a file name for \input.
There are several workarounds:
If the simpler \uppercase can be used:
\uppercase{\input{"#1 - #2"}}

With \MakeUppercase:
\MakeUppercase{\protect\input{"#1 - #2"}}

Macro \protect prevents that \input is executed too early. \MakeUppercase expands the argument before converting to uppercase. Also, it puts the argument in a group. If this is not wanted, a global macro can be defined instead and later used as file name argument in \input.
\MakeUppercase{\gdef\noexpand\gtemp{"#1 - #2"}}\input{\gtemp}

A: Assuming that A - B.tex contains
hylo

then
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\cs_new_protected_nopar:Nn \patrik_inputfile:nn
{
  \tl_set:Nn \l_tmpa_tl  { \text_uppercase:n { #1 ~ - ~ #2 } }
  \file_input:V \l_tmpa_tl
}
\NewDocumentCommand \inputFile { m m }
{
  \group_begin:
  \patrik_inputfile:nn { #1 } { #2 }
  \group_end:
}
\cs_generate_variant:Nn \file_input:n { V }
\ExplSyntaxOff
\begin{document}
\inputFile{a}{b}
\end{document}

will generate a document saying 'hylo'.


text:
Q: Examples and references of connections on elliptic curves In studying connections on vector bundles, I am trying to find non trivial examples of connections over an elliptic curve, over $\Bbb P^1_k$ and $\Bbb A^1_k$ for a field $k$.
By a connection on a vector bundle $E$ on a scheme $X$, I mean a morphism $\nabla :E \mapsto E\otimes \Omega^1$ such that $\forall f,e \in \mathcal O_X\times E: \nabla(fe) = f \nabla(e) + df \otimes e$.
Thank you for your help, answers and references.


text:
Q: Deregistering Jscripts / CSS From Wordpress Plugins Im not sure if this is an issue with Wordpress 3.0 and changes to function names but as far as I can tell this should remove the jscripts and css from the headers sitewide
add_action('wp_print_scripts','my_deregister_javascript', 100);
function my_deregister_javascript(){
    wp_deregister_script('ngg_script');
    wp_deregister_script('thickbox');

}
add_action('wp_print_styles','my_deregister_styles', 100);
function my_deregister_styles(){
    wp_deregister_style('NextGEN');
    wp_deregister_style('thickbox');

}

A: My fault I was calling the action before hte function


text:
Q: what does context mean with respect to a web-container / a web application? what does context mean with respect to a web-container / a web application ?
what does Context cont = new InitialContext() initialize ?

A:
what does context mean with respect to a web-container / a webapplication ?

Usually a context will specify object mappings that are specific to your environment -- You may have a production context refer to a different jdbc configuration than a test context

what does Context cont = new InitialContext() initialize?

This will initialize an empty environment


text:
Q: Lightbox effect in wordpress i have to add a pop up for images that i have in a gallery page.I've a custom post type called mgallery and i am using gallery-template like this
   <?php
            $args=array('post_type' => 'mygallery');
            $query= new WP_Query($args);
            while ($query-> have_posts() ) : $query->the_post()?>

<a href="<?php echo get_post_permalink() ?>"><?php the_title();?>

              <?php the_post_thumbnail( 'full', array( 'class' => 'product_img') );?>

   <?php
        endwhile;
    ?>

now the plugins i try to use they offer to add lightbox effect in pages how do i add this in a page that is getting   data from  page-template please help

A: First get Lightbox, put it in your js folder and enqueue it
wp_enqueue_script('lightbox', get_template_directory_uri().'/js/lightbox.js', array());

Then in your gallery template try putting this:
<?php
    $args=array('post_type' => 'mygallery');
    $query= new WP_Query($args);
    while ($query-> have_posts() ) : $query->the_post()?>
    <?php
        $thumbnail_id = get_post_thumbnail_id(get_the_ID());
        $thumbnail_object = get_post($thumbnail_id);
        $url = wp_get_attachment_url( $thumbnail_id );
    ?>

<a href="<?php echo get_post_permalink() ?>"><?php the_title();?>

                <a data-lightbox="image" data-title="<?php the_title();?>" href="<?php echo esc_url($url);?>"><?php the_post_thumbnail( 'full', array( 'class' => 'product_img') );?>

   <?php
       endwhile;
   ?>

Let me know if you have any errors. And be sure you don't have any jquery conflicts if you have other lightbox plugins.


text:
Q: Mean number of customers in a $M/M/\infty$ queue I had a bit of trouble deriving the following statement:
Setting: Consider an $M/M/\infty$ queue and a Poisson arrival process with rate $\lambda$ and exponential service time with rate $\mu$. Suppose that the arrival process starts in the distinct past and ends at time $t = 0$, i.e. the arrival rate is defined as
$$
\begin{cases}
\lambda(t) = \lambda & t \in (\infty, 0]\\
\lambda(t) = 0 & t \geq 0
\end{cases}
$$
where $\lambda > 0$ is a constant.
Question: Let $m(\tau)$ be the mean number of customers in the system at time $\tau$. Verify that $m(0) = \frac{\lambda}{\mu}$ and $m(\tau) = \frac{\lambda}{\mu}e^{-\mu t}$.
My problem: In the solutions to this exercise they first state that
$$
m(0) = \int_{-\infty}^{0} \lambda e^{-\mu(- t)} dt
$$
I think this definitely makes sense, but I have trouble actually convincing myself that this is formally the case. I understand that expected number of customers that arrive between $t = -\infty$ and $t = \tau$ should be $\int_{-\infty}^{\tau} \lambda(t) dt$, since that is what it means to be rate.
From here I intuitively understand that we want to "discount" the amount of people in the system at every time by some factor so to get the actual number that are left in the system. It makes sense that this factor should be the exponential, but I do not exactly see how to formally arise to the exact expression: $m(\tau) = \int_{\infty}^{0} \lambda e^{-\mu(\tau - t)} dt$. I have tried multiple times to formally derive this myself, but unfortunately I couldn't figure it out. Could someone else help me? Thanks in advance! :)


text:
Q: How to check if an item is already there in an array let us consider an array
let array=["a","b","c","d","a"]

a is already present in the array, how to return true/false for this condition.
i don't want to do this
let value=array.includes("a")

in this case i know a is repeated so i use includes("a"). How to write a generic solution to find if an item is repeated in an array .(imagine getting an array from an api, so u wont know what will be repeated )

A: Well you can use the .indexOf and .lastIndexOf to do that, so the idea is if both return the same index of the item then it's not repeated and it's unique but if the index is different then there are at least two copies of the item, so we can write a small function to do that given the array to search in and the item to search for

var x = [1, 6, 4, 6, 3, 2, 1];
function isRepeated(arr, n) {
  return arr.indexOf(n) !== arr.lastIndexOf(n);
}
console.log("1 is repeated? " + isRepeated(x, 1));
console.log("3 is repeated? " + isRepeated(x, 3));
console.log("6 is repeated? " + isRepeated(x, 6));
console.log("4 is repeated? " + isRepeated(x, 4));


text:
Q: (C#) Can I access a struct's members by name or index? Is it possible to access a struct's public members by their names / indices?
For example, if I have:
struct Person
{
  int id;
  string surname;
}

Person person;

Is it possible to get person.id with just the string "id" or the integer index 0?
Or to get person.surname with the string "surname" or the integer index 1?

A: You can use reflection to get member by name (in this case field):
var p = new Person();
var fieldInfo = p.GetType().GetField("id", BindingFlags.NonPublic | BindingFlags.Instance);
Console.WriteLine(fieldInfo.GetValue(p)); // prints 0


text:
Q: How to get min date and max date if results remain unchanged I have an address SCD type 2 table but sometimes information entered remain the same I want to write a query that if information is unchanged, retain the previous begin data and set end date to max e.g

OBJID          BEGDA      ENDDA     HASHROW_COL RK
83022088    2012-03-30  2012-10-28  e1-ef-a9-36 1
83022088    2012-10-29  2013-09-07  63-69-e5-25 2
83022088    2013-09-08  2014-08-30  e1-ef-a9-36 3
83022088    2014-08-31  2016-11-26  e1-ef-a9-36 4
83022088    2016-11-27  9999-12-31  e1-ef-a9-36 5

Notice that from rows 3 – 5 the HASHROW_COL remain the same.

Desired result:
OBJID          BEGDA       ENDDA    HASHROW_COL RK
83022088    2012-03-30  2012-10-28  e1-ef-a9-36 1
83022088    2012-10-29  2013-09-07  63-69-e5-25 2
83022088    2013-09-08  9999-12-31  e1-ef-a9-36 3

Query so far
select a.objid, a.hashrow_col,
case when a.objid <> b.objid then b.begda
    when a.hashrow_col = b.hashrow_col and (b.begda - interval '1' day <= a.endda) then
    a.begda  end,
case when a.objid <> b.objid then b.endda
    when (a.hashrow_col = b.hashrow_col) and (b.begda - interval '1' day <= a.endda) and b.endda > a.endda
    then b.endda
    end,
from
(select objid, begda, endda, HASHROW_COL,
from OTABLE )  a
inner join
(select objid, begda, endda, HASHROW_COL,
from OTABLE) b
on
a.objid = b.objid
where
and a.objid = '83022088'
order by a.OBJID, a.BEGDA,  a.HASHROW_COL;

A: This is a gaps-and-islands problem.  In this case, I would use:
select objid, min(begda), max(endda), HASHROW_COL,
       row_number() over (partition by objid order by min(begda)) as ranking
from (select t.*,
             sum(case when prev_endda = begda - interval '1' day then 0 else 1 end) over (partition by objid order by begda) as grouping
      from (select t.*,
                   lag(endda) over (partition by objid, HASHROW_COL order by begda) as prev_endda
            from t
           ) t
      ) t
group by grouping, objid, HASHROW_COL;

A: Assuming that the hashrow_col is the value which remains the same,(ie you got the values you need to group by) then all you would need is the min(begda) and max(endda)
select objid, min(begda) as begda, max(endda) as enddat, HASHROW_COL,
       min(rnk)
  from OTABLE
group by objid,hashrow_col

A: Here's a solution using the NORMALIZE function and the period data type.
We have to convert your start and end dates to a period.  One gotcha with normalize to work is that consecutive end and start dates must overlap, that's why I've added 1 day to the end date (unless it's 9999-12-31').
select normalize on meets or overlaps objid,hashrow_col,duration from (
select
t.*,
period(begda, case when endda = '9999-12-31' then endda else endda +interval '1' DAY end) as duration
from
<your table> t) tt

Normalize and period are extremely powerful in the right circumstances.


text:
Q: select and run a java class or call a method in a class using JFileChooser on an other class (GUI) I have a file A.java containing a class A with a method aMethod() that is saved on a folder on the PC (not inside the package or workspace).
I have a JFileChooser on another class (GUI).
I want to be able to select class A and run it, or call A::aMethod() using the JFileChooser.
Is this possible?

A: You need to load class A into a custom class load so you can execute it.
There are a number of issues involved with this.  The first revolves around package names, the second revolves around actually calling the classes methods.
The following example basically uses a URLClassLoader to point to a directory of classes, these classes are layout our in there correct package structure.  The essentially provides the custom class loader with it's class path
try {
    URLClassLoader classLoader = new URLClassLoader(new URL[] {new File("path/to/classes/").toURI().toURL()});
    Class<?> loadClass = classLoader.loadClass("dynamicclasses.TestClass");
    Object newInstance = loadClass.newInstance();
    System.out.println(newInstance);
} catch (Exception ex) {
    ex.printStackTrace();
}

The example also relies on the loaded classes toString method to return a result.  In my test, I simply dumped the classes class loader reference.
The second problem is a little more difficult to overcome.  You have two basic chooses.

*

*You can define a common interface which is available to both the current runtime and the dynamically loaded class.  This allows you to cast the loaded class to some known interface which provides you with the ability to call the loaded classes methods (as you have established a contract between the two)

*Use reflection to call the methods on the loaded class.

I prefer the first option, but it does mean if you change the interface, you need to compile both sides again.

A: So I have made some progress. Not where I want to be but it's good...
My GUI has a button that does the following:
btnButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            runFAQm();
        }
    });

the method called in the GUI when the button is clicked is runFAQm(). Method runFAQm() uses Runtime to run a java file that is saved in an other directory.
public static void runFAQm(){
try {
                String[] cmdArray = new String[2];
                // first argument is the program we want to open
                cmdArray[0] = "java";
                // second argument is a txt file we want to open with notepad
                cmdArray[1] = "FAQm";
                // print a message
                // create a file which contains the directory of the file needed
                File dir = new File(
                        "c:/Documents and Settings/AESENG/My Documents/MK/Selenium_Practice/workspace/TestCDM/src");
                // create a process and execute cmdArray and currect environment
                Process p = Runtime.getRuntime().exec(cmdArray, null, dir);
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        p.getInputStream()));
                String line = null;
                while ((line = in.readLine()) != null) {
                    System.out.println(line);
                    textArea.append(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

The java file (called FAQm.java) that is run via the runtime() inside the runFAQm() method, starts a Firefox browser. Of course I have sun Javac.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import static org.junit.Assert.*;
import org.openqa.selenium.*;

public class FAQm {
static WebDriver driver = new FirefoxDriver();

public static void main(String[] args) throws Exception {
    System.out.print("inside FAQm main" );
}

My problem now is that I can run Class FAQm from command line, and from eclipse, but it hangs when i run it from GUI by clicking on button. It hangs only when the Webdriver is initiated. If i comment out //static WebDriver driver = new FirefoxDriver(); the program runs fine.


text:
Q: The jar of this class file belongs to container 'RFT Libraries' I get this error when I try to integrate Selenium web driver with IBM RFT.

The jar of this class file belongs to container 'RFT Libraries' which does not allow modifications to source attachment'

How do i overcome this issue? Can some one shed some light on it?


text:
Q: Do the entries in .gitignore get applied to the SVN repository when using git-svn? If I tell git to ignore x amount of files and never add them to the repository, will those files also make it into the svn:ignore property? And if so, how can I keep .gitignore local to only my local git repository?
EDIT Sorry about the duplicate, I searched on here and couldn't find anything on it.

A: No, git will not do anything with svn:ignore.
From the documentation:

We ignore all SVN properties except svn:executable. Any unhandled properties are logged to $GIT_DIR/svn//unhandled.log

Also this other StackOverflow question is very similar.

A: If you want the .gitignore local to your repo, don't commit it.
Similar question:
How can you indicate files to ignore in svn when using git and the git-svn bridge

A: git-svn does neither .gitignore — svn:ignore, nor git attributes — svn properties conversion.
You may consider using SubGit instead. It does properly handle ignore, properties, merge-tracking data, etc. Among other things it works on a server-side, so one can use any Git client available to send changes to Subversion repository.
See documentation and comparison with git-svn.


text:
Q: Printing a portion of a page using JavaScript I am printing a page by the printer, using JS function print(window.print()). But, it prints the whole page, including the "Print" button, which looks odd. I want to print the page without that button. May be printing the page-wrapper div would be good. What should I do ?
Thanks.

A: You can customize your page's "printed" display, by using a print-specific stylesheet, imported like this:
<link rel="stylesheet" type="text/css" media="print" href="print.css" />

In that stylesheet, you could remove elements you don't want to show in on the printed page:
.printButton{
    display: none;
}

Or, if you're not concerned about IE 8 compatibility, something like this might work:
:not(.page-wrapper div){
    display:none;
}

For more information, "A List Apart" has a nice tutorial on the subject


text:
Q: Unit + nilpotent = a unit Would this proof work?
Let $N$ be a nilpotent in a commutative ring and let $X$ be a unit.
Let $Y$ be an element in the ring.
Proof by contradiction:
Assume
$$Y(X+N) \neq 1$$
Then
$$YX + YN \neq 1 $$
Then
$$YXN^{n-1} \neq N^{n-1} $$
A contradiction since since $Y$ can be the inverse of $X$ and thus the equation can hold above.

A: $u$ unit, $n$ nilpotent, $u+n=u(1+u^{-1}n)$, suppose $n^m=0$, $(u^{-1}n)^m=0$, so $n'=u^{-1}n$ is nilpotent $(1+n')(1+\sum_{i=1}^{i=m-1}(-1)^i{n'}^i)=1+(-1)^{m-1}{n'}^m)=1$, so $1+n'$ is invertible and $u+n=u(1+n')$ is invertible since it is the product of two invertible elements.

A: I'll write out how I understand your reasoning, and then point out the mistake.
Let R be a ring, $u$ be a unit, $n$ nilpotent, with $n^k=0$. Suppose, that $y(u+n)\neq1\forall y\in R$. Then $y(u+n)n^{k-1}\neq n^{k-1} \forall y\in R$. A contradiction since $u$ is unit.
The problem with the above, is that you assume $a\neq b \Rightarrow ac\neq bc$, which is wrong. For example in $\mathbb Z/4\mathbb Z$ we have $1\neq3$, but $1\times2=3\times2$.
Here is an easy direct way. If $u$ is unit, $n$ nilpotent, with $uv=1, n^k = 0$, then it is easy to see that $v+\sum_{i=1}^{k-1}(-1)^i(uv)^i$ is the inverse of $u+n$.


text:
Q: Boost Geometry/Spatial Query Shapes I am currently using the boost geometry/spatial index library, in order to perform range queries on 3d bounding boxes. For example I am able to get a list of all bounding boxes, that overlap a query bounding box.
The documentation (http://www.boost.org/doc/libs/1_54_0_beta1/libs/geometry/doc/html/geometry/spatial_indexes/queries.html) shows, that -- at least in 2d -- polygons can be used instead of the bounding box as a query object. Is it possible to use more advanced query shapes in 3d as well? I am thinking of objects like oriented bounding boxes, pyramids, or camera frustums. If so: how can I do that/where can I find an example for that?
Thanks

A: In short: it's not supported because for now in Boost.Geometry OOB, Pyramid and Frustum concepts are not available/supported.
But, theoretically it should be possible to perform such a query. During the query, the bgi::rtree calls adequate boolean algorithm defined in the boost::geometry namespace, e.g. if you call
rtree.query(bgi::intersects(my_geometry), out_it);

internally
bg::intersects(xxx, my_geometry);

is called, where xxx is node's bounding box or value's indexable (geometry extracted from ValueType passed by the user into the bgi::rtree, e.g. also a box or a point). So if you implemented e.g.
namespace boost { namespace geometry {

template <typename Box> inline
bool intersects(Box const& b, MyFrustum const& f)
{
    // your implementation
}

}}

theoretically it should work. Didn't tested it though.
Above:
namespace bg = boost::geometry;
namespace bgi = boost::geometry::index;

Also if you'd like to contact the developers directly you might consider subscribing to the Boost.Geometry mailing list: http://lists.boost.org/mailman/listinfo.cgi/geometry

A: I had the same problems and after chatting with @Adam he proposed the following solution which fixed the issue for me (I'm building my code on GCC and the solution above seems to compile only on Visual Studio).
#include <boost/geometry.hpp>

struct MyFrustum
{
    MyFrustum(int d) : dummy(d) {}
    int dummy;
};

namespace boost { namespace geometry {

// This will be called for Nodes and Values!

template <typename Box> inline
bool intersects(Box const& b, MyFrustum const& f)
{
    std::cout << "checking the intersection with " << f.dummy << std::endl;
    return true;
}

}}

#include <boost/geometry/index/rtree.hpp>

Apparently the order in which things are defined is important so that the compiler does not fallback to its default implementation (which produces not-yet-implemented errors).
Hope that helps, and again, thanks to Adam!

A: The other answers here are great, but I still encountered trouble in Xcode, no matter what order I included/declared things. I am posting this answer for others who can't get this to work in their environment.
The other solution(s) here worked fine for me in Visual Studio 2013, but not in Xcode 5.1.1. There appears to be an overload resolution issue in that compiler. The solution is to avoid using a template type for "Box" and use all the concrete types directly, like this:
#include <boost/geometry.hpp>

namespace bg = boost::geometry;
using point3d = bg::model::point<float, 3, bg::cs::cartesian>;
using box3d = bg::model::box<point3d>;

namespace boost { namespace geometry {

    template <> inline
    bool intersects(box3d const& b, MyFrustum const& p) {
        // your implementation
        return true;
    }
}


text: Q: Concept of Flux Linkage in solving Faraday's Law Problems I understand that the definition of flux linkage as kind of the sum of all the fluxes going through the surfaces bound by all the turns. That is, $\Lambda = N \Phi $. However what I don't understand is what happens if the coils are not uniformly stacked up on top of each other like a solenoid. For example, take the example of a sphere with N turns of wire wrapped around it to create some sort of spherical solenoid and run a time varying magnetic field through it. In this case, there should be a voltage induced however I don't understand how to employ the concept of flux linkage to calculate that here because $\Lambda \neq N \Phi$ as every loop of wire links a different amount of flux to the current. If anybody could help me understand how to use linkage here to solve for induced voltage or self inductance that would be great.