Q:

Почему команда push не создает файлы на удаленном сервере?

Есть репозиторий на локальной машине и на удаленном сервере, pull и push выполняются без проблем и ошибок, собственно в чем проблема:
На локальной машине: создаю файл, коммит на его основе, заливаю на сервер:
touch test.html
git add test.html
git commit -m'added test.html'
git push

На сервере: коммит получен, файла нет.
git log

(показывает, что последний коммит получен)

ls -A

.git

Почему команда git push не создает файлы на удаленном сервере?

A:

Как правило, удаленный репозиторий является bare («голым»). Такой репозиторий используется только для хранения файлов Git и организации работы группы пользователей. Предполагается, что никто не будет создавать коммиты непосредственно на bare-репозитории. Это повышает надежность и экономит дисковое пространство.
Если вы хотите делать развертывание через Git, то это возможно через git-hooks: Настройка и развертывание проекта c помощью Git
Но это плохая практика. (В том же вопросе объясняется, почему). Лучше использовать автоматизированные системы развертывания.


Q:

layout_span in TableLayout in Android

I would like to create a login screen for an android application. I'm using TableLayout to get the correct alignment. So two rows consist of a TextView and an EditText and I would like to add a Button below them that width is stretched to the screen. So I put the Button in another TableRow and I added layout_span="2" for the Button, but the Button is displayed in the first column.
I think this should be correct, but I must do something wrong in the xml file. Do you have an idea what is wrong?
<TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".LoginActivity"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="5dp"
            android:paddingRight="15dp"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="@string/evUsername" />
        <EditText
            android:id="@+id/username"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="text" />
    </TableRow>
    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="5dp"
            android:paddingRight="15dp"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="@string/evPassword" />
        <EditText
            android:id="@+id/password"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="textPassword" />
    </TableRow>
    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <Button
            android:id="@+id/btnLogin"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_span="2"
            android:text="@string/btnLogin" />
    </TableRow>
</TableLayout>

Thanks in advance!

A:

At the end I wrapped my TableLayout in a LinearLayout and I added the Button after the TableLayout.
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".LoginActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="5dp"
                android:paddingRight="15dp"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="@string/evUsername" />
            <EditText
                android:id="@+id/username"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:inputType="text" />
        </TableRow>
        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="5dp"
                android:paddingRight="15dp"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:text="@string/evPassword" />
            <EditText
                android:id="@+id/password"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:inputType="textPassword" />
        </TableRow>
    </TableLayout>
    <Button
        android:id="@+id/btnLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/btnLogin" />
</LinearLayout>

A:

In your original xml file, you can simply add
android:layout_weight="1"
in your button


Q:

Strange Bounds Error with Visual Studio C++

I'm working in Visual Studio for a class project. Since I can no longer tell if I'm going crazy or not, this code runs and immediately results in an 'index out of bounds' error. There's no way that should happen in my mind.
int _tmain(int argc, _TCHAR* argv[]){
    vector<int> points;
    for(int i = 0; i < points.size() - 1; i++){
        points[i+1] = 2;
    return 0;
}

There are no values in the vector so the size comes back as 0 and we're checking then if i < -1. Is 0 < -1? No, it's not so the loop never runs and the program should return.
The exact warning I get is this:

I am compiling for debug mode so I guess my question is, first, am I missing something? If not, is this some kind of weird Visual Studio Debug feature?

A:

Here is the expression that causes the problem:
i < points.size() - 1

when you subtract 1 from an unsigned value of zero (points.size() is size_t, which is unsigned) you get a very large number. Switch to this condition to fix the problem:
i + 1 < points.size()

It is identical mathematically, but it will not produce a numeric overflow unless i is at the max value of int.


Q:

How do you specify the origin of the arrow on a popover segue with OS X 10.10 storyboards

I'm playing around with storyboarding in an OS X 10.10 app.  I have an NSTableView that, when you click a specific row opens a segue that goes to a popover that contains an NSViewController.
How do you specify the origin NSPoint of the arrow for the popover?  Right now, it just points to the NSTableView in the middle.  I assumed that I could do this in prepareForSegue, but I can't seem to figure it out.  prepareForSegue doesn't seem to have an understanding that the NSViewController is contained in an NSPopover
Any ideas?

A:

You should file an enhancement request Radar for this behavior if you think it should be provided by the framework in some way.

But to workaround this in the meantime, you can create your own custom NSStoryboardSegue subclass to help with this.
@interface TablePopoverSegue : NSStoryboardSegue

@property (weak) NSTableView *anchorTableView;
@property NSRectEdge preferredEdge;
@property NSPopoverBehavior popoverBehavior;

@end

@implementation TablePopoverSegue

- (void)perform {
    if ([self anchorTableView]) {
        NSInteger selectedColumn = [[self anchorTableView] selectedColumn];
        NSInteger selectedRow = [[self anchorTableView] selectedRow];

        // If we can pick a specific row to show from, do that; otherwise just fallback to showing from the tableView
        NSView *anchorView = [self anchorTableView];
        if (selectedRow >= 0) {
            anchorView = [[self anchorTableView] viewAtColumn:selectedColumn row:selectedRow makeIfNecessary:NO];
        }

        // Use the presentation API so that the popover can be dismissed using -dismissController:.
        [[self sourceController] presentViewController:[self destinationController] asPopoverRelativeToRect:[anchorView bounds] ofView:anchorView preferredEdge:[self preferredEdge] behavior:[self popoverBehavior]];
    }
}

@end

This can be specified in IB in the inspector panel for the segue (just like iOS):

And then in your source view controller's prepareForSegue:, you can just set up the segue:
- (void)prepareForSegue:(NSStoryboardSegue *)segue sender:(id)sender {
    if ([segue isKindOfClass:[TablePopoverSegue class]]) {
        TablePopoverSegue *popoverSegue = (TablePopoverSegue *)segue;
        popoverSegue.preferredEdge = NSMaxXEdge;
        popoverSegue.popoverBehavior = NSPopoverBehaviorTransient;
        popoverSegue.anchorTableView = [self tableView];
    }
}


Q:

Where is the libpcap library for QNX Neutrino?

I know QNX 6.6 has libpcap as part of its standard libraries.
When I link to libpcap.a and try to use the functions, I get "undefined reference to 'function_name'".
Where is the real libpcap library I need to get it to actually work? Is there someplace I need to download it from?

I am building from Momentics, so there is no single command to build.
Under Linker > other options I have -lpcap, and under Linker > extra libraries I have pcap.
A possibility is that I need to import additional libraries, but libpcap comes with hundreds and I have no idea which ones I would need.
As for output, I get some innoculous building messages followed by my project search path, followed by 18 of these about different functions:
U:/.../target/qnx6/x86/usr/lib\libpcap.a(fad-getad.o): In function pcap_findalldevs':
(.text+0x2b): undefined reference to `getifaddrs'

Some of which are in pcap.h and some aren't. This is the complete list:

'U:/shutchinson/QNX/target/qnx6/x86/usr/lib\libpcap.a(scanner.o): In function pcap_lex':
  (.text+0x9c8): undefined reference togetaddrinfo'
  U:/shutchinson/QNX/target/qnx6/x86/usr/lib\libpcap.a(inet.o): In function pcap_lookupnet':
  (.text+0x6d8): undefined reference tosocket'
  U:/shutchinson/QNX/target/qnx6/x86/usr/lib\libpcap.a(inet.o): In function pcap_lookupnet':
  (.text+0x744): undefined reference toioctl_socket'
  U:/shutchinson/QNX/target/qnx6/x86/usr/lib\libpcap.a(inet.o): In function pcap_lookupnet':
  (.text+0x7c8): undefined reference toioctl_socket'
  U:/shutchinson/QNX/target/qnx6/x86/usr/lib\libpcap.a(pcap-bpf.o): In function pcap_set_datalink_bpf':
  (.text+0x16): undefined reference toioctl_socket'
  U:/shutchinson/QNX/target/qnx6/x86/usr/lib\libpcap.a(pcap-bpf.o): In function pcap_stats_bpf':
  (.text+0x21a): undefined reference toioctl_socket'
  U:/shutchinson/QNX/target/qnx6/x86/usr/lib\libpcap.a(pcap-bpf.o): In function pcap_setdirection_bpf':
  (.text+0x3ef): undefined reference toioctl_socket'
  U:/shutchinson/QNX/target/qnx6/x86/usr/lib\libpcap.a(pcap-bpf.o):(.text+0x49d): more undefined references to ioctl_socket' follow
  U:/shutchinson/QNX/target/qnx6/x86/usr/lib\libpcap.a(fad-getad.o): In functionpcap_findalldevs':
  (.text+0x2b): undefined reference to getifaddrs'
  U:/shutchinson/QNX/target/qnx6/x86/usr/lib\libpcap.a(fad-getad.o): In functionpcap_findalldevs':
  (.text+0x175): undefined reference to freeifaddrs'
  U:/shutchinson/QNX/target/qnx6/x86/usr/lib\libpcap.a(gencode.o): In functiongen_mcode6':
  (.text+0x5777): undefined reference to freeaddrinfo'
  U:/shutchinson/QNX/target/qnx6/x86/usr/lib\libpcap.a(gencode.o): In functiongen_scode':
  (.text+0x5b36): undefined reference to freeaddrinfo'
  U:/shutchinson/QNX/target/qnx6/x86/usr/lib\libpcap.a(nametoaddr.o): In functionpcap_nametoaddr':
  (.text+0x2e): undefined reference to gethostbyname'
  U:/shutchinson/QNX/target/qnx6/x86/usr/lib\libpcap.a(nametoaddr.o): In functionpcap_nametoaddrinfo':
  (.text+0x93): undefined reference to getaddrinfo'
  U:/shutchinson/QNX/target/qnx6/x86/usr/lib\libpcap.a(nametoaddr.o): In functionpcap_nametonetaddr':
  (.text+0xc4): undefined reference to getnetbyname'
  U:/shutchinson/QNX/target/qnx6/x86/usr/lib\libpcap.a(nametoaddr.o): In functionpcap_nametoport':
  (.text+0xee): undefined reference to getservbyname'
  U:/shutchinson/QNX/target/qnx6/x86/usr/lib\libpcap.a(nametoaddr.o): In functionpcap_nametoport':
  (.text+0x10f): undefined reference to getservbyname'
  U:/shutchinson/QNX/target/qnx6/x86/usr/lib\libpcap.a(nametoaddr.o): In functionpcap_nametoproto':
  (.text+0x251): undefined reference to `getprotobyname'

A:

You must add another library (libsocket.a) to the linker options. I.e. your linker options must be.............. -lpcap -lsocket.


Q:

In JavaScript and knockout.js, why can't I return a variable? Why must I return the variable as if it's a method?

Consider this snippet of code:
function AppViewModel() {
    this.firstName = ko.observable("");
    this.lastName = ko.observable("");
    this.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName()
    }, this);
}

ko.applyBindings(new AppViewModel());

For a while I couldn't figure out why the fullName variable wasn't working properly. But then I noticed that I need to return this.firstName() instead of return this.firstName. Why is it that way? Is it just a strange JavaScript convention or is there some reason for it? I'd like to learn more about JavaScript and Knockout for my own enjoyment which is why I'm going through Knockout's tutorial.

A:

Why is it that way? Is it just a strange JavaScript convention or is
  there some reason for it?

It is this way, because this.firstName is an observable, a function. If you want to get it's value, you should evaluate it, this.firstName(). Whereas, if you want to set it's value, you should pass a value in it this.firstName("HandlerThatError"). This is the way observables work in knockout.js.
Regarding the this.fullName, this is a computed observable. The main difference between, this.fullName and this.firstName, this.lastName is that the value of this.fullName is dependent on the values of two other observables, while the values of this.firstName and this.lastName doesn't. Hence, this is called a computed observable.
From the knockout.js documentation:

How can KO know when parts of your view model change? Answer: you need
  to declare your model properties as observables, because these are
  special JavaScript objects that can notify subscribers about changes,
  and can automatically detect dependencies.

Furthermore,

To read the observable’s current value, just call the observable with
  no parameters.

and

To write a new value to the observable, call the observable and pass
  the new value as a parameter.


Q:

Rename 'Like' link in custom lists

Is there a way to rename the Like/Unlike links in a custom list where rating has been enabled?
'Like' in our case would be misleading so we would like to have it show up as something like 'Confirm'.

A:

You can use Client Side Rendering (CSR) for such requirements in SharePoint 2013.
Below is the code sample which replaces Like button by a image stored in Style Library:
SP.SOD.executeFunc("clienttemplates.js", "SPClientTemplates", function() {
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
      OnPreRender: function(ctx) {
          SP.UI.Reputation.LikesHelpers.ImageUrls.$W = "/Style Library/hand-like-32.png";
          SP.UI.Reputation.LikesHelpers.ImageUrls.$X = "/Style Library/hand-like-32.png";
      }
    });
});

You can find a full code and explanation at: Custom “Like”-Button in SharePoint List
.
Check my answer given here to know how to set the JSLink property of your Web Part:
Color Coding List Item by Web Part based on value


Q:

Get a specific image from any URL like Facebook does

My Question might be looks like similar to other questions but really this is not.(according to my knowledge). i can't understand that how to fetch a specific image from any URL Like Facebook does, i can't show you screen shot because i don't have real device. but i can show you Skype's screen shot taken from MAC. any help will be appreciated. thanks.
EDIT:i got favicon using this link but it is very small i want that in bigger size.

A:

finally, i got the answer. this might be helpful to you thats why i post this answer.use this macro#define FACEBOOK_GRAPH @"https://graph.facebook.com/v2.3/oauth/access_token?client_id=USE_YOUR_CLIENT_ID&client_secret=USE_YOUR_CLIENT_SECRET&grant_type=client_credentials"NOTE: you can get "client_id" and "client_secret" by registering your Application on developer.facebook.com now make a call for FACEBOOK_GRAPH Like bellow.
AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    //manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer=[AFJSONResponseSerializer new];
    AFHTTPRequestOperation* operation = [manager POST:FACEBOOK_GRAPH parameters:nil
                                              success:^(AFHTTPRequestOperation* op, id responseObject){
                                                  //here pass your URL as a string and access Token as a string, access token will found in responseObject
                                              }
                                              failure:^(AFHTTPRequestOperation* op, NSError* error){
                                                  NSLog(@"\n\nerror--->%@\n\n",error.localizedDescription);
                                              }];
    [operation start];

now the second method to get image from our URL, use our URL and access Token got from above method
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    token = [token stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer=[AFJSONResponseSerializer new];
    AFHTTPRequestOperation* operation = [manager POST:[NSString stringWithFormat:@"https://graph.facebook.com/v2.3/?id=%@&access_token=%@&scrape=true",url,token] parameters:nil success:^(AFHTTPRequestOperation* op, id responseObject){
        NSLog(@"\n\nData Response==\n%@\n",responseObject);
        //you will get Image URL in response
    }failure:^(AFHTTPRequestOperation* op, NSError* error){
                                                NSLog(@"##error--->\n%@",error.localizedDescription);
                                         }];
    [operation start];


Q:

Calculate value using row above in data.frame and another column

Hi I want to do something in R that seems like it should be simple but I seem to be having a brain fade.
For each row in a data.frame I want to get the value of Vol in row above, add value of In for that row and minus a value dependent on this value.
Here is my attempt but lag is just looking one row back for the values at the start, not continuing to look back once the next value has been calculated
library(dplyr)
df <- data.frame(In = c(1,4,0,0,1,2,3,0,0), Vol = c(1,rep(NA,8)))

df %>% mutate(Vol = (lag(Vol) + In) -  (lag(Vol) + In)*0.01)

desired output =
  In     Vol
1  1  1.00
2  4  4.95
3  0  4.90
4  0  4.85
5  1  5.79
6  2  7.72
7  3 10.61
8  0 10.50
9  0 10.40

A:

Here is a solution using accumulate from the purrr package. The accumulate function can apply a function with two arguments, such as x and y, to a sequence of vector. The return value would become the input value of the next round.
In the following example, I asked the accumulate function to begin at the second number of the In column to the end. I also provided 1 to the .init argument, which will be the first x to the function.
library(dplyr)
library(purrr)

df <- data.frame(In = c(1,4,0,0,1,2,3,0,0), Vol = c(1,rep(NA,8)))

df %>%
  mutate(Vol = accumulate(In[2:n()], function(x, y) (x + y) * 0.99, .init = 1))
#   In       Vol
# 1  1  1.000000
# 2  4  4.950000
# 3  0  4.900500
# 4  0  4.851495
# 5  1  5.792980
# 6  2  7.715050
# 7  3 10.607900
# 8  0 10.501821
# 9  0 10.396803

In addition, it seems like the first value from the Vol column is the same as the first value of the In column. If what you are trying to do is accumulate the process simply on the In column, the following code would be more concise and you don't even need to copy the first value to the Vol column.
df %>%
  mutate(Vol = accumulate(In, function(x, y) (x + y) * 0.99))
#   In       Vol
# 1  1  1.000000
# 2  4  4.950000
# 3  0  4.900500
# 4  0  4.851495
# 5  1  5.792980
# 6  2  7.715050
# 7  3 10.607900
# 8  0 10.501821
# 9  0 10.396803


Q:

Plotting ECDF of values using R and ggplot2

I'm trying to plot the ECDF of 'x' based on the observed frequency of 'x' given in 'freq'. The data frame is shown below.
    x   freq
1   1    165
2   2    898
3   3    289
4   4   2220
5   5    535
6   6   1885
7   7   2344
8   8  36550
9   9    884
10 10   1480
11 11   1132
12 12   2733
13 13   1828
14 14  11152
15 15   6379
16 16 304355

The following code snippet seems to generate what I want, but I was wondering if this is the right/better/idiomatic way to do this.
ggplot(transform(freq.data, ecdf = cumsum(freq)/sum(freq.data$freq)), aes(x, ecdf)) + geom_step()

A:

Does this work?
library(ggplot2)
x <- with(df, rep(x, freq))
ggplot(data = data.frame(x = x), aes(x)) + stat_ecdf()


Q:

SQL perf issue - configure server correctly first or troubleshoot issues one by one?

This is for SQL Server 2012.
I am  troubleshooting overall slow performance on a Dynamics AX environment. Everything is just slow - app itself, reports, ad-hoc, etc.  Right off the bat, I can see that none of the best practices for SQL Server have been configured - MAXDOP, tempdb, trace flags specific for Dynamics, and index/fragmentation maintenance.  I am pretty sure there are inefficient queries, missing or non-optimal indexes, etc.
I spent a little bit of time looking at wait stats, but now I'm wondering if I should first apply all the recommended best practices (industry-standard best practices for DynamicsAX), then troubleshoot what is slow, or dig into each issue one by one, and address it as it comes?  I know some will say, don't start flipping switches until you know for sure it needs to be flipped.
How would you approach this kind of scenario?

A:

There are a couple of things to say about this, Dynamics AX performance is not necessarily always caused by SQL Server slowness, especially if you say "everything is slow".
When faced with performance issues in Dynamics AX I tend to use the following approach:

First start with reviewing resources on all servers involved (cpu pressure, memory pressure, page life expectancy,...)

Every AOS, Client & Citrix need at least 4 cores
AX is very sensitive to CPU latency, make sure your CPU's are set to high performance in the BIOS. If you say everything is slow, even simple forms my gut feeling says this isn't the case.
Perform the standard  checks such as disk latency and the likes, not only on the SQL Server but on all components involved.

Then verify if all the SQL Server settings are correct and according to best practices

Correct trace flags
Correct index/stats maintenance
MaxDOP
max memory settings
...

Review all the relevant database properties if they are set according to best practices

auto update statistics

Review the database design by reviewing missing indexes and slow queries

use known DMV queries (I tend to like the Glenn Berry scripts)
log dmv data using DynamicsPerf If you contact support this will be the first tool they'll have you install
log slow queries to the SQL Statement trace log so you can relate them to the call stack in code

review known issues in the application set up (number sequences, database log, ...)

look at the top 10 issues discovered by the Premier Field Engineers

Once you have a setup that works acceptably and some processes remain slow, use the Trace Parser to have exact timings on every piece of code and query that's being run during the process. This should help you either solve or at least explain why the remaining process is slow.


Q:

D Programming - How to get the piped content from stdin

I'd like to get the piped content in stdin of a D program only IF it is there.
Considering the following
string output;
char[] buf;
while (stdin.readln(buf))
{
    output ~= buf;
}
return output;

This works great if you pipe content
e.g
echo "poop" | test.exe

will print out "poop" and continue execution.
However if you just run test.exe, it will hang there waiting for CTRL+C before continuing.
I'd like to assess the fact that content has been piped in so that I'm not doing a readline() if there is no piped content.
Any clues? Thanks!

A:

There's two ways you can do this: ask if data is available on stdin with a timeout, or see if stdin is a pipe or the user-interactive console. Both of these are platform specific; the D std library doesn't include a function to check them. Since you're talking exe, I'll give an answer for Windows. (If you aren't on Windows, the posix functions you want are probably select and isatty, search the web for info about them. You could also set the files to non-blocking mode and try to read.)
To check if data is available, you can call WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 50). The second argument is a timeout in milliseconds - 50 will be quick enough that it looks basically instant to a user, while giving a program time to pipe stuff to it. It will return zero if the object is ready; if there's data available.
https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032%28v=vs.85%29.aspx
WaitForSingleObject and STD_INPUT_HANDLE are both defined in D by first doing import core.sys.windows.windows;
import core.sys.windows.windows;
import std.stdio;

void main() {
        if(WaitForSingleObject(GetStdHandle(STD_INPUT_HANDLE), 50) == 0) {
                string output;
                char[] buf;
                while (stdin.readln(buf))
                {
                    output ~= buf;
                }
                writeln(output);
        }
}

To tell if stdin is a console.... well, to be honest with you, I don't remember how to do it in Win32 off the top of my head and need to go right now! Maybe I can come back later tonight and edit it in, but if you can find a C solution, the same thing can be done in D too.
See also my comment on the question about end-of-file.


Q:

Weird discrepancy between database value and value display in view

So I've implemented a voting system, and in my view where I print video.vote_sum, the value for one of the video's vote_sum displays 1. However when I run Video.find(450) in my console, I see that the element actually has a vote_sum of two. I'm not sure why this is happening, and although the voting works as it should, when I reload the page, the pluralize method in my view displays "1 votes". But this is only upon a page reload. When I'm voting, it displays "1 vote". Weird.
Here's the create method in the video_votes controller:
def create
  @video = Video.find(params[:video_id])
  @vote = current_user.video_votes.find_or_create_by_video_id(@video.id)

  if @vote.value.nil?
    if params[:type] == "up"
      @vote.value = 1
    else
      @vote.value = -1
    end
  elsif (params[:type] == "up" && @vote.value == 1) || (params[:type] == "down" && @vote.value == -1)
    @vote.value = 0
  elsif ((params[:type] == "up" && @vote.value == -1) || (params[:type] == "down" && @vote.value == 1)) || (@vote.value == 0)
    if params[:type] == "up"
      @vote.value = 1
    else
      @vote.value = -1
    end
  end

  if @vote.save
    respond_to do |format|
      format.html { redirect_to @video }
      format.js
    end
  else
    respond_to do |format|
      format.html { redirect_to @video }
      format.js {render 'fail_create.js.erb'}
    end
  end
end

Here's the relevant code in my Video model:
def vote_sum
  video_votes.sum(:value)
end

And here's the relevant code in my video_vote model:
after_update :update_vote_sum

private

  def update_vote_sum
    video.update_attributes!(:vote_sum => video.vote_sum + value)
  end

Why is this happening, and how could I fix it?

A:

I believe this is a problem with your view and the way you're using pluralize--you're supposed to pass it the singular version of your noun, and optionally a plural version (in case it can't guess it correctly).
Please see my change on GitHub.
Here's a screenshot:

[Update]
After messing with your app, somehow it's possible to get video.vote_sum (the actual database value) to be different than video.video_votes.sum(:value); I'm not yet sure why. However, you do have another issue with your codebase, demonstrated below:
ruby-1.9.2-p136 :001 > v = Video.find 2
 => #<Video id: 2, ... video_votes_count: 0, vote_sum: 3>
ruby-1.9.2-p136 :002 > v.video_votes.sum(:value)
 => 2
ruby-1.9.2-p136 :003 > v.vote_sum
 => 2 # doesn't match vote_sum in the database!

You have a method called vote_sum on your Video model. This means when you access @video.vote_sum, you are NOT accessing the vote_sum property from the model from the database, because you overwrite that functionality. This makes it pointless to update vote_sum in VideoVote's after_create because you can never access it (as demonstrated in my IRB session, above).


Q:

re-format CSV input file

what I want to do is just create CSV file initially and append to it every month end. So as to generate annual CSV file in following format:
Month 1, Nokia8800, 156.0
Month 1, Nokia3120, 113.0
Month 2, Nokia8800, 16.0
Month 2, Nokia3120, 152.0
Month 3, Nokia8800, 44.0
Month 3, Nokia3120, 52.0 and so on for 12 months.
Now what i need is to re-format this CSV in following file format:
Month 1,2,3,4,5,6,7,8,9,10,11,12
Nokia8800,156.0,16.0,44.0
Nokia3120, 113.0,152.0,52.0 and so on for 12 months.
How can i get this done?
thanks in advance.
*hope this can be solve with an arraylist..

A:

You can easily append to a file in Java with the PrintWriter class. When creating it, simply use the overloaded constructor to tell the PrintWriter to append to the file:
PrintWriter printWriter
    = new PrintWriter(new FileWriter(new File("filename"), true));

As for the second part, you can do this by reading everything into a Map and then rewriting it in the format you want.
Map<String, ArrayList<Double>> REGISTRY = new HashMap<String, ArrayList<Double>>();
REGISTRY.add("Month", new ArrayList<Double>());

Scanner scanner = new Scanner(new File("filename"));
while (scanner.hashNextLine()) {
    String[] line = scanner.nextLine().split(",");

    // for the month key
    String month = line[0].split(" ")[1];
    REGISTRY.get("Month").add(new Double(month));

    // then for the rest of the entries
    if (!REGISTRY.containsKey(line[1])) {
        REGISTRY.add(line[1], new ArrayList<Double>());
    }
    REGISTRY.get(line[1]).add(new Double(line[2]));
}

Now that everything is nice and sorted, you can easily write it out:
// first the months
printWriter2.print("Month");
for (Double d : REGISTRY.get("Month")) {
    printWriter2.print("," + d);
}
printWriter2.println();

// now the rest
for (Map.Entry<String, ArrayList<Double>> tuple : REGISTRY.entrySet()) {
    if (!tuple.getKey().equals("Month")) {
        printWriter2.print(tuple.getKey());
        for (Double d : tuple.getValue()) {
            printWriter2.print("," + d);
        }
        printWriter2.println();
    }
}

That should be it.
** I could have made a mistake, not in front of an IDE at the moment. Please let me know so I can correct it.
** Also, please note this is NOT a robust answer, but one that is very specific to the format of you input file. It has no exception handling which is a bad thing, but you can flesh it out.


Q:

How to add, subtract, multiply and divide 2 numbers each containing 100 digits in C? (using arrays)

I'am trying to write a C code to add, subtract, multiply and divide 2 numbers each containing 100 digits. This should include the use of arrays.
Can anyone please give me any suggestions, a pseudo code or a sample code?
To be more clear
The user will enter 2 numbers(Integers)
Each number can comprise of 100 or less digits i.e integer a can be 10 or 234 or 43582 or 23456788 or 23445667788...... etc. Same for integer b.
Now taking these two integers I have to perform the arithmetic operations of Addition,Subtraction,Division,Multiplication,Modulas(%)

A:

You could try using the GMP Library as answered in this question. It can perform Bigint operations in both C and C++. Also if you are fine with C++ code for Bigint you could check out this blogpost.


Q:

CryptKeeper icon doesn't show up in the tray?

I'm trying to encrypt a folder, but the CryptKeeper icon doesn't show up in the tray.  I'm not sure why.  I've tried changing the whitlist to "all", but that didn't work.  How do I get CryptKeeper to show up in the tray?  Or, what would be an alternative to CryptKeeper?

A:

It is a bug.
Here is the bug report:
Bug #760800 “Cryptkeeper icon do not appear on the gnome panel” : Bugs : “cryptkeeper” package : Ubuntu
And a work around:
How To Re-Enable The Notification Area (Systray) In Ubuntu, For All Applications ~ Web Upd8: Ubuntu / Linux blog
Basically you run the following command :
gsettings set com.canonical.Unity.Panel systray-whitelist "['all']"

See the link for a more detailed explanation and an graphical solution.


Q:

How to read logcat written through my application in all android os

I need to capture all the logs written through my application. I know from Jetllybean OS we can read need only our application log. But when I tried by using command "logcat -d" using exec method by application and  I did not get any data.
Please help me on this.
Thanks,
Saravanakumar

A:

This is the example that I was playing around with before that will generate a log text file in local storage:
private static String generateLogcatLogCommond = "logcat -d > /sdcard/IssueReport/log.txt";

public static String generateLogcatLog() throws InterruptedException {
    try {
        File issueReport = new File(Environment.getExternalStorageDirectory(), "IssueReport");
        if (!issueReport.exists())
            issueReport.mkdir();
        File logFile = new File(issueReport,"log.txt");
        logFile.createNewFile();

        Process process = Runtime.getRuntime().exec("/system/bin/sh -");
        DataOutputStream os = new DataOutputStream(process.getOutputStream());
        os.writeBytes(generateLogcatLogCommond);

        logLocation = "/sdcard/IssueReport/log.txt";
        Log.d("Client", logLocation);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return logLocation;
}

What the above code is doing is using 'sh' to run 'logcat -d' command and save it as a file locally. This will get ALL the logcat log. For you, you can change that to 'logcat -s ""' and it will save all logcat log of your application to a file.


Q:

What is a good substitute word for the X-cum-Y construction?

I wanted to use the word "cum" to avoid repeating "and" in the following phrase:

example.com is a teacher-cum-student search and listing site...

But on second thoughts, the word "cum" is also a vulgar slang, which certainly would raise a few eyebrows when readers come across it. Is there a good substitute for this word?

A:

It's utterly ridiculous to think of "cum" as the slang word.
"... the word 'cum' would raise a few eyebrows when readers come across it ..."
only if the readers are total morons.
So, in a "bevis and butthead" cartoon, that would happen.  ("Heh heh .. he said 'cum' .. heh heh")

A:

I think the best substitute for 'cum' is the simple forward slash:
teacher/student search and listing site.
However, you might also consider encouraging your readers to lift their minds out of the gutter by ignoring the salacious connotations of the word 'cum'.
Similarly, it seems a pity for everybody to have to stop allowing their consciences to prick them or refrain from cheering when someone cocks a snook at overbearing authority -- or for Dick's friends to be compelled to always call him Richard -- simply because they are all terrified of offending some self-styled Savonarola-in-a-suit.

A:

I'm not sure X-cum-Y is a substitute for X and Y.
X-cum-Y means that the single entity A is both an X and a Y at the same time, X and Y suggests two entities A being an X and B being a Y, except for the likes of johnny-cum-lately which is not the same thing.
If anything I'd think that it's search and listing that you want to combine into a dual nature rather than the intended audience and in that case example.com is a teacher and student search/listing site might work.


Q:

doFilter method called multiple times when an error is throw in a custom Servlet Filter

I have implemented a filter to check an IP adresses white list with Spring Security.
It works, but if i throw an error in my doFilter method, the throw is called 3 times oO.
I found a solution with "return;", but i am not that happy with it.
It means i have to log my error without using throw...
What do you think, is there any better way ? a best practice ?
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Here is the web configuration
    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
                http.authorizeRequests()
                        .antMatchers("/**").permitAll().and()
                        .addFilterBefore(new CustomIpFilter(),
                                BasicAuthenticationFilter.class)
                        .csrf().disable()
                        .formLogin().disable();
        }
    }

Here is my filter
    @Log4j2
    @WebFilter
    public class CustomIpFilter implements Filter {

        Set<String> whitelist = new HashSet<>();

        public CustomIpFilter() {
            whitelist.add("0:0:0:0:0:0:0:1"); //localhost
            whitelist.add("127.0.0.1");
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {

            String ipAdress = request.getRemoteAddr();
            if (!whitelist.contains(ipAdress)) {
                log.error("Unknown IP adress");
                /* if the return is replaced by throw line, it still works, but doFilter will be called 3 times and throw 3 times the same error
                throw new UnknownHostException("Unknown IP adress");*/
                return;
            }
            chain.doFilter(request, response); //Continue
        }

        @Override
        public void destroy() {

        }

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {

        }
    }

The controller used to test
@RestController
@RequestMapping(value = "test")
public class LoggerController {

    @GetMapping("/go")
    public String logsTest() {
        System.out.println("ok");
        return "Ok";
    }
}

i have tried the same stuff with an interceptor removing Spring Security using "preHandle" method and i still have 3 times the Throw.
So i start to understand why, look at the logs:
1st Throw
java.net.UnknownHostException: Unknown IP adress

2nd Throw
[nio-8181-exec-5] c.e.d.S.IpAdressInterceptor              : Unknown IP adress
[nio-8181-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] threw exception

3rd Throw:
[nio-8181-exec-5] o.a.c.c.C.[Tomcat].[localhost]           : Exception Processing ErrorPage[errorCode=0, location=/error]

Thanks for your help !

A:

You are running in a Servlet environment. The servlet spec doesn't say you should respond to errors by throwing exceptions. Instead, you are supposed to respond with an HTTP status code and message. When you throw the exception the servlet container is going to do its best to figure out what to do but frequently that will result in a 500 Internal Server Error being returned to the user, which isn't accurate or helpful.
Just returning from the filter isn't correct either as you haven't put anything into the HTTP response. Again, you should be setting an appropriate status code in the response, such as 403 Forbidden, which gives the caller an indication that something isn't configured correctly.


Q:

Arrays, going from MySQLi to PDO

A couple years ago, SO users helped me construct the following code to assign "partners" for in a group (like a round robin [A->B->C->D->A->B->...]):
$q = "SELECT user_id FROM users WHERE group_id='$gi' ORDER BY RAND()";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n
MySQL Error: " . mysqli_error($dbc));

    while ($row = mysqli_fetch_array($r)) {
        $users[] = $row[0];
    }

    $current = end($users);
    $partners = array();
    foreach ($users as $user) {
        $partners[$user] = $current;
        $current = $user;
        $q="UPDATE users SET partner='{$partners[$user]}' WHERE user_id='{$user}'";
        mysqli_query ($dbc, $q) or trigger_error("Query: $q\n
MySQL Error: " . mysqli_error($dbc));
    }

Now, however, I am rewriting much of my code with PDO, and arrays are killing me.  This is my best attempt so far at rewriting this:
$query = "SELECT id FROM users WHERE gid=:gid ORDER BY RAND()";
$query_params = array( ':gid' => $_SESSION['user']['gid'] );
try {
    $stmt = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch(PDOException $ex) {
    die("Failed to run query: " . $ex->getMessage());
}
while ($row = $stmt->fetchAll(PDO::FETCH_COLUMN)) {
$users[] = $row[0];
}
$current = end($users);
$partners = array();
foreach ($users as $user) {
    $partners[$user] = $current;
    $current = $user;
    $query = "UPDATE users SET partner=:partner WHERE id=:id";
    $query_params = array(
        ':partner' => '{$partners[$user]}',
        ':id' => '{$user}'
    );

    try {
    $stmt = $db->prepare($query);
    $result = $stmt->execute($query_params);
    }
    catch(PDOException $ex) {
        die("Failed to run query: " . $ex->getMessage());
    }
}

All my reading and searching has not yielded an answer as to why my revised code no longer works.  All that happens now is that the one user gets assigned himself as partner, rather than a round robin assignment of partners.
As best I can tell, my fetchAll statement is incorrect, but how?  I cannot, for the life of me, figure it out.
(And I won't be upset if you suggest a more efficient method of doing this whole thing.)

A:

Another hour of scouring and tinkering and I happened upon the answer.  I don't know why it seems to be shared nowhere, but the PDO equivalent of mysqli_fetch_array is not universally fetchAll.  In this case, and many others, the proper substitute is fetch(PDO::FETCH_NUM).
So, my code now works exactly as above except for this one change:
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
    $users[] = $row[0];
}

Instead of:
while ($row = $stmt->fetchAll(PDO::FETCH_COLUMN)) {
    $users[] = $row[0];
}


Q:

docker-compose: Sharing container between multiple projects by using the same container_name

I want to use a MySQL docker container for multiple projects running on the same server.
Using docker-compose v3 files, I simply have the same mysql container configuration in each of the projects, and they have the same container_name:
version: "3"

services:
  app1:
    image: foo
    links:
      - mysql

  mysql:
    image: mysql/mysql:5.7
    container_name: shared_mysql

The second application has a similar docker-compose.yml file, but with app2 instead of app1.
When running docker-compose up --no-recreate for app2, I get an error:
Creating shared_mysql ... error
ERROR: for shared_mysql
Cannot create container for service mysql: Conflict.
The container name "/shared_mysql" is already in use by container "deadbeef".
You have to remove (or rename) that container to be able to reuse that name.

What can I do to share the MySQL container between multiple docker projects?

A:

You can simply avoid redefining the mysql in one of the two docker-compose.yml files and connect mysql and the other containers to the same network.
In order to do so, create a network:
docker network create shared

Assign your network to your mysql container:
version: '3'
services:
  mysql:
    ...
    networks:
    - shared
networks:
  shared:
    external:
      name: shared

For any other container that has need to access mysql, just add the same network definition as above:
version: '3'
services:
  app1:
    ...
    networks:
    - shared
  app2:
    ...
    networks:
    - shared
  ...
networks:
  shared:
    external:
      name: shared

A:

If your container is only created from other compose file you can use the external links feature in docker-compose.
If you want both docker compose files to be able to create the mysql container, I suggest you look into Share Compose configurations between files and projects. In this case, you can create a base file that only defines mysql and extend/merge it in both apps compose files.


Q:

How can I find exact delay in badly synced audio and video streams in a media container?

While making screencasts I always end up with a file having poorly synced audio and video streams. This is not container specific as this happens with all the formats - ogg, mkv, avi, mp4 etc. I guess this has something to do with ffmpeg.
After searching on Internet, I found that this can be fixed using itsoffset switch in ffmpeg. I also tested it and it works. But the question is how do I find exact lag between audio and video streams in seconds:milliseconds?? I tried ffmpeg -i but it always shows delay to be zero.

A:

Do you know what a clapper is? It's an old device used in movie making and looks like this:

This is used by the editor to sync the video and audio together. You need this because there is nothing about audio and video streams that really allow a computer to work out how out of sync they are.
Your best course of action is to work out why your recording is going out of sync. It sounds like your computer might be underpowered (conjecture as I don't know how powerful your computer is). If you can't solve the syncing problem, then use a clapper (or make one) and then trial and error your way into syncing it back up.
Of course this only helps with fixed sync issues, if you have progressive sync issues then you can use the time signature to resync the streams and this is something the computer can help you with. Is suspect that's what ffmpeg is trying to do.


Q:

What makes Probability so difficult to get it right in the first place?

I took two classes of Probability, I did very well and was confident on the subject. Now I meet it again in my Combinatorial Algorithm course, and guess what? I feel completely blank again! I have to review all my notes, look for examples ... even though I've already "solved" them thoroughly. I realize the amount of time I spent for these Probability classes is usually double/triple the time I spent for any other science classes. Why is it so difficult to grasp the concepts in Probability in the first place?

A:

Human beings are notoriously bad at calculating probabilities.
Probability theory was not part of mathematics for  2000 years  and it took  more than 400 years  and the genius of  Cardano, Pascal, Fermat, Huygens, De Moivre, Laplace and finally Kolmogoroff to show that it  could after all be integrated  completely into  mathematics. To give just one example, the difficulty of probability theory was spectacularly illustrated  by the incredible number of mathematicians who gave wrong answers to the Monty Hall problem,  Paul Erdős (one of the most amazing mathematicians of the twentieth century) being one of  them.
The essential rôle of probability theory in quantum mechanics is probably also the reason why, as Bohr, Feynman and others liked to emphasize, nobody really understands quantum mechanics at the gut level (even though most of our technology nowadays derives from it). Some  scientists believe that our brains developed a superb intuitive understanding of kinematics and dynamics thanks to the pressure of the environment  on our hunter-gatherer ancestors  (think throwing spears at sabre-toothed tigers!) but that probability theory was useless there.
To come back to your question, it might  be closed because some users will feel that it is inappropriate for this site, but I am not sure  that evolutionary psychology sites or similar ones will be able to answer it either. But you should try your luck (and if you do learn something there, let me know: I find the subject interesting!)

A:

Its actually a way of thinking that is so quintessential to solve almost all text book problems in permutation and combination,
When you are doing it everyday it all seem obvious, but if you let loose of it, and then come back after some time, then it all seems distant and blurred.
Though this is somewhat true of all disciplines in mathematics , but its more evident in case of this particular subject of permutation and combination


Q:

Regex for case sensitive and conditions for the matching

I am trying to match words with the following structure:
call NAME,
or
call name;
that is, preceded by "call" and a blank space
And
NAME (whatever;
that is, NAME+ blank space+(
and the same for the lower case
I learnt (?.) for case insensitiveness. How the complete regex command would be?

A:

This does the trick:
Pattern pattern = Pattern.compile("(?:call (?i)name)|(?:(?i)name \\(.*)");

System.out.println(pattern.matcher("call NAME").matches());
System.out.println(pattern.matcher("call name").matches());
System.out.println(pattern.matcher("CALL name").matches());
System.out.println(pattern.matcher("NAME (blablabla").matches());
System.out.println(pattern.matcher("name (blablabla").matches());

Output:
true
true
false
true
true


Q:

Bootstrap collapse inside table with Laravel

What I am trying to do is to show the details checkout of specific order after the user hits the button with bootstrap collapse.
Below pictures will show you what I am expected as a solution.
Before clicking the button:

After clicking the button the desirable solution I want:

But instead of this result I have(that is my problem every td element is in one row only):

Html:

My Orders

Total orders: {{$orders->total()}}

        Order Id
        Total Paid
        Order Date/Time

    @foreach($orders as $keyo => $item)

            {{$item->id}} <button class="btn btn-success fa fa-eye" type="button" data-toggle="collapse" data-target="#viewmyorder{{$keyo}}" aria-expanded="false" aria-controls="collapseExample">
            {{ number_format($item->total_paid,2,',','') }} €
            {{$item->created_at}}

            <?php $orderitemtable = \App\OrderItem::all()->where('order_id', $item->id); ?>
            @foreach($orderitemtable as $theitems)
                <?php $findproducts = \DB::table('products')->select('id', 'name', 'code', 'price')->where('id', $theitems->product_id)->get(); ?>
            @foreach($findproducts as $pr)
                {{$pr->name}}
                <?php $findphoto = \App\Photo::where('product_id', $pr->id)->get()->first(); ?>
                show_path}}">
                {{$pr->code}}
                {{$pr->price}}
                @if($theitems->order_condition == 0)
            Condition Order: Is in proccess
            @elseif($theitems->order_condition == 1)
            Condition Order: We haven't enough items
            @elseif($theitems->order_condition == 2)
            Condition Order: Order Completed
            @endif
            @if(($theitems->order_comments != null)== true)
            {{$theitems->order_comments}}
            @else
            No comments in this item
            @endif

            @endforeach

            @endforeach

    @endforeach

A:

You can use accordion for collapse table rows.
Here is best example for it.
http://www.bootply.com/fdTMNTiLis


Q:

What is the name of this kind of forms?

I need to add a form exactly like this to my app, but I cannot find information because I do not know how do they are "called".
Form is like this:

A:

My fault, I attached the action bar to the activity and it shows exactly as the picture.


Q:

Node.js - Concurrent SQL queries crashing server

I have a basic Twitter-like app which works fine when one user is online. However, when more than one user comes online and tries to perform an SQL query the server crashes.
This is happening because the function closes the database for the first user while the second user is still mid-function, then the second user tries to close the already closed database, leading to a crash.
Here's a basic function as an example:
function showAllUsers(req, res){
  dbConnect();
  var query = 'SELECT * FROM USERS';
  connection.query(query, function (err,rows,fields){
    if (err) {
        throw err;
    }
    dbClose(req,res);
    console.log(rows);
    res.render('allUsers', { user: req.user, message: req.flash('info'), users: rows })
  })
}

I'm using the mysql package from npm, but I'm assuming I'm not using it correctly. I'm  currently opening the database before each query and closing it immediately afterwards.
Is there a safer way to do this, or can I just leave it open until the server quits?

A:

Using connection pools solved this issue for me.


Q:

Sparse Matrix error in MLPRegressor

Context
I'm running into an error when trying to use sparse matrices as an input to sklearn.neural_network.MLPRegressor. Nominally, this method is able to handle sparse matrices. I think this might be a bug in scikit-learn, but wanted to check on here before I submit an issue.
The Problem
When passing a scipy.sparse input to sklearn.neural_network.MLPRegressor I get:
ValueError: input must be a square array

The error is raised by the matrix_power function within numpy.matrixlab.defmatrix. It seems to occur because matrix_power passes the sparse matrix to numpy.asanyarray (L137), which returns an array of size=1, ndim=0 containing the sparse matrix object. matrix_power then performs some dimension checks (L138-141) to make sure the input is a square matrix, which fail because the array returned by numpy.asanyarray is not square, even though the underlying sparse matrix is square.
As far as I can tell, the problem stems from numpy.asanyarray preventing the dimensions of the sparse matrix being determined. The sparse matrix itself has a size attribute which would allow it to pass the dimension checks, but only if it's not run through asanyarray.
I think this might be a bug, but don't want to dive around filing issues until I've confirmed that I'm not just being an idiot! Please see below, to check.
If it is a bug, where would be the most appropriate place to raise an issue? NumPy? SciPy? or Scikit-Learn?
Minimal Example
Environment
Arch Linux
kernel     4.15.7-1

Python     3.6.4
numpy      1.14.1
scipy      1.0.0
sklearn    0.19.1

Code
import numpy as np
from scipy import sparse
from sklearn import model_selection
from sklearn.preprocessing import StandardScaler, Imputer
from sklearn.neural_network import MLPRegressor

## Generate some synthetic data

def fW(A, B, C):
    return A * np.random.normal(.3, .1) + B * np.random.normal(.6, .1)

def fX(A, B, C):
    return B * np.random.normal(-1, .1) + A * np.random.normal(-.9, .1) / C

# independent variables
N = int(1e4)
A = np.random.uniform(2, 12, N)
B = np.random.uniform(2, 12, N)
C = np.random.uniform(2, 12, N)

# synthetic data
mW = fW(A, B, C)
mX = fX(A, B, C)

# combine datasets
real = np.vstack([A, B, C]).T
meas = np.vstack([mW, mX]).T

# add noise to meas
meas *= np.random.normal(1, 0.0001, meas.shape)

## Make data sparse
prob_null = 0.2
real[np.random.choice([True, False], real.shape, p=[prob_null, 1-prob_null])] = np.nan
meas[np.random.choice([True, False], meas.shape, p=[prob_null, 1-prob_null])] = np.nan

# NB: problem persists whichever sparse matrix method is used.
real = sparse.csr_matrix(real)
meas = sparse.csr_matrix(meas)

# replace missing values with mean
rmnan = Imputer()
real = rmnan.fit_transform(real)
meas = rmnan.fit_transform(meas)

# split into test/training sets
real_train, real_test, meas_train, meas_test = model_selection.train_test_split(real, meas, test_size=0.3)

# create scalers and apply to data
real_scaler = StandardScaler(with_mean=False)
meas_scaler = StandardScaler(with_mean=False)

real_scaler.fit(real_train)
meas_scaler.fit(meas_train)

treal_train = real_scaler.transform(real_train)
tmeas_train = meas_scaler.transform(meas_train)

treal_test = real_scaler.transform(real_test)
tmeas_test = meas_scaler.transform(meas_test)

nn = MLPRegressor((100,100,10), solver='lbfgs', early_stopping=True, activation='tanh')
nn.fit(tmeas_train, treal_train)

## ERROR RAISED HERE

## The problem:

# the sparse matrix has a shape attribute that would pass the square matrix validation
tmeas_train.shape

# but not after it's been through asanyarray
np.asanyarray(tmeas_train).shape

A:

MLPRegressor.fit() as given in documentation supports sparse matrix for X but not for y

Parameters:
X : array-like or sparse matrix, shape (n_samples, n_features)
The input data.

y : array-like, shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels in classification, real numbers in regression).

I am able to successfully run your code with:
nn.fit(tmeas_train, treal_train.toarray())


Q:

Safari 5.0 Extension Scripts Won't Run on Local Files

I wrote a very simple extension for Safari 5 that only outputs a single log message from a start script. This is the start script:
console.log('start script running');
If I go to any internet page (eg. http://www.yahoo.com) the log message appears in the error console. But if I open any local html page no log message appears. By local I mean on my local machine. It's like my start script never gets run for local pages (eg. C:/blank.html).
Is there a permission setting I'm overlooking or is this a feature of Safari 5?
Brent

A:

Caveat: I only have a passing familiarity with the Safari extension system. I work on Google Chrome which is based on Webkit. Safari is also based on webkit.
In a Google Chrome extension, you can inject a script into a local page using the file:// permission. But I’m pretty sure there’s no analogue for Safari extensions.
The Safari page on script injection also seems to say you can’t interact with local files:
“You cannot access resources on the user’s hard drive outside of the extensions folder.”

A:

There is no way to inject scripts on local files.
If you feel like it, you may complain at bugreport.apple.com.


Q:

gridview link button are not work in other column

I have a GridView and in it there are some columns:
<asp:TemplateField HeaderText="Approved">
    <ItemTemplate>

Loan Calculation

        <asp:Button ID="btnapp" runat="server" Text="Approved" CommandName="Approved"
            CommandArgument='<%#Eval("rcno")+ "," +Eval("mobile")+ "," +Eval("email") %>'
            class="btn btn-success" />
    </ItemTemplate>
</asp:TemplateField>

This has successfully worked in only one column, not in the other column

A:

You can use Hyperlink to link the column in GridView.
Kindly check below example:
<asp:Hyperlink ID="Hyperlink2" CssClass="control" runat="Server"
    NavigateUrl='<%#Bind("link")%>' Text='<%#Bind("Title")%>'>
</asp:Hyperlink>


Q:

How can I use Mongodb Aggregation in this example?

I am currently using Python to build many of my results instead of MongoDB itself.  I am trying to get my head around Aggregation, but I'm struggling a bit.  Here is an example of what I am doing currently which perhaps could be better handled by MongoDB.
I have a collection of programs and a collection of episodes.  Each program has a list of episodes (DBRefs) associated with it.  (The episodes are stored in their own collection because both programs and episodes are quite complex and deep, so embedding is impractical).  Each episode has a duration (float).  If I want to find a program's average episode duration, I do this:
episodes = list(db.Episodes.find({'Program':DBRef('Programs',ObjectId(...))}))
durations = set(e['Duration'] for e in episodes if e['Duration'] > 0)
avg_mins = int(sum(durations) / len(durations) / 60

This is pretty slow when a program has over 1000 episodes.  Is there a way I can do it in MongoDB?
Here is some sample data in Mongo shell format.  There are three episodes belonging to the same program.  How can I calculate the average episode duration for the program?
> db.Episodes.find({
    '_Program':DBRef('Programs',ObjectId('4ec634fbf4c4005664000313'))},
   {'_Program':1,'Duration':1}).limit(3)

{
    "_id" : ObjectId("506c15cbf4c4005f9c40f830"),
    "Duration" : 1643.856,
    "_Program" : DBRef("Programs", ObjectId("4ec634fbf4c4005664000313"))
}
{
    "_id" : ObjectId("506c15d3f4c4005f9c40f8cf"),
    "Duration" : 1598.088,
    "_Program" : DBRef("Programs", ObjectId("4ec634fbf4c4005664000313"))
}
{
    "_id" : ObjectId("506c15caf4c4005f9c40f80e"),
    "_Program" : DBRef("Programs", ObjectId("4ec634fbf4c4005664000313")),
    "Duration" : 1667.04
}

A:

I figured it out, and it is ridiculously fast compared to pulling it all into Python.
p = db.Programs.find_one({'Title':'...'})

pipe = [
        {'$match':{'_Program':DBRef('Programs',p['_id']),'Duration':{'$gt':0}}},
        {'$group':{'_id':'$_Program', 'AverageDuration':{'$avg':'$Duration'}}}
        ]

eps = db.Episodes.aggregate(pipeline=pipe)

print eps['result']


Q:

How Get rid of NDK compiler warning: "APP_PLATFORM is larger.." and "Invalid package"

I have the following Application.mk
APP_PLATFORM := android-9
APP_STL := gnustl_static
APP_CPPFLAGS := -frtti -fexceptions -O2 -mfpu=neon -mfloat-abi=softfp
APP_ABI := armeabi-v7a
LOCAL_ARM_NEON := true

and when running ndk-build I always get the warnings:
Invalid attribute name:
    package
/Users/tmanthey/Documents/android/android-ndk-r8d/build/core/add-application.mk:128: Android NDK: WARNING: APP_PLATFORM android-14 is larger than android:minSdkVersion  in ./AndroidManifest.xml
Invalid attribute name:
    package

This is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.evotegra.aCoDriver"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <uses-permission android:name="android.permission.CAMERA" />

    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.VIBRATE"/>

    <application
        android:name=".ACoDriverApp"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" android:allowBackup="true">
        <activity
            android:name=".ACoDriverActivity"
            android:label="@string/app_name" android:launchMode="singleTask">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="PreferencesActivity" />
        <activity android:name="GaugeSelectActivity" />
    </application>

</manifest>

How can I get rid of these warnings?

A:

Regarding "package", this is most likely some crlf problem with your XML file. Check the line end characters there. Or, maybe something is wrong in your project.properties file.
The APP_PLATFORM warning is actually correct: your APP_PLATFORM (android-14) is larger than android:minSdkVersion you set in AndroidManifest.xml. This is only a warning to remind you about this (legitimate) situation, so that at certain stage you decide to drop support for very dated devices.

A:

For NDK rev r9 (works in others too but line# may differ)
${NDK}/build/core/add-application.mk line 138
add "#" at start of the line.
# $(call __ndk_info,WARNING: APP_PLATFORM $(APP_PLATFORM) is larger than android:minSdkVersion $(APP_MIN_PLATFORM_LEVEL) in $(APP_MANIFEST))
One character, 30 second fix ... go debug native code.


Q:

Cairo and memory leaks fix with valgrind

In my program, even if do all the obvious housekeeping, such as calling cairo_destroy(), cairo_surface_destroy()..., valgrind always finds memory leaks, the leaks are in cairo dependencies (freetype, pixman, ...). How do I cleanup after cairo, so that valgrind won't detect any leaks, or are the leaks normal?
Sample output
==1861== HEAP SUMMARY:
==1861==     in use at exit: 1,996,663 bytes in 532 blocks
==1861==   total heap usage: 21,915 allocs, 21,383 frees, 95,411,698 bytes allocated
==1861==
==1861== LEAK SUMMARY:
==1861==    definitely lost: 0 bytes in 0 blocks
==1861==    indirectly lost: 0 bytes in 0 blocks
==1861==      possibly lost: 0 bytes in 0 blocks
==1861==    still reachable: 1,996,663 bytes in 532 blocks
==1861==         suppressed: 0 bytes in 0 blocks
==1861== Reachable blocks (those to which a pointer was found) are not shown.
==1861== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==1861==
==1861== For counts of detected and suppressed errors, rerun with: -v
==1861== Use --track-origins=yes to see where uninitialised values come from
==1861== ERROR SUMMARY: 1961 errors from 7 contexts (suppressed: 1 from 1)

UPDATE:
This question says, the "leaks" are normal, does there exist a way to do the cleanup, so valgrind becomes happy?

A:

For cairo there is cairo_debug_reset_static_data().
While writing this as a comment, I was looking into pixman's source and the implementation of _pixman_choose_implementation() and apparently you cannot "clean up" pixman.
I have no clue about freetype.
Edit:
For fontconfig (related to freetype, so possibly interesting here), there is FcFini().


Q:

How to split a "historical" git repository?

I have here a rather special case: I have some old repositories in different VCSs (git,svn). I now want/have to tidy up things a bit.
The goal was to migrate everything to one single VCS and we decided on git.
In a first step I imported the "foreign" VCS history into git using git svn. Everything ok so far.
Another issue was that the users did not use SVN correctly in the sense that all files (including the generated/compiled ones) were added to the VCS.
As a result the history is quite large and cumbersome.
As new projects will soon start from the actual version I search for a solution to avoid the whole binary data to be kept within every development repo in git. On the oter hand I do not want to throw everything old away. It might be needed in future. as there are severar branches,...
I found the information that the linux kernel used a spliting of the history too (see this question on stackoverflow).
I played a bit around with the linux kernel repos to see how things work out there.
Now I am unsure if I understood everything correctly and if I am doing it the right way. Normally I would create an orphaned branch from the working copy and use this one as the starting point of any future development:
git checkout --orphan new_master
<Commit all source files and leave all bin files out>
git remote add new_origin <...>
git push new_origin new_master:master

In case the old history is needed I need to clone the newly created repository as well as the "historical" one. The I have two independent working lines in git which are logically linked.I then add a graft for the initial commit of the new repo to the final commit of the historical repo and should be set up with a complete repo.
Am I correct or is there a better way?

A:

You can simply use something like
git init
git add .
git commit -m "Import project blablabla"

in a directory containing all the files you want to import (but not the directories like .svn), and get a new Git repository without history.
git checkout --orphan would also work if you already have an imported history and if the latest commit of this history contains the right files.
Then, you want to graft this commit on top of the imported history. Graft points were initially created for this use-case, but they were superseded by git replace. The manual page for git replace is hard to read, but there's a Replace Kicker tutorial.


Q:

how to avoid loading the source for iframe

I would like to improve loading performance for a page that has a button to trigger a popup initially hidden on the page (uses 'modal' component from twitter bootstrap). This popup body contains an iframe, which source is loaded on the page inital load adding about 30-40% more time to load, however. The iframe source is not needed to be loaded till the button is clicked which brings up the popup with the iframe. How can one avoid loading the iframe source on initial page load? ...only load the iframe source when the button is clicked? Can JS be used here? If so, then how or what method/library? Is there a better approach than make popup with iframe hidden in the page to improve loading time? Thank You

A:

This is possible with JavaScript (no extra libraries required).
Simply use a function to set the src/display the frame when a link or button is clicked.
function loadIFrame(frameID, url) {
    var frame = document.getElementById(frameID);
    frame.setAttribute('src', url);
    frame.style.display = 'block';
}

See the example here:
http://jsfiddle.net/ZNGmy/


Q:

makefile: dynamically expose global variables from within targets

I want to use dynamic variables in make file, e.g.:
all: ask
        @echo "I want the $$ANSWER here too"
ask:
        @read -p "please enter your answer: " ans && export ANSWER=$$ans
        @echo "Your answer is $$ANSWER"

The above example does not work, the $ANSWER is empty.
EDIT:
Asking question using read is only an example. My purpose is that the value must be dynamically obtained at runtime of the target, not calculated on top of the makefile, or passed in on command line of make.

A:

As I said in my comment, asking interactive questions in makefiles is a bad idea; Make is not designed for that. The whole point of Make, is that if all files are up to date, nothing happens. In your case, no matter what, you want something to happen. Not a good use case for Make.
Having said that, I still want to give you an answer. Maybe you will like this:
all: ask
    @echo "I want the $$(cat ANSWER) here too"
ask:
    @read -p "please enter your answer: " ans && echo -n "$$ans" > ANSWER
    @echo "Your answer is $$(cat ANSWER)"


Q:

C# making own button and passing argument

We use C# form applications as HMI for our Automation projects.
While doing this we generally use button click events. These events are changed boolean values from false to true. My problem starts here.
There are lots of boolean and if I add button events one by one, I will spend many many times. So I want to do my own button component and. I will drag and drop my button from toolbox and relate it with a boolean using properties window. After doing this, It will do everything automaticly instead of me. Button design is not important for me.
Example:
//Define Variables
public class PLCVars
{
    public bool PLCVar1;
    public bool PLCVar2;
    public bool PLCVar3;
    public bool PLCVar4;
    public bool PLCVar5;
    public bool PLCVar6;
    public bool PLCVar7;
    public bool PLCVar8;
}

//(!)I have a PLCVars object defined as PLCVariables
//Button Events
private void button_JogPLCVar1_MouseDown(object sender, MouseEventArgs e)
{
    PLCVariables.PLCVar1 = true;
}

private void button_JogPLCVar1_MouseUp(object sender, MouseEventArgs e
{
    PLCVariables.PLCVar1 = false;
}

As shown above example, I want to relate my button component with a plc variable. It will make all mouseup and mousedown events automaticly and change the value of plc variables.
As I searched, I should use Custom Control. But I don't know relating form variables with Custom Control components is posibble. If it is possible how?

A:

There is no need for custom control. Subscribe all buttons to these two event handlers. All you need to do is get PLCVar# field name. And you can use button's Tag property for that. Assign field name to tags PLCVar1, PLCVar2 etc. Then get field name in event handler and assign value via reflection:
private void button_JogPLCVar_MouseDown(object sender, MouseEventArgs e)
{
    Button button = (Button)sender;
    SetPLCVariable((string)button.Tag, true);
}

private void button_JogPLCVar_MouseUp(object sender, MouseEventArgs e
{
    Button button = (Button)sender;
    SetPLCVariable((string)button.Tag, false);
}

private void SetPLCVariable(string fieldName, bool value)
{
    Type type = typeof(PLCVars);
    FieldInfo fieldInfo = type.GetField(fieldName);
    fieldInfo.SetValue(PLCVariables, true);
}

Creating and subscribing all buttons
 panel1.Controls.Clear();

 for (int i = 1; i < 5; i++)
 {
     Button button = new Button();
     button.Name = "Button" + i;
     button.Tag = "PLCVar" + i;
     button.MouseUp += button_JogPLCVar_MouseUp;
     button.MouseDown += button_JogPLCVar_MouseDown;
     panel1.Controls.Add(button);
 }

NOTE: It's better to use properties instead of public fields. For properties you will need to use type.GetProperty method. Also it's better to use FlowLayoutPanel.


Q:

How to do an ordered reduction in OpenMP

OpenMP 4.5+ provides the capability to do vector/array reductions in C++ (press release)
Using said capability allows us to write, e.g.:
#include <vector>
#include <iostream>

int main(){
  std::vector<int> vec;

  #pragma omp declare reduction (merge : std::vector<int> : omp_out.insert(omp_out.end(), omp_in.begin(), omp_in.end()))

  #pragma omp parallel for default(none) schedule(static) reduction(merge: vec)
  for(int i=0;i<100;i++)
    vec.push_back(i);

  for(const auto x: vec)
    std::cout<<x<<"\n";

  return 0;
}

The problem is, upon executing such code, the results of the various threads may be ordered in any which way.
Is there a way to enforce order such that thread 0's results preceed thread 1's, and so on?

A:

The order of a reduction is explicitly not specified. ("The location in the OpenMP program at which the values are combined and the order in which the
values are combined are unspecified.", 2.15.3.6 in OpenMP 4.5). Therefore you cannot use a reduction.
One way would be to use ordered as follows:
std::vector<int> vec;
#pragma omp parallel for default(none) schedule(static) shared(vec)
for(int i=0;i<100;i++) {
    // do some computations here
    #pragma omp ordered
    vec.push_back(i);
}

Note that vec is now shared, and ordered implies a serialization of execution and synchronization among threads. This can be very bad for performance except if each of your computations require a significant and uniform amount of time.
You can make a custom ordered reduction. Split the parallel region from for loop and manually insert the local results in a sequential order.
std::vector<int> global_vec;
#pragma omp parallel
{
    std::vector<int> local_vec;
    #pragma omp for schedule(static)
    for (int i=0; i < 100; i++) {
        // some computations
        local_vec.push_back(i);
    }
    for (int t = 0; t < omp_get_num_threads(); t++) {
        #pragma omp barrier
        if (t == omp_get_thread_num()) {
            global_vec.insert(local_vec.begin(), local_vec.end())
        }
    }
}


Q:

Add rewrite endpoint to author page + pagination

I want to add a new endpoint to the author page, so that the URL looks like this:

http://example.com/writer/username/articles

So far, I have:

Changed the author base
Added a rewrite rule
Setup the query_vars
Added the endpoint
Used template_redirect to use my template

Result: 404 Page Not Found (even after flushing the rewrite rules). I can't figure out where the problem is. Also I'd like to add pagination to the endpoint. Below is my code:
Changed the author base:
function foo_change_author_base() {
    global $wp_rewrite;
    $wp_rewrite->author_base = 'writer';
}
add_filter( 'init', 'foo_change_author_base', 0 );

Added a rewrite rule:
function foo_rewrite_rule()
{
    add_rewrite_rule( 'writer/([^/]+)/articles(/(.*))?/?$', 'index.php?author_name=$matches[1]&articles=$matches[3]', 'top' );
}
add_action( 'init', 'foo_rewrite_rule' );

Setup query_vars:
function foo_add_vars($vars) {
    $vars[] = 'articles';
    return $vars;
}
add_filter('query_vars', 'foo_add_vars');

Added the endpoint:
function foo_add_endpoint() {
    global $wp_rewrite;
    add_rewrite_endpoint( 'articles', EP_AUTHORS | EP_PAGES );
}
add_action( 'init', 'foo_add_endpoint');

And added my template:
function foo_rewrite_template()
{
    global $wp_query;

    if ( array_key_exists( 'articles', $wp_query->query_vars ) ) {
        include (get_template_directory_uri() . '/articles.php');
        exit;
    }
}
add_action( 'template_redirect', 'foo_rewrite_template' );

A:

Your code should works. The line:
include (get_template_directory_uri() . '/articles.php');

Needs to have  allow_url_include=1 in the server configration because you are trying to include a file via http. Can you check this?
You must know also that template_redirect should be use for a real redirect, a include() may have undesired effects here. I think what you really want is template_include:
add_filter('template_include', 'my_template_include');

function my_template_include( $template ) {
    global $wp->query;
    if ( array_key_exists( 'articles', $wp_query->query_vars ) ) {
        return get_template_directory() . '/articles.php';
    }
   return $template;
}

So here is my code:
function foo_change_author_base() {
    global $wp_rewrite;
    $wp_rewrite->author_base = 'writer';
}
add_filter( 'init', 'foo_change_author_base', 0 );

function foo_rewrite_rule()
{
    add_rewrite_rule( 'writer/([^/]+)/articles/page/([0-9]{1,})/?$', 'index.php?author_name=$matches[1]&articles=1&paged=$matches[2]', 'top' );
    //If you don't want the last trailing slash change the las /?$ to just $
    add_rewrite_rule( 'writer/([^/]+)/articles/?$', 'index.php?author_name=$matches[1]&articles=1', 'top' );
}
add_action( 'init', 'foo_rewrite_rule' );

function foo_add_vars($vars) {
    $vars[] = 'articles';
    return $vars;
}
add_filter('query_vars', 'foo_add_vars');

function foo_add_endpoint() {
    add_rewrite_endpoint( 'articles', EP_AUTHORS );
}
//add_action( 'init', 'foo_add_endpoint'); // Commented out
// Edit: add_rewrite_endpoint is not needed when using add_rewrite_rule

// auto-add the articles endpoint to author links
function foo_author_link_filter( $link, $author_id, $author_nicename ) {
    return user_trailingslashit($link) . 'articles/';
}
add_filter( 'author_link', 'foo_author_link_filter', 20, 3);

add_filter('template_include', 'foo_template_include');
function foo_template_include( $template ) {
    global $wp_query;
    //You may need some other checks
    if ( array_key_exists( 'articles', $wp_query->query_vars ) ) {
        return get_template_directory() . '/articles.php';
    }
    return $template;
}

Now go to yoursite.com/writer/author_name/articles/


Q:

iOS swift NSMutableData has no member appendString

Hello I am new to swift and I am following a tutorial and creating the same code in order to Upload an image . I am now using swift 3 and it seems like NSMutableData() no longer has the appendString method available what can I do as a substitute ? The tutorial I am following is here http://swiftdeveloperblog.com/image-upload-example/ and my code is this
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
       let body = NSMutableData()

        if parameters != nil {
            for (key, value) in parameters! {
                body.("--\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value)\r\n")
            }
        }

        let filename = "user-profile.jpg"
        let mimetype = "image/jpg"

        body.appendString(options: <#T##NSData.Base64EncodingOptions#>)("--\(boundary)\r\n")
        body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
        body.appendString("Content-Type: \(mimetype)\r\n\r\n")
        body.appendString("\r\n")

        body.appendString("--\(boundary)--\r\n")

        return body
    }

Again the issue is with the appendString as I am getting the error:
value of type NSMutableData has no member appendString
I been searching for work arounds but have not found any and I have the append method available but it does not take a String.

A:

As @dan points out in the comments, that method is part of the tutorial you’re looking at. It’s easy enough in Swift without defining a custom method, though.
First, don’t use NSMutableData; instead, use the new Data struct, which will be either mutable or immutable depending on whether you use var or let:
var body = Data()

Then to append UTF-8 bytes:
body.append(Data("foo".utf8))

(There are other String methods for other encodings if you need something other than UTF-8.)
If you want the exact behavior of the tutorial, here’s how to translate its method to Swift 3:
extension Data {
  mutating func append(string: String) {
    let data = string.data(
        using: String.Encoding.utf8,
        allowLossyConversion: true)
    append(data!)
  }
}

…

body.append("foo")

I wouldn’t recommend this code, though, for two reasons. First, the lossy conversion means that your app may silently discard important data. Second, the force unwrap (data! instead of data) means that in case of encoding trouble, your app will crash instead of displaying a useful error.

A:

extension NSMutableData {

    func appendString(_ string: String) {
        let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
        append(data!)
    }
}

This work With Me Swift 3


Q:

convert double quote string to string array in vb.net

How can I convert below string,
"[""1"",""2"",""3""]"

To this,
["1","2","3"]

I have try this without success:
Replace(string, """", "")

A:

In vb.net - you should try like this,
 Dim stringVar As String = "[""1"",""2"",""3""]"
 stringVar.Replace("""", "")

Also check this to use Replace function.


Q:

What does mean $$ or $! in bash?

It's kind of easy question but I didn't find any information. What does mean $! or $$ in bash?
For example: ps -p $!  or pstree $$?

A:

Actually, these variables were inherited by bash from the Bourne shell.
"$$" means current PID.
"$!" is the PID of the last program your shell ran in the background (e.g. "myprog &")
Here is a list of shell variables:

http://unixhelp.ed.ac.uk/scrpt/scrpt2.2.2.html

A:

$! is the process ID of the last job run in the background.
$$ is the process ID of the script itself.
(Both of the above are links to the Advanced Bash Scripting Guide on TDLP.)


Q:

Sorting an imported list not working

I am trying to sort an imported list then display it but I have tried all sorts of things and it didnt work.
Here is an exemple of the list:
pommes : 54
bananes : 18
oranges : 30

ananas :12
clémentines    :77
cerises de terre:    43

The output should be ordered alphabeticaly
This is what I am getting
['\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0', '1', '1', '2',
 '3', '3', '4', '4', '5', '7', '7', '8', ':', ':', ':', ':', ':', ':', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e'
, 'e', 'e', 'g', 'i', 'i', 'l', 'm', 'm', 'm', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'o', 'o', 'p', 'r', 'r', 'r', 'r', 's', 's', 's', 's', 's', 's', 's', 't', 't
', 'é']

Here's is my code
import sys

def liste(entree):
    try:
        ouvrir = open("data2.txt")
    except IOError:
        message1 = "Le fichier data2 n'existe pas."
        return message1
    lecture = ouvrir.read()
    if len(entree) < 1:
        message2 = "Il faut préciser le nom du fichier à traiter"
        return message2
    elif len(entree) > 1:
        message3 = "Un seul argument est attendu, soit le nom du fichier à traiter."
        return message3
    else:
        return lecture

def main():
    while True:
        entree = sys.argv[1:]
        choix = str(entree)
        texte = "data2.txt"
        if texte in choix:
            message4 = liste(entree)
            message4 = sorted(message4)
            print(message4)
            break
        else:
            print("Il faut préciser le nom du fichier à traiter")
            exit()

if __name__ == "__main__":
    main()

A:

Try readlines, (see this answer: How do I read a file line-by-line into a list?, also see: Reading a text file and splitting it into single words in python).
Oh, and 'with open()' is idiomatic (moreso than try),
with open("data2.txt") as ouvrir:
    lines = ouvrir.readlines()
print sorted(lines)

Assuming each line contains a single word, you are done.
Suppose you want to treat each line as words (one or more words per line), sort the words on each line, and sort the lines,
#open file "data2.txt" and readlines into list
#split each line into words and sort that list of sorted lines
#words = list ( list ( word ) )
with open("data2.txt") as ouvrir:
    lines = ouvrir.readlines()
    line_words = [ x for x in [ line.split(":") for line in lines ] ]
    #line_names = [ x[0] for x in [ line.split(":") for line in lines ] ]
print sorted(line_words)

Suppose each line has one or more words, and you want a sorted list of words? The following flattens the nested list of words into a single list of words,
#open file "data2.txt" and readlines into list
#split each line into words, flatten into single list of words
#words = list ( word )
with open("data2.txt") as ouvrir:
    lecture = ouvrir.readlines()
    words = [ word for line in lecture for word in line.split() ]
print sorted(words)

Suppose your lines have key:value pairs, e.g. "Apple: 23"?, then you want something different
Your program combines examining entree (slice sys.argv[1:]) with opening and reading a file. You should separate those two functions. Here is one way to revise your code,
import sys

def liste(texte,entree):
    if len(entree) < 1:
        return "Il faut préciser le nom du fichier à traiter"
    elif len(entree) > 1:
        return "Un seul argument est attendu, soit le nom du fichier à traiter."
    with open(texte) as ouvrir:
        lecture = ouvrir.readlines()
        words = [ x.split(":")[0].strip() for x in [ line.strip() for line in lecture ] ]
        words = [ x for x in words if len(x) > 1 ] #filter, remove short words (blanks)
        return lecture
    return "Le fichier {} n'existe pas.".format(texte)

def main():
    while True:
        entree = sys.argv[1:]
        choix = str(entree)
        texte = "data2.txt"
        if texte in choix:
            message4 = sorted(liste(texte,entree))
            print(message4)
            for el in message4: print(el)
            break
        else:
            print("Il faut préciser le nom du fichier à traiter")
            break

if __name__ == "__main__":
    main()
    exit()


Q:

Retrieving the COM class factory for component with CLSID {...} failed due to the following error: 80040154

I am using DirectShowLib and SampleGrabber to capture video frames of an AVI file.
I am accomplishing this by using graph builder and couple of filters. Everything was working fine, I was able to initialize graph and filters.
I then added code to get some video information like Dimension, Frame rate e.t.c. For this I used to IMediaDet. But when I try to initialize it:
Type t = Type.GetTypeFromCLSID(new Guid("65BD0710-24D2-4ff7-9324-ED2E5D3ABAFA"));
IMediaDet mediaDet = (IMediaDet)Activator.CreateInstance(t);

The Activator.CreateInstance(t) throw an exception:

Retrieving the COM class factory for component with CLSID {65BD0710-24D2-4FF7-9324-ED2E5D3ABAFA} failed due to the following error: 80040154.

I don't think its the problem with the build as the filters and graph builder are initializing fine. Any one has any idea, or is there any other API I can use to gather AVI file information like Dimensions, Frame rate, Video Length?

A:

I think you mistyped the Guid.  It is close to one supported by qedit.dll, 65BD0711-24D2-4FF7-9324-ED2E5D3ABAFA, you're off by one digit.


Q:

Symfony 4 Translations not displaying

So I have the following demo for the Symfony 4 framework which works fine and translates everything as expected:
$translator = new \Symfony\Component\Translation\Translator('en_GB');
$translator->addLoader('array', new \Symfony\Component\Translation\Loader\ArrayLoader());
$translator->addResource('array', [
    'sample' => 'The English translation goes here...',
], 'en_GB');
echo $translator->trans('sample');

However I can't seem to get the following demo to work:
echo $this->get('translator')->trans('sample');

The following config is in place:
/config/services.yaml:
parameters:
    locale: en

/config/packages/translation.yaml:
framework:
    default_locale: en
    translator:
        fallbacks: ['en']
        paths:
            - '%kernel.project_dir%/translations'

/translations/messages.en.yaml:
sample: The English translation goes here...

Dumping out the following:
$request->getLocale();
$request->getDefaultLocale();

Produces the following strings:
'en_GB'
'en'

And I've tried renaming the translation file to 'messages.en.yaml', 'messages.en_GB.yaml', 'messages.en_US.yaml' and then run "php bin/console cache:clear" afterwards to ensure the cache was fully cleared.
I can't seem to get the translations to display from the yaml file. There are no errors displaying but only the translation keys are visible.
Can anyone see if I'm making an obvious mistake somewhere or overlooking something?
PHP 7.2.0-2+ubuntu16.04.1+deb.sury.org+2 (cli) (built: Dec 7 2017 20:14:31) ( NTS ) Linux Mint 18, Apache2 Ubuntu.

A:

I had the same problem and i found a solution . Maybe this is a solution for someone else too.
In my case the command
./bin/console cache:clear

didn't cleared the /var/cache/translations folder. After dropping this folder manually
rm -rf var/log/translations

the translations were loaded like expected.
I don't know why the cache:clear isn't working probably in this case, but at the moment i get along with it. Maybe i find some time next week to debug the reason.


Q:

making a popup window with menus

I'm writing a program to simulate an ATM machine. I have the code to simulate it but it's all text. I want to put a GUI on it which I'm working on. I originally have a window that pops up at the beginning asking for the username and password. My idea is to put a JButton that when clicked a new window will pop up with the options to be selected, "check balance, deposit and withdraw". All these options will be JButtons also to perform the actions. How can I create a new panel to appear on the screen with the options. JOptionPane.showInputDialog only displays a message. Would it be necessary to make a new JPanel for the option?
Kindly advice.

A:

You may not wish to shove a bunch of windows at the user since that will make for a very annoying user interface. Instead, consider doing what professional applications do -- keep one window in view for the most part, but change views in that window, showing an occasional dialog window as needed. In Swing you can use a CardLayout to help you swap JPanels, each with its own GUI/view on it.
If you're interested in pursuing this, then check out the CardLayout tutorial. There are also plenty of examples of CardLayout use to be found on this site, several written by me.


Q:

What is "formatting" in Latin?

I would like to adapt the proverb dē gustibus nōn est disputandum ("there's no accounting for taste") to refer to formatting—the layout of text on a page, the font selection, the use of italics, and so on.
Is there a Classical word for this "formatting"? I know there was no equivalent to modern typography in ancient Rome, but perhaps some Classical author wrote about the aesthetics of arranging words in inscriptions, or about different styles of handwriting?

A:

I would suggest simply the word forma.
It means all kinds of things related to shape, size, form, and such.
The linked entry in L&S (I.B.2) gives "outline, plan, design (of an architect, etc.)".
Formatting is the design of a page much like how that part of the dictionary entry describes the design of a house.
I found no attestations related to writing, but this seems to be a word for design in many senses.
The word forma is very general, so I quite like the maxim de formis non est disputandum as a general reminder to focus on content rather than shape.
If you want a more specific word to be able to make distinction with something you call forma, then perhaps formatio (post-Augustan) is a good alternative.


Q:

What is overextending?

I've been hearing this term a lot when used in context of scrim matches between teams in TF2, or usually during Highlander sessions.
What does it mean? What does it refer to?

A:

In the context of TF2, overextending is commonly used to define a specific mistake in attack/defense maps. On defense, a team "overextends" when they repel an initial offensive wave and proceed to extend as far as they can, hoping to push the offense all the way to their base and begin a spawn camp, which generally wins games.
However, given that this usually occurs when the defense is on their last capture point, their last point is now vulnerable to any enterprising Spy or Scout. Any offensive player that recognizes an potential overextension will try to hide and ride out the defensive push-back, then proceed to capture the now un-defended point.


Q:

Visual Studio 2017 add item cross-platform missing

I have installed Visual Studio 2017 to follow along with online training for Xamarin created in May. They instructed us to add a new item and then selected Cross-Platform.
I did not have Cross-Platform as an option. I found a post for an older version of Visual Studio where they showed how to add it manually. I did this and it created the Cross-Platform item but this only contained four options instead of the ten in the video.
Has this been taken away in a newer release or do I need to do something to add all the items?
Many thanks

A:

I have finally found a solution. I used the Visual Studio uninstaller to uninstall Mobile Development with .Net, rebooted and then installed it again. Works like a charm. There must have been old versions that were not getting updated or something was corrupt. Hope this helps someone.