text:
Q: Ruby on Rails: How can I add a css file with rails project? The application.html.erb file:
<!DOCTYPE html>

  <title>Site</title>
  <%= stylesheet_link_tag    :all %>
  <%= javascript_include_tag "application" %>
  <%= csrf_meta_tags %>

<%= yield %>

I have a file "cake.generic.css" in public/ folder.
But when I reload the page the effect of css file is not working.
If I see the page view source I see something like this:
<!DOCTYPE html>

  <title>Site</title>
  <link href="/assets/all.css" media="screen" rel="stylesheet" type="text/css" />

  <meta content="authenticity_token" name="csrf-param" />
<meta content="6CPvchXr1amagxd7VmOzB82WGx/WmjfDOXjMLfjLzqQ=" name="csrf-token" />

Home#index

Find me in app/views/home/index.html.erb

What should I do to fix this problem?
How can I set the public folder for stylesheets and javascripts?
It looks that app/assets folder is set for css and js files?

A: Rails is likely consolidating all your css files into one that it is calling assets/all.css
Consider using the free plug-ins firebug + firepath to further characterize the problem.  This common combo of tools will help you to interrogate web page elements and see the css that is contributing to their display.

A: Copy cake.generic.css to the folder public/assets/, if not exists make directory first.
then add this to you erb

<%= stylesheet_link_tag "cake.generic" %>

2nd question: How can i set the public folder for stylesheets and javascripts ?
Just put all you images, js and css file under 'public/assets/' and then include them in the erb pages
3rd question: It looks that app/assets folder is set for css and js files ?
Yes, 'app/assets/stylesheets/' for css and scss file
and 'app/assets/javascripts'  for js and coffeescript file
You can get more info here: http://guides.rubyonrails.org/asset_pipeline.html#how-to-use-the-asset-pipeline
Hope this work for you:)

A: Your Style sheet should be placed in the following directory \public\stylesheets from your root project and also if you want to specify different location provide an absolute path inside stylesheet_link_tag("/public/yourfolder/test.css")

A: I had similar issue, but my fix was to make sure the css is under app/assets/stylesheets/   and I had to add the below line to the application.css file (my css file is named custom.css)
@import 'custom'


text:
Q: Getting which radio button is selected by POST with JSP I'm trying to POST to a JSP page some values with radio buttons.
It's a little paradoxic:

*

*By selecting another radio button it doesn't deselect the previous one, if I take various names for the radio buttons, but if I name the radio buttons equal it always returns me the value 'on' by trying to catch the value with -> request.getAttributes('filter').

To getting the value 'on' if one of them is selected is way pointless, if the speech is about radio buttons.
My question now is how will I able to catch which one of them is selected?
Maybe by setting the value tag and getting it on the JSP site? If so, how is that achievable?
The worst case is, that I name the radio buttons with various values and deselect the previous one with javascript.
<form method="post" action="./activity.jsp">
    <input type="radio" name="filter" value="nofilter" checked="checked"> Kein Filter
    <input type="radio" name="filter" id="dayRadio"> Tag
    <input type="text" id="day" onfocus="choosed(this)">
    <input type="radio" name="filter" id="weekRadio"> Woche
    <input type="text" id="week" onfocus="choosed(this)">
    <input type="radio" name="filter" id="monthRadio"> Monat
    <input type="text" id="month" onfocus="choosed(this)">
    <input type="radio" name="filter" id="yearRadio"> Jahr
    <input type="text" id="year" onfocus="choosed(this)">
    <input type="submit" value="OK">
</form>

A: The idea is that you group the radio buttons together by giving them the same name, but then you assign the different buttons different values, so you know which one has been clicked
<INPUT TYPE="radio" name="filter" value="1"/>Tag
<INPUT TYPE="radio" NAME="filter" VALUE="2"/>Woche

and then in your java
String value= request.getParameter("filter");
System.out.println(value);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does the IronKey executable on Ubuntu 11.10 fail when executed? When I plug my IronKey into my Ubuntu 11.10 64-bit laptop, the read-only partition mounts as usual at /media/Ironkey. However, when I change into the /media/IronKey/linux/ directory and try to execute the ironkey executable via ./ironkey, it returns the following:
bash: ./ironkey: No such file or directory

I have lib32gcc1 installed, and this used to work fine but all the sudden does not. Any ideas?

A: If you are on Ubuntu, try
# apt-get install lib32gcc1

which worked for me.

A: I believe it may be related to the Linux kernel being modified.  You would probably need to contact IK to see if they have a patch available.


text:
Q: get HTMLUnitDriver bypass untrusted certificate verification (Selenium 2.0) I have been trying to access an HTTPS URL with the HTMLUnitDriver API of Selenium 2.0, but somehow the execution gets stuck at the "This Connection is Untrusted" window and and the control doesn't return back. Following is the code I have tried working on after I got some hint from this thread:
WebDriver driver = new HtmlUnitDriver() {
    protected WebClient modifyWebClient(final WebClient client) {
        try {
            client.setUseInsecureSSL(true);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        return client;
    }
};
driver.get("https://172.25.194.91:8443/meta/homeScreen.do");

I'd highly appreciate any help to get it work .

A: The issue was something else and is resolved now: HtmlUnitDriver uses WaitingRefreshHandler without parameters and unfortunately that is inappropriate for some sites - for example, HtmlUnitDriver hangs on http://news.google.com.
Cause & Scenario:

*

*You load a page, which refreshes to itself after a period of time, because of the presence of a <meta http-equiv="refresh"...> directive in your HTML header.

*WaitingRefreshHandler waits for the time specified but after that time elapses, it again redirects HtmlUnitDriver to get that page!

*Consequently, you loop forever in this redirection process.

Solution:
One needs to extend the HtmlUnitDriver and override the modifyWebClient method to set a new (read: to clear the) refresh handler.
@Override
protected WebClient modifyWebClient(WebClient client) {
    RefreshHandler rh = new RefreshHandler() {
        public void handleRefresh(final Page page, final URL url, final int seconds) { }
    };
    client.setRefreshHandler(rh);
    return client;
}


text:
Q: inline css in angularjs I am new to angular js and material design, can someone help me on how can I make this css as inline css to my md-select tag?
css:
body md-select-menu, body md-content{
  max-height: 350px;
}

here's my html code for md-select
<md-select ng-model="aaa" name="bbb" required>
    <md-option value="1">1</md-option>
    <md-option value="2">2</md-option>
    <md-option value="3">3</md-option>
    <md-option value="4">4</md-option>
    <md-option value="5">5</md-option>
    <md-option value="6">6</md-option>
    <md-option value="7">7</md-option>
    <md-option value="8">8</md-option>
    <md-option value="9">9</md-option>
    <md-option value="10">10</md-option>
    <md-option value="11">11</md-option>
    <md-option value="12">12</md-option>

it's now working when I just use the style attribute.

A: james,
You won't be able to do it for two reasons:

*

*This directive won't map the parameter style="yourstyle" to whatever other structure lays underneath

*You can't apply inline css to nested child elements
I do believe the best way to do it still is having you css class. (This is also pretty good for code reuse)

A:     <md-select ng-model="aaa" name="bbb" class="mdselectheight" required>
        <md-option value="1">1</md-option>
        <md-option value="2">2</md-option>
        <md-option value="3">3</md-option>
        <md-option value="4">4</md-option>
        <md-option value="5">5</md-option>
        <md-option value="6">6</md-option>
        <md-option value="7">7</md-option>
        <md-option value="8">8</md-option>
        <md-option value="9">9</md-option>
        <md-option value="10">10</md-option>
        <md-option value="11">11</md-option>
        <md-option value="12">12</md-option>
</md-select>

        .mdselectheight{
        max-height: 350px !important;
        }

try this i'm not sure this is working or not.


text:
Q: Ler diversos arquivos .txt e remover informações duplicadas Tenho diversos arquivos .txt com matrículas e algumas se repetem em arquivos diferentes e eu gostaria de remover todas as repetidas.
A primeira solução que pensei foi fazer uma comparação entre todos os arquivos usando PHP ou NodeJS, mas fiquei meio com o pé atrás e não sei se isso seria a melhor solução.
Depois pensei em jogar tudo num DB apenas para tratar, pq preciso dessas matrículas em arquivos .txt, mas vi que o DB iria ficar enorme, com muitas matrículas e talvez não seja muito viável por se tratar de centenas de arquivos e milhares de matrículas.
Qual seria a melhor solução para esse problema? Alguma dessas duas acima podem resolver?

A: Você pode utilizar a função file para abrir o arquivo e jogar todo o conteúdo dele em um array.
Depois basta utilizar a função array_unique para remover as linhas idênticas.
01.txt
valdeir
psr
naval
fuz. nav
valdeir
valdeir psr
stackoverflow

Código PHP
<?php

$files = glob("*.txt");

$content = [];

foreach($files as $file) {
    $content = array_merge($content, file($file, FILE_IGNORE_NEW_LINES));
}

$contentUniq = array_unique($content);

var_export($contentUniq);

Output
array (
  0 => 'valdeir',
  1 => 'psr',
  2 => 'naval',
  3 => 'fuz. nav',
  5 => 'valdeir psr',
  6 => 'stackoverflow',
)


text:
Q: Disable a PHP Plugin on mobile Screens with Code? I have this plugin called "WP FLOAT", I want to disable it when it detects a small screen size, lets say smaller than 400px.  Is there a line of PHP code I can paste in one of the plugin's files to make this happen?
These are the only files for the plugin:
wp-float/wp-float(.)php
wp-float/readme(.)txt
wp-float/js/jquery.hoverIntent.minified(.)js
wp-float/js/jquery.easing(.)js
wp-float/js/wp-float-button(.)js
wp-float/js/jquery.floater.2.2(.)js
wp-float/js/button-wpfloat(.)php
What would I paste and in which file? Thanks

A: As Nicolas said, there's no way to access the client screen size on server side unless we have previously sent that information from the client side, JavaScript for example.
But, headers brings us a nice information. So, if you're looking to disable it for, let's say, mobile devices, which we can assume they won't have a big screen, you can try reading the headers of the request to get the browser's agent, lets say, in PHP:
if (preg_match('/iphone|android|blackberry|nokia/i'),$_SERVER['HTTP_USER_AGENT']))
    echo "Looks like a small screen device...";

You could also try this PHP class for detecting mobile devices:
http://code.google.com/p/php-mobile-detect/
Later you can do something like this
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;

if ($detect->isMobile()) {
    echo "It's a phone or tablet";
}

if($detect->isTablet()){
    echo "It's a tablet";
}

if ($detect->isMobile() && !$detect->isTablet()) {
    echo "It's a phone ;)";
}

A: well you can remove properly with jquery after you get the current size of screen or with media querys in css.

A: I don't think you can do that, because PHP is on the server, there is no way to get the size of the screen from it.
However, you could use javascript to redirect to the current page and disable the plugin:
if(!isset( $_GET['r'] ) )
{
  $script = "<script>";
  $script .= 'document.location="' . $_SERVER['PHP_SELF']. '?r=1&width=screen.width';
  $script .= "</script>";
  echo $script;
}
else {
  if( isset( $_GET['width'] ) && $_GET['width'] < 400 )
    // Disable plugin
}

I would suggest you to change the plugin or look for another workaround, because I believe this is gonna be a little slow.


text:
Q: Rewrite image link in angular app with a different domain than native I suppose this can be done on http server level since I am using the same domain on angular app for server and client.
But say if I want angular to fetch the image from another domain based the URL I am having in my content. How can the angular do it?
Say this image url is relative src='/php-load-image/abc.jpg, how can I rewrite it in angular routing level or http request level? I don't know how to put it but surely I can also parse that url and replace the relative path to another domain path.


text:
Q: How to extract a specific string followed by any number? I have a small problem.
I have text in this format:
A.1 Goals

Section 1: Blah Blah Blah
Random sentence A. Random sentence.
Section 2: Blah Blah Blah
Random sentence A.
Random sentence.

A.2 description

I want to obtain output of:
A.1 Goals

Section 1: Blah Blah Blah

Section 2: Blah Blah Blah

A.2 description

So basically how to obtain any string that is repeated more than once and followed by any possible number (any pattern of the same string and varying numbers)

A: We can use grep after reading with readLines.  Here, we match either
the letter ("A" followed by a . followed by one or more numbers - \\d+) or (|) if the text starts with "Section" (^Section) followed by some characters (.*) and if there is a repeated word followed spaces ((\\w+\\s*)\\1 - \\1 is the backreference for the captured group)
out <- grep("(^A\\.\\d+)|(^Section.*\\b(\\w+\\s*)\\1)", lines, value = TRUE)
cat(out, sep= "\n\n")
#A.1 Goals

#Section 1: Blah Blah Blah

#Section 2: Blah Blah Blah

#A.2 description

data
lines <- readLines("file.txt") #reading from the file

A: You can try this, However I am not sure about the exact output:
string <- c("Section 1: Blah Blah Blah","Random sentence A. Random sentence.",
"Section 2: Blah Blah Blah","Random sentence A.",
"Random sentence.")

 grep("(\\w+)\\s+\\1\\s+\\1",string, value=TRUE)

Logic: The word is wrapped under parenthesis to capture it, then it can be captured into \\1 to get the repetition. Taking two instances of \\1 suggest we want to select it more than twice.
I am assuming the similar structure that , the word must be followed by a space then the word.
Output:
[1] "Section 1: Blah Blah Blah" "Section 2: Blah Blah Blah"

Added after OP Request:
With invert = TRUE in grep, you can change the matching
 grep("(\\w+)\\s+\\1\\s+\\1",string, value=TRUE,invert = TRUE)

Hence above regex would result to :
#[1] "Random sentence A. Random sentence."
#[2] "Random sentence A."
#[3] "Random sentence."


text:
Q: Getting window height on mobile (jQuery Mobile) How do I get window height on mobile? $(window).height() works fine on desktop, but as soon as I emulate a mobile device from Chrome dev tools, it reports back that the window height is 1739px. Why is this?
http://jsfiddle.net/frank_o/ebkeq/3/embedded/result/
$(document).on("pagecontainershow", function() {

  // https://github.com/jquery/jquery-mobile/issues/6306
  alert($(window).height());
});

A: See documentation on the window object here: http://www.w3schools.com/jsref/obj_window.asp
Try
window.innerHeight

or
window.outerHeight

And for jQuery:
$(window).innerHeight()

http://api.jquery.com/innerHeight/


text:
Q: Returning viewmodel from view gives an ampty object in the controller I'm working on a small project. The intention is to maintain the presences of a couple of users on some specific dates. This dates are first chosen by the user.
Therefor I use a view model. This will provide all possible data with a check box in a table to show to the user.
In the view itself I walk every day in the given view modeland I let the view generate a tag  and an editor object (Html.EditorFor ()). All this is surrounded by the form creation (@ Html.BeginForm ()). Rendering the view is not the problem.
The problem is when I try to return the view model. The viewmodel object that I receive is an object with null - objects in themselves. Like it has been created by the default constructor.
Controller:
[HttpGet]
    public ActionResult OpldagenLt()
    {
        var lt = _gebruikerRepository.GeefTraject(_gebruikerRepository.TrajectId);
        List<DatumModel> data = new List<DatumModel>();
        foreach (Opleidingdag opldag in lt.GeefOpleidingdagenKleinerDanOfGelijkAanVandaag())
            data.Add(new DatumModel(opldag));

        List<ToekomstModel> toekomst = new List<ToekomstModel>();
        foreach (Opleidingdag opldag in lt.GeefOpleidingdagenGroterDanVandaag())
            toekomst.Add(new ToekomstModel(opldag));

        DataModel datamod = new DataModel();
        datamod.Datums = data;
        datamod.Toekomst = toekomst;

        if (lt.ControleerAantalOpleidingdagen())
        {
             _gebruikerRepository.GekozenDagen = GekozenDagen(datamod) as List<Opleidingdag>;
            return RedirectToAction("Index", "Aanwezigheid");
        }
        return View(datamod);
    }

    [HttpPost]
    public ActionResult OpldagenLt(DataModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        _gebruikerRepository.GekozenDagen = GekozenDagen(model) as List<Opleidingdag>;

        return RedirectToAction("Index", "Aanwezigheid");
    }

    public ICollection<Opleidingdag> GekozenDagen(DataModel datamod)
    {
        List<Opleidingdag> dagen = new List<Opleidingdag>();
            foreach (DatumModel datum in datamod.Datums)
            {
                dagen.Add(datum.Dag);
            }
        return dagen;
    }

View:
@using(@Html.BeginForm( "OpldagenLt", "Leertraject", FormMethod.Post))
{

            reeds begonnen dagen

        @foreach (var item in @Model.Datums)
        {

                @Html.DisplayFor(modelItem => item.Dag.Dag.Day)/@Html.DisplayFor(modelItem => item.Dag.Dag.Month)/@Html.DisplayFor(modelItem => item.Dag.Dag.Year)
                @Html.EditorFor(modelItem => item.Checked)

        }

            Dagen in de toekomst

        @foreach (var item in @Model.Toekomst)
        {

                @Html.DisplayFor(modelItem => item.Dag.Dag.Day)/@Html.DisplayFor(modelItem => item.Dag.Dag.Month)/@Html.DisplayFor(modelItem => item.Dag.Dag.Year)

        }

<input type="submit" value="Volgende"/>

}

Model:
using System;
using System.Collections.Generic;
using ProjectII.Models.domain;

namespace ProjectII.Viewmodels
{
public class DataModel
{
    public  DataModel()
    {
        Datums = new List<DatumModel>();
    }

    public ICollection<DatumModel> Datums { get; set; }
    public ICollection<ToekomstModel> Toekomst{ get; set; }
}

public class DatumModel
{
    public DatumModel()
    {
        Dag = new Opleidingdag(new DateTime().Date);
        Checked = true;
    }
    public DatumModel(Opleidingdag opldag)
    {
        Dag = opldag;
        Checked = true;
    }

    public Opleidingdag Dag { get; set; }
    public bool Checked { get; set; }
}

public class ToekomstModel
{
    public ToekomstModel()
    {
        Dag = new Opleidingdag(new DateTime().Date);
    }
    public ToekomstModel(Opleidingdag opldag)
    {
        Dag = opldag;
    }

    public Opleidingdag Dag { get; set; }
}
}

Thanks in advance for the help

A: With the way you construct your view, the ModelBinder cannot differantiate between the different elements in the list, and doesn't recognize them as items in the list. Try constructing the view like this:
@{ int datumteller = 0; }
 @foreach (var item in @Model.Datums)
 {

            @Html.DisplayFor(modelItem => @Model.Datums[datumteller].Dag.Dag.Day)/@Html.DisplayFor(modelItem => @Model.Datums[datumteller].Dag.Dag.Month)/@Html.DisplayFor(modelItem => @Model.Datums[datumteller].Dag.Dag.Year)
            @Html.EditorFor(modelItem => @Model.Datums[datumteller].Checked)

 datumteller++;
 }

@{ int toekomstteller = 0; }
 @foreach (var item in @Model.Toekomst)
 {

            @Html.DisplayFor(modelItem => @Model.Toekomst[toekomstteller].Dag.Dag.Day)/@Html.DisplayFor(modelItem => @Model.Toekomst[toekomstteller].Dag.Dag.Month)/@Html.DisplayFor(modelItem => @Model.Toekomst[toekomstteller].Dag.Dag.Year)

  toekomstteller++
  }

A: @stephen: thanks for the help.
with keeping your answer in my mind I finally succeeded returning those data.
I changed the foreach into a for
and changed ICollection to a List
Model:
using System;
using System.Collections.Generic;
using ProjectII.Models.domain;

namespace ProjectII.Viewmodels
{
public class DataModel
{
    public List<DatumModel> Datums { get; set; }
    public List<ToekomstModel> Toekomst{ get; set; }
}

public class DatumModel
{
    public DatumModel()
    {
        Dag = new Opleidingdag(new DateTime().Date);
        Checked = true;
    }
    public DatumModel(Opleidingdag opldag)
    {
        Dag = opldag;
        Checked = true;
    }

    public Opleidingdag Dag { get; set; }
    public bool Checked { get; set; }
}

public class ToekomstModel
{
    public ToekomstModel()
    {
        Dag = new Opleidingdag(new DateTime().Date);
    }
    public ToekomstModel(Opleidingdag opldag)
    {
        Dag = opldag;
    }

    public Opleidingdag Dag { get; set; }
}
}

view:
@model ProjectII.Viewmodels.DataModel

@using(@Html.BeginForm())
{

            reeds begonnen dagen

         @for (int i = 0; i < Model.Datums.Count; i++)
       {

                @Html.DisplayFor(modelItem => Model.Datums[i].Dag.Dag.Day)/@Html.DisplayFor(modelItem => Model.Datums[i].Dag.Dag.Month)/@Html.DisplayFor(modelItem => Model.Datums[i].Dag.Dag.Year)

                     @Html.EditorFor(modelItem => Model.Datums[i].Checked)

        }

    @*@for (int i = 0; i < Model.Datums.Count; i++)
    {

 @Html.DisplayFor(x => Model.Datums[i].Dag.Dag)
            @Html.CheckBoxFor(x => Model.Datums[i].Checked)

    }*@

            Dagen in de toekomst

        @foreach (var item in @Model.Toekomst)
        {

                @Html.DisplayFor(modelItem => item.Dag.Dag.Day)/@Html.DisplayFor(modelItem => item.Dag.Dag.Month)/@Html.DisplayFor(modelItem => item.Dag.Dag.Year)

        }

<input type="submit" value="Volgende"/>

}

Now I recieve a model with the right values
thanks for the help people


text:
Q: How to convert a tab-separated file into a comma-separated file? I want to convert a tab-separated file into a CSV file. Can anyone help me?

A: The answer for OSX is different.
MacOS does not understand \t in the sed expression.
You have to insert the tab literal into the sed search pattern by using ctrl+v then tab (see How can I insert a tab character with sed on OS X?)
sed 's/ /,/g' input_file > output_file

A: You can use sed as:
sed 's/\t/,/g' input_file > output_file

This will keep the input file unchanged and will create a new file output_file with the changes.
If you want to change the input file itself without creating a new file you can use -i option to sed to do inplace changes:
sed -i 's/\t/,/g' input_file

A: This can also be achieved with Perl:
In order to pipe the results to a new output file you can use the following:
perl -wnlp -e 's/\t/,/g;' input_file.txt > output_file.csv
If you'd like to edit the file in place, you can invoke the -i option:
perl -wnlpi -e 's/\t/,/g;' input_file.txt
If by some chance you find that what you are dealing with is not actually tabs, but instead multiple spaces, you can use the following to replace each occurrence of two or more spaces with a comma:
perl -wnlpi -e 's/\s+/,/g;' input_file
Keep in mind that \s represents any whitespace character, including spaces, tabs or newlines and cannot be used in the replacement string.

A: If the input_file did not contain commas nor quoted tabs, the easiest method is to use the sed command with a substitution regular expression that replaces tabs in the input_file with commas:
sed 's/\t/,/g' input_file > output_file

There is of course the case of input_files containing quoted tabs that will confuse the regex, also input_files that has values containing commas, these values should be quoted in output_files. Thee regex solution above would not be sufficient to address those cases.
One could think of several bash commands to "clean" the input file before processing it...
However, in the spirit of not reinventing the wheel. I would use a simple python3 script and store it in a file, let's call it: tsv_to_csv_converter.py:
import csv
import sys

tsv_file = sys.argv[1]
csv_file = sys.argv[2]

in_tsv = csv.reader(open(tsv_file, "r"), delimiter = '\t')
out_csv = csv.writer(open(csv_file, 'w'))

out_csv.writerows(in_tsv)

Of course, this code can be dramatically improved with exception catching, input value checks, a nice CLI interface, documentation.
The script can be used as follows:
python3 tsv_to_csv_converter.py input_file output_file

A: Bear in mind that there are many flavours of comma-separated-value file.  Since you didn't specify one, I'll assume RFC-4180 format, in UTF-8 encoding, and the TSV to be the same but using tabs instead of commas.
The naive approach would be to simply replace every tab with a comma:
tr '\t' ,

This falls down if any of the values already contain a comma, or if any contain a quoted tab.  You'll need to minimally parse the file, to maintain quoting.  Instead of hand-rolling such a parser, it's simpler, clearer and more flexible to use one already written, such as Text::CSV for Perl:
#!/usr/bin/perl -w

use Text::CSV;

my $tsv = Text::CSV->new({ sep_char => "\t", auto_diag => 2 });
my $csv = Text::CSV->new();

while (my $row = $tsv->getline(*ARGV)) {
    $csv->print(STDOUT, $row) or die $csv->error_diag();
    print $/;
}
$csv->error_diag() unless $tsv->eof;

A: After testing in MacOS, this is working for converting csv file to tsv file (suppose no tab or comma exists in the column values):
cat file_input.tsv | tr '\t' ',' > file_output.csv
I tried:
sed 's/ /,/g' input_file > output_file
and
sed 's/\t/,/g' input_file > output_file
However, neither of them worked.

A: Is this the usual easy-question-all-languages thing? Okay, here is my haskell solution:
main = interact (unlines . replTab . lines) where
  replTab l = l       >>= (\line ->
    "\"" ++ line "\"" >>= \char ->
    case char of
      '\t' -> "\",\""
      '"'  -> "\"\""
      _    -> [char]
    )

not tested, but should work.
PS: All the other solutions aren't aware of escaping commas.

A: Try replacing all the tabs with commas.
Possibly with a regex like s/\t/,/g, if you don't have any quoted fields.
Or, you know, Excel could do that for ya.  Or R.  Or anything which can take in a TSV file.

A: In UNIX replace all tabs with commas in place:
sed -i -e 's/\t/,/g' filename

A: sed -e 's/TAB_CHAR/,/g' data.tsv > data.csv
The tricky part is how to enter the TAB character in command line, to do that:
Just hist "CTRL+V", then TAB
I frequently use this with mysql queries with -e parameter as described in this blog post http://blog.modsaid.com/2013/12/exporting-data-from-remote-mysql.html


text:
Q: Android Studio - Failed to resolve: com.android.support:appcompat I know this question has been asked several times on the forum but I still haven't succeed in solving the problem.
SO I am trying to use the Parrot's sdk for programming a drone app, on the sdk documentations they say to put this in the gradle
build.gradle to use Parrot's sdk 3
Here is one gradle I tried for my the drone module of my app:
apply plugin: 'java'

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile project(':referencing')
    compile 'com.android.support:appcompat-v7:v24.2.0'

    compile 'com.parrot:arsdk:3.11.0'
}

sourceCompatibility = "1.7"
targetCompatibility = "1.7"

and I get this error when making the drone module:
Error:Could not resolve all dependencies for configuration ':drone:compileClasspath'.
> Could not find com.android.support:appcompat-v7:21.0.3.
  Searched in the following locations:
      file:/opt/android-studio/gradle/m2repository/com/android/support/appcompat-v7/21.0.3/appcompat-v7-21.0.3.pom
      file:/opt/android-studio/gradle/m2repository/com/android/support/appcompat-v7/21.0.3/appcompat-v7-21.0.3.jar
      https://jcenter.bintray.com/com/android/support/appcompat-v7/21.0.3/appcompat-v7-21.0.3.pom
      https://jcenter.bintray.com/com/android/support/appcompat-v7/21.0.3/appcompat-v7-21.0.3.jar
  Required by:
      DroneRacingApp:drone:unspecified
> Could not find com.android.support:appcompat-v7:21.0.3.
  Searched in the following locations:
      file:/opt/android-studio/gradle/m2repository/com/android/support/appcompat-v7/21.0.3/appcompat-v7-21.0.3.pom
      file:/opt/android-studio/gradle/m2repository/com/android/support/appcompat-v7/21.0.3/appcompat-v7-21.0.3.jar
      https://jcenter.bintray.com/com/android/support/appcompat-v7/21.0.3/appcompat-v7-21.0.3.pom
      https://jcenter.bintray.com/com/android/support/appcompat-v7/21.0.3/appcompat-v7-21.0.3.jar
  Required by:
      DroneRacingApp:drone:unspecified > com.parrot:arsdk:3.11.0
> Could not find any matches for com.android.support:support-v4:22.0.+ as no versions of com.android.support:support-v4 are available.
  Searched in the following locations:
      file:/opt/android-studio/gradle/m2repository/com/android/support/support-v4/maven-metadata.xml
      file:/opt/android-studio/gradle/m2repository/com/android/support/support-v4/
      https://jcenter.bintray.com/com/android/support/support-v4/maven-metadata.xml
      https://jcenter.bintray.com/com/android/support/support-v4/
  Required by:
      DroneRacingApp:drone:unspecified > com.parrot:arsdk:3.11.0 > com.parrot:libARDiscovery:3.11.0

I am new to android and not familiar with all the tools yet. In my project structure the targeted version of the SDL is set to 25 and the minimum to 15.
I have tried to replace the appcompat version in build.gradle to 25.0.1, 25.1.1, 25.0.0, and other values but it doesn't work.
In the SDK manager the Android Support Repository is also installed, I don't have any clue of how I can solve the problem.
Thank you for your help,
regardings.
Edit: Here is my project's build.gradle, I have not touched it yet.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Edit 2: Android Studio is looking for `appcompat``in /opt/android-studio/gradle/m2repository/com/android/support/appcompat-v7/21.0.3/appcompat-v7-21.0.3.pom whereas the file is located in /opt/android-sdk/extras/android/m2repository/com/android/support/appcompat-v7/23.0.1/appcompat-v7-23.0.1.pom, that may be the real problem.
However, in the project structure window, the android sdk is set to /opt/android-sdk, but I am not sure if it is part of the android sdk...
So how can I tell android studio to look in the right folder?

A: The problem was that the module was a Java Library whereas it should be an Android Library.
So I've recreated an Android Library module and put my classes in it, here is the build.gradle in which I have just added the dependency compile 'com.parrot:arsdk:3.11.0':
apply plugin: 'com.android.library'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.1"

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.1'
    testCompile 'junit:junit:4.12'
    compile 'com.parrot:arsdk:3.11.0'

}

and everything works as expected now!


text:
Q: Acessing divs using the selenium IDE New to selenium and this is my sample project.
I have a element inside of a div that I cant access, I have tried searching for answers but only found java code. As I am new to selenium I am using the Table way of making my tests.
I found this answer:
You can use cssSelector,
driver.switchTo().frame(driver.findElement(By.cssSelector("iframe[title='Fill Quote']")));
But there is no command called driver.
Sorry if this sounds stupid but my only wish is to learn!

A: The 'driver' here is an instance standing for browser.
And you are finding elements by: browser.find_element_by...()
The steps of using selenium is actually same as the steps that you manually find elements on browser:

*

*open a browser and enter URL

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.python.org")

*find elements by either id, class, tag or compound of them:

elem = driver.find_element_by_css_selector("iframe[title='Fill Quote']")

Here is a doc for selenium of python.


text:
Q: Can we write $Bv_i$ in the form $\beta_1v_1+\beta_2v_2+\beta_3v_3+...\beta_nv_n$ where $\beta_1,\beta_2,..,\beta_n\in\Bbb R$? Let us consider a linear transformation $L:V\to V$
The matrix $A$ corresponds to $L$ in a certain basis $\{v_1,v_2,v_3,...,v_n\}$ of $V$.
If $AB=BA$, can we write $Bv_i$ in the form $\beta_1v_1+\beta_2v_2+\beta_3v_3+...\beta_nv_n$ where $\beta_1,\beta_2,..,\beta_n\in\Bbb R$ ? Why? [Where, $1\leq i\leq n$]
P.S: $A$ and $B$ are invertible $n\times n$ matrices

A: If $B$ is a matrix then $Bv_i$ does not make sense in general. Assuming you actually meant that $B : V \to V$ and $BL = LB$ (although this assumption is unnecessary).
Since $Bv_i \in V$, and $\{v_1, v_2, \ldots, v_n\}$ is a basis for $V$, then $Bv_i = \beta_1 v_1 + \cdots + \beta_n v_n$ for some $\beta_1, \ldots, \beta_n \in \mathbb{R}$ by the definition of basis.


text:
Q: Finding exact value from a comma separated string in PHP MySQL I have a product table which contains a field called 'categories' to save product related category ids as comma separated values. I am using regexp to search products from a category.
Assume there is record containing 4,24,1,31
my expression is,
..WHERE categories REGEXP ',?4,?'

but this returns both product of category 4 and 24
I just need to display only category 4.
Am I missing something?

A: Use
WHERE categories REGEXP "(^|,)4(,|$)"

This matches 4 if surrounded by commas or at the start/end of the string.
In your present version, both commas are entirely optional, so the 4 in 24 matches.


text:
Q: How to use excel macro to sort data with empty cell? Thanks so much for reading my questions. I tried to search the similar questions in the stackoverflow but failed to get the answer...thanks so much if you can help me.
My purpose here is to copy and paste the data from Sheets("Parts") to Sheets("Summary"), and then sort by A column, ignoring the empty cell.
A1: 2.1

A2:

A3: 1.1

A4: 1.2

After sorting :
A1: 1.1

A2: 1.2

A3: 2.1

A4:

The macro is success in the Macro builder but then failed in the worksheet (First row empty). Indeed I try to not copying the empty cell with "SkipBlanks" but not functional...
Sub IEMacro()
Dim Lastcell As Range

Sheets("Parts").Range("A3:A300").Copy

With Sheets("Summary")
Set Lastcell = .Range("A65536").End(xlUp)
.Range("A2", Lastcell).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,     SkipBlanks:=True, Transpose:=False
.Range("A2", Lastcell).Sort Key1:=ActiveCell, Order1:=xlAscending, Header:=xlGuess
End With

A: In that case you need to select complete range till the last column of your data then sort it to ascending order, fianlly go with the auto filter.

Sub sort()
'selecting complete range change it as required
    Range("A1:O12").Select
' Replace the sheet name with yours
    ActiveWorkbook.Worksheets("Sheet1").sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet1").sort.SortFields.Add Key:=Range("A1"), _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet1").sort
    'sorting complete range change it as required
        .SetRange Range("A1:O11")
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

A: This should apply the sorting key properly :
Sub IEMacro()
Dim LastCell As Range

Sheets("Parts").Range("A3:A300").Copy

With Sheets("Summary")
    Set LastCell = .Range("A" & .Rows.count).End(xlUp)
    .Range("A2").PasteSpecial Paste:=xlPasteValues, _
                                        Operation:=xlNone, _
                                        SkipBlanks:=True, _
                                        Transpose:=False
    With .Sort
        .SortFields.Clear
        .SortFields.Add Key:=Sheets("Summary").Range(Sheets("Summary").Range("A1"), LastCell), _
                        SortOn:=xlSortOnValues, _
                        Order:=xlAscending, _
                        DataOption:=xlSortNormal
        .SetRange Sheets("Summary").Range(Sheets("Summary").Range("A1"), LastCell)
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End With

End Sub


text:
Q: How to reconnect using Pool in nodejs' promise-mysql if the connection went down? I am employing  promise-mysql NodeJs library to make awaitable operations against a MySQL server.
Presently I have a simple config:
 let pool = await mysql.createPool(dbConfig);
 let connection = await pool.getConnection();

 /// after the connection is made on the program start, once,
 /// some querying using the connection follows

However, just one connection seems to get disconnected. Question: how to implement the automatic handling of a disconnect and bringing up a subsequent new connection if current one was dropped?

A: This is working solution for me
pool.getConnection((err, connection) => {
  if (err) {
    console.log('Error while connecting ', err)
  } else {
    if (connection) connection.release()
    console.log('Database Connected Successfully!')
  }
})

Replace this let connection = await pool.getConnection(); with above code. And execute your queries with pool and not with the connection. So, if your single connection went down or is busy, then your query will be executed with another connection from pool.


text:
Q: Trying to insert another span tag before another Well, i'm trying to insert a span tag before another one to act like an ID of it depending on the other spans value. There are severall of these spans with an specific classname. So im looping thru every single one of them to edit one at the time. But the result I'm getting is just that one span is getting inserted to the top span, or no span is inserted.
I've tried using to just att the "id" to inneHTML like "A-"+class.innerHTML. But that gave same result.

ÄN:1023

function arendebokstav() {

  var nummerid = document.getElementsByClassName("nummer");
  var bokstavid = '';
  for (var i = 0; i < nummerid.length; i++) {
    if (nummerid[i].textcontent <= 999) {
      bokstavid = 'A-';
      nummerid[i].insertBefore(bokstavid, nummerid[i])
    } else if (nummerid[i].textcontent <= 1999) {
      bokstavid = 'B-';
      nummerid[i].insertBefore(bokstavid, nummerid[i])
    } else if (nummerid[i].textcontent <= 2999) {
      bokstavid = 'C-';
      nummerid[i].insertBefore(bokstavid, nummerid[i])
    } else if (nummerid[i].textcontent <= 3999) {
      bokstavid = 'D-';
      nummerid[i].insertBefore(bokstavid, nummerid[i])
    } else if (nummerid[i].textcontent <= 4999) {
      abokstavid = 'E-';
      nummerid[i].insertBefore(bokstavid, nummerid[i])
    }
  }
}

No error message getting shown. I want it to write out "A-999" and "B-1000" and so on but all I get is "999" "1000" etc etc

A:

<!DOCTYPE html>

1000

Click the button to insert a word before text.

<button onclick="myFunction('mySpan', 'A-')">Try it</button>

A: I edited your code as follows:

function arendebokstav() {
  let mySpan = document.getElementById('mySpan');
  let nummerid = document.getElementsByClassName("nummer");

  for (let i = 0; i < nummerid.length; i++) {
    let letter;
    if (nummerid[i].textContent <= 999) {
        letter = 'A-'
    } else if (nummerid[i].textContent <= 1999) {
        letter = 'D-'
    } else if (nummerid[i].textContent <= 2999) {
        letter = 'C-'
    } else if (nummerid[i].textContent <= 3999) {
        letter = 'D-'
    } else if (nummerid[i].textContent <= 4999) {
        letter = 'E-';
    }

    let newItem = document.createElement("span");
    newItem.classList.add("newcssclass");
    newItem.textContent = letter;

    mySpan.insertBefore(newItem, mySpan.childNodes[0])
  }
}

arendebokstav();
.newcssclass {
     color: red;
 }

    3000

Here's what you've missed:

*

*insertBefore needs to append a node to the parent.

For a more detailed explaination consult the doc


text:
Q: What is messaging domain in JMS I am learning JMS from documentation: http://docs.oracle.com/javaee/6/tutorial/doc/bncdr.html and came across this statement:

The JMS API minimizes the set of concepts a programmer must learn in
  order to use messaging products but provides enough features to
  support sophisticated messaging applications. It also strives to
  maximize the portability of JMS applications across JMS providers in
  the same messaging domain.

I don't understand this. What are JMS providers and what is messaging domain here?

A: JMS providers are 3rd parties that provide implementations of the JMS specification such as IBMMQ & RabbitMQ.
The messaging domain in this case will be the processing of messages as determined by the JMS specification.

A: I know it is old but people who come here searching for answer it helps, here
good article explained nicely. To answer to the question "domain" is very generic in this context. to say in the world of messaging


text:
Q: Select rows that have columns equal values in laravel 5.2 I'm new user of Laravel 5.2
For example i have data rows something like this:
mytable
-------------------------------
url          |  ip
-------------------------------
google.com   |  11.44.180.149       <-----
msn.com      |  11.44.180.149
google.com   |  11.44.180.149       <-----
yahoo.com    |  11.44.180.149
google.com   |  11.44.180.149       <-----

I want select all rows that 2 or 3 columns value their is equal and delete rows equal that it's more than one
For example convert to this:
mytable
-------------------------------
url          |  ip
-------------------------------
google.com   |  11.44.180.149       <-----
msn.com      |  11.44.180.149
yahoo.com    |  11.44.180.149

Guys i'm so sorry because can't speak English very well.
Thank you

A: You can use groupBy() method with Eloquent:
MyTable::groupBy('ip')->get();

Or query builder:
DB::table('mytable')->groupBy('ip')->get();

A: You need to first select the columns you want to check, then do a DISTINCT.
DB::table('mytable')->select('url','ip')->Distinct()->get();

This should only include one of each matching set.

A: If you try this,
$myTable = MyTable::groupBy('url', 'ip')
                ->get(['url', 'ip']);

or
$myTable = DB::table('mytable')->groupBy('url', 'ip')
                ->get(['url', 'ip']);

Please check this code.

A: try this
  $query = DB::table('MyTable');
     $query->whereIn('ip', function($query) {
            $query->select('ip')
                ->from('MyTable')
                ->groupBy('ip')
                 ->having(DB::raw('count(*)'),'>',1);
        });
         $user=$query->get();
         dd($user);


text:
Q: Find all the columns which are having null values I am novice in sql , I'm trying to find all the columns which are having null values in my database. i have searched a lot answers but not satisfied

A: Here is the example with MS SQL with later version:
declare @col varchar(255), @cmd varchar(max)

DECLARE getinfo cursor for
SELECT c.name FROM sys.tables t JOIN sys.columns c ON t.Object_ID = c.Object_ID
WHERE t.Name = 'YOUR_TABLE_NAME'

OPEN getinfo

FETCH NEXT FROM getinfo into @col

WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @cmd = 'IF NOT EXISTS (SELECT top 1 * FROM YOUR_TABLE_NAME WHERE [' + @col + '] IS NOT NULL) BEGIN print ''' + @col + ''' end'
    EXEC(@cmd)

    FETCH NEXT FROM getinfo into @col
END

CLOSE getinfo
DEALLOCATE getinfo

A: you can try this
SELECT cols
FROM table
WHERE cols IS NULL


text:
Q: How can I associate data - a string, integer or enum member - with a Gtk::ComboBoxText item? I am using gktmm 3.0 on an Ubuntu 12.04 box with the default GCC toolchain.
In the C# world, the ComboBox class has a ComboxBox.item[n].value property, which allows you to associate each item in the comboBox with data.
I am looking for something similar in the Gtk::ComboBoxTextclass. How can I associate data - a string, integer or enum member for example - with a particular Gtk::ComboBoxTextitem?
I know that many frameworks provide a genericdata pointer on widgets for such use, as this is quite a common need.
Is there something in Gtk::ComboBoxText class or one of its parent classes that might allow me accomplish this, or do I need to set up such an association myself, using a map or other associative collection?

A: The Gtk::ComboBoxText append, insert() and prepend() methods allows you to specify an ID string as well as the human-visible text. For instance:
https://developer.gnome.org/gtkmm/stable/classGtk_1_1ComboBoxText.html#a19e80f4e451e23d2c00d3fb11023f9f2
But it would be clearer and more type-safe to use Gtk::ComboBox and define an actual underlying model that contains the associated data. This example uses an int, but you could use other types or use more columns:
https://developer.gnome.org/gtkmm-tutorial/stable/combobox-example-full.html.en


text:
Q: Order by ou filtro em join Sql Server É possível utilizar order by ou algum filtro em inner join ou left join ou estou tentando fazer isso de forma errada.
Eu preciso trazer em uma consulta uma coluna que está em uma tabela filha, mas eu preciso que seja a coluna do registro mais recente dos registros da tabela filha.
Para resolver esse problema eu fiz um sub-query e resolveu bem o problema, mas eu queria saber se teria como fazer um join com top 1 e ordenado por uma coluna.

A: Abaixo tem um script de como fazer o que gostaria, porem se conseguir postar o que fez para entender melhor ficará mais claro para todos.
Select TOP 10 TB1.COLUNANOVA
from Tabela1 TB1
   inner join Tabela2 TB2
      on TB1.CODPRIMARIO = TB2.CODIGOPRIMARIO
where TB1.COLUNAANTIGA = "resultado"
order by TB1.COLUNANOVA

A: O que você quer não pode ser resolvido com Cross Apply? Segue um exemplo de uso, só não está ordenando, mas aí você edita para o que se aplica ao seu caso.
SELECT  Employee.EmployeeId ,
        FirstName ,
        LastName ,
        PhoneType ,
        PhoneNumber
FROM    dbo.Employee
        CROSS  APPLY ( SELECT TOP 1
                                PhoneNumber ,
                                PhoneType ,
                                EmployeeId
                      FROM      dbo.PhoneNumber
                      WHERE     PhoneType = 4
                                AND EmployeeId = Employee.EmployeeId ) p
ORDER BY EmployeeId;

A: Bom dia!
Acredito que poderia fazer assim também, ou seja, colocar um TOP 1 em um select como se fosse uma coluna, com o where = a coluna de fora. Sendo assim vai trazer o último registro de cada item consultado.
Select

CT1.coluna_1_tabela_1,
(select TOP 1 CT3.coluna_1_tabela_3 from Tabela3 CT3 where CT3.coluna_1_tabela_3 = CT1.coluna_1_tabela_1 order BY CT3.coluna_1_tabela_3 DESC) as Seu_resultado

from Tabela1 CT1
   INNER JOIN Tabela2 CT2
      on CT1.coluna_1_tabela_1 = CT2.coluna_1_tabela_2
where CT1.coluna_10_tabela1 = 'XYZ'
order by CT1.coluna_1_tabela_1


text:
Q: How can we solve this lifetime error occuring when conditionally returning a string slice? The desired behaviour is if you can cut off 4 bytes cut and return 4 bytes, else if you can cut off 2 bytes cut and return 2 bytes, else return an error.
The methods cut, cut_alternative and cut_alternative_1 try to achieve this. The compiler error messages are listed below.
Why do all of these example methods fail to compile? In cut_alternative_1 the borrows are separated from each other while the error message is the same.
Can you give a workaround?
Playground link
struct StrWrapper<'s> {
    content: &'s str,
}

impl<'s> StrWrapper<'s> {
    fn cut(&mut self) -> Result<&str, ()> {
        self.cut4()
            .or(self.cut2())
    }

    fn cut_alternative(&mut self) -> Result<&str, ()> {
        if let Ok(part) = self.cut4() {
            Ok(part)
        } else if let Ok(part) = self.cut2() {
            Ok(part)
        } else {
            Err(())
        }
    }

    fn cut_alternative_1(&'s mut self) -> Result<&'s str, ()> {
        {
            let part = self.cut4();
            if part.is_ok() {
                return part;
            }
        }
        {
            let part = self.cut2();
            if part.is_ok() {
                return part;
            }
        }
        Err(())
    }

    fn cut2(&mut self) -> Result<&str, ()> {
        if self.content.len() >= 2 {
            let part = &self.content[..2];
            self.content = &self.content[2..];
            Ok(part)
        } else {
            Err(())
        }
    }

    fn cut4(&mut self) -> Result<&str, ()> {
        if self.content.len() >= 4 {
            let part = &self.content[..4];
            self.content = &self.content[4..];
            Ok(part)
        } else {
            Err(())
        }
    }
}

error[E0499]: cannot borrow `*self` as mutable more than once at a time
   --> src/parser.rs:210:17
    |
208 |       fn cut(&mut self) -> Result<&str, ()> {
    |              - let's call the lifetime of this reference `'1`
209 |           self.cut4()
    |           ----
    |           |
    |  _________first mutable borrow occurs here
    | |
210 | |             .or(self.cut2())
    | |_________________^^^^_______- returning this value requires that `*self` is borrowed for `'1`
    |                   |
    |                   second mutable borrow occurs here

error[E0499]: cannot borrow `*self` as mutable more than once at a time
   --> src/parser.rs:216:34
    |
213 |     fn cut_alternative(&mut self) -> Result<&str, ()> {
    |                        - let's call the lifetime of this reference `'1`
214 |         if let Ok(part) = self.cut4() {
    |                           ---- first mutable borrow occurs here
215 |             Ok(part)
    |             -------- returning this value requires that `*self` is borrowed for `'1`
216 |         } else if let Ok(part) = self.cut2() {
    |                                  ^^^^ second mutable borrow occurs here

error[E0499]: cannot borrow `*self` as mutable more than once at a time
   --> src/parser.rs:230:24
    |
207 | impl<'s> StrWrapper<'s> {
    |      -- lifetime `'s` defined here
...
224 |             let part = self.cut4();
    |                        ---- first mutable borrow occurs here
225 |             if part.is_ok() {
226 |                 return part;
    |                        ---- returning this value requires that `*self` is borrowed for `'s`
...
230 |             let part = self.cut2();
    |                        ^^^^ second mutable borrow occurs here

@Shepmaster commented a link to a similar question: Returning a reference from a HashMap or Vec causes a borrow to last beyond the scope it's in?
This question differs in two ways:

*

*There are multiple mutable borrows instead of one unmutable and one mutable borrow.

*I am unable to apply the workarounds in the answer to this problem right now. A workaround would be much appreciated.

A: The secret sauce in the HashMap solution is the use of contains_key(), which returns a bool that just doesn't carry the lifetime baggage. Likewise, the Vec solution involves using indices instead of slices in strategic places.
In your case the equivalent adaptation requires changing the signatures cut4() and cut2() to return Result<Range<usize>, ()>. Then you'd be able to write something like this:
fn cut(&mut self) -> Result<&str, ()> {
    if let Ok(part) = self.cut4() {
        Ok(&self.content[part])
    } else if let Ok(part) = self.cut2() {
        Ok(&self.content[part])
    } else {
        Err(())
    }
}

fn cut2(&mut self) -> Result<Range<usize>, ()> {
    if self.content.len() >= 2 {
        let part = 0..2;
        self.content = &self.content[2..];
        Ok(part)
    } else {
        Err(())
    }
}

// likewise for cut4

Playground
Another option would be to use interior mutability and make all of the functions accept &self:
use std::cell::Cell;

struct StrWrapper<'s> {
    content: Cell<&'s str>,
}

impl<'s> StrWrapper<'s> {
    fn cut(&self) -> Result<&str, ()> {
        if let Ok(part) = self.cut4() {
            Ok(part)
        } else if let Ok(part) = self.cut2() {
            Ok(part)
        } else {
            Err(())
        }
    }

    fn cut2(&self) -> Result<&str, ()> {
        if self.content.get().len() >= 2 {
            let part = &self.content.get()[..2];
            self.content.set(&self.content.get()[2..]);
            Ok(part)
        } else {
            Err(())
        }
    }

    // likewise for cut4
}

Playground (I was honestly surprised that this compiled, I've never tried to put a reference inside a Cell before.)
Finally, if neither of the above options is palatable for you, there is always unsafe:
fn cut(&mut self) -> Result<&str, ()> {
    // Safety: slices returned by cut4() and cut2() must live at least as
    // long as `self` (because the lifetime of `&str` returned is tied to the
    // lifetime of `&self`). This is the case because cut2() and cut4() are
    // bound by their signatures to return sub-slices of `self`, and we don't
    // modify `self` between a successful call to cut*() and the return.
    unsafe {
        if let Ok((ptr, len)) = self.cut4().map(|s| (s.as_ptr(), s.len())) {
            Ok(std::str::from_utf8(std::slice::from_raw_parts(ptr, len)).unwrap())
        } else if let Ok((ptr, len)) = self.cut2().map(|s| (s.as_ptr(), s.len())) {
            Ok(std::str::from_utf8(std::slice::from_raw_parts(ptr, len)).unwrap())
        } else {
            Err(())
        }
    }
}

Playground
If the unsafe voodoo looks scary, good - it should. The compiler won't help you if you slip up and make a mistake, so that kind of thing should be used only as a last resort. I think the above code is correct because it basically works the same way as the range version, it just converts the slices to their constituent parts after they've been created. But any time someone refactors the code you'll be wondering if a crash or, worse, a silent UB is lurking around the corner.
In case it's not already obvious, my recommendation would be approach #1.


text:
Q: DATE_FORMAT in query generate this error: Notice: Trying to access array offset on value of type bool in I've been trying to figure out how to fix this for about two hours, except I can't. Yesterday everything worked well despite this error but today without me touching anything it does not work anymore.
This is my code:
$getprod_t = $bdd->prepare("SELECT id, author, item, qte, type,
                                DATE_FORMAT(datee, \'%d/%m/%Y - %H:%i\') AS datee
                            FROM registre
                            WHERE author=:author
                            AND item=:item
                            AND type=1");
$getprod_t->execute([
    'author' => $_SESSION['username'],
    'item' => 3
]);
$prod_t = $getprod_t->fetch();
echo $prod_t['qte'];

Today, When I remove the DATE_FORMAT it works again, except that yesterday I didn't need to remove it, everything worked fine.
Sincerely,

A: there is no  need to escape the single quotes
$getprod_t = $bdd->prepare("SELECT id, author, item, qte, type, DATE_FORMAT(datee, '%d/%m/%Y - %H:%i') AS datee FROM registre WHERE author=:author AND item=:item AND type=1");
            $getprod_t->execute([
                'author' => $_SESSION['username'],
                'item' => 3
            ]);
            $prod_t = $getprod_t->fetch();
            echo $prod_t['qte'];


text:
Q: Windows 10 scheduled php task not working I've made a Weather script that downloads the weather forecast from worldweatheronline.com and copy it to my database. My local CakePhp Shell / script is working correctly when I execute it via Git Bash.
Now I want to automatically update the weather script on my local machine with a Windows 10 task. My task seems to run (I've got a quick pop-up on my screen every five minutes), but the php script doesn't do anything.
My task settings are:
Tab 'General'

*

*Use the following useraccount to execute the task: sam_c

*Execute only when the user is logged in

Tab 'Triggers'

*

*Dayly

*Start 13/04/2017 21:32:00

*Repeat every: 5 min.

*During: 1 day

Tab 'Action'

*

*Action: Start program

*Program/script: C:\xampp\php\php.exe

*Parameters (optional): -f D:\Websites\BellewaerdeFun 2017\03 - Online\app\Console\Command\WeatherShell.php

Tab 'Conditions', 'Settings' and 'History'

*

*No changes

I guess the problem is in the tab 'Action'. I already tried to changed the parameters field to:

*

*-f D:/Websites/BellewaerdeFun 2017/03 - Online/app/Console/Command\WeatherShell.php

*php -f D:\Websites\BellewaerdeFun 2017\03 - Online\app\Console\Command\WeatherShell.php

*...

Nothing seems to work. When I check the task history, it tells me that the task is completed. Liar :)


text:
Q: How to use an unnamed type implementing a trait in a closure's return type? Closures are unnamed types in rust, so you have to use impl Fn to return one. Is it possible to also use an unnamed type for the closure's return type?
This is what I'm trying to do:
use actix_web::{services, web, Resource, dev::HttpServiceFactory};

pub fn service_factory() -> impl Fn() -> (impl HttpServiceFactory + 'static) + Clone + Send + 'static {
    || services![web::resource("/a"), web::resource("/b")]
}

But the compiler disallows (impl HttpServiceFactory + 'static) and tells me that impl Trait is only usable in function return values, so I'm instead forced to do this:
use actix_web::{services, web, Resource};

pub fn service_factory() -> impl Fn() -> (Resource, Resource) + Clone + Send + 'static {
    || services![web::resource("/a"), web::resource("/b")]
}

which works, but is a pain to use; also, if the type I'm returning from the closure was truly unnamed (such as another closure), this workaround wouldn't be possible at all.
What's the idiomatic way to write this code?
I should also mention that Box<dyn HttpServiceFactory + 'static> doesn't work for me because some function somewhere doesn't expect boxed trait objects, so the type has to be known.

A: You can make a helper trait "alias" with an associated type:
trait HttpContextFactoryFn: Fn() -> Self::Factory {
    type Factory: HttpContextFactory + 'static;
}

impl<F, T> HttpContextFactoryFn for F
where
    F: ?Sized + Fn() -> T,
    T: HttpContextFactory + 'static,
{
    type Factory = T;
}

This trait is equvialent to Fn() -> (impl HttpContextFactory + 'static), except it's one that can actually be expressed in Rust today. That means that you can use this in your function signature:
pub fn service_factory() -> impl HttpContextFactoryFn + Clone + Send + 'static {
    || services![web::resource("/a"), web::resource("/b")]
}


text:
Q: How do I monitor a subset of logins with sysadmin role to find out if they are still in use? How do I monitor a certain subset of logins that have the sysadmin role to find out if they are still in use.  I would like to remove the logins but, do not want to run the risk of disabling them if they are being used.
I found the following code on mssqltips.com that almost works but, it generated about 5 million records a day on the test server and I do not know why.  Does anyone have another solution or know how to fix this code so it only the table when a login with sysadm role logs into the server?
CREATE TABLE dbo.AuditSysAdminLogin
(AuditEventId INT IDENTITY(1,1) NOT NULL,
EventTime DATETIME NOT NULL,
ServerLogin NVARCHAR(100) NOT NULL,
CONSTRAINT PK_AuditSysAdminLogin PRIMARY KEY CLUSTERED (AuditEventID));
GO

USE master;
GO

CREATE TRIGGER trigLogon_CheckForSysAdmin
            ON ALL SERVER
            FOR LOGON
            AS
    BEGIN
    IF EXISTS (
        SELECT sp.principal_id
            FROM sys.server_role_members srm
                    JOIN sys.server_principals sp
                    ON srm.member_principal_id = sp.principal_id
            WHERE role_principal_id = (
            SELECT principal_id
                FROM sys.server_principals
                WHERE NAME = 'sysadmin')
                AND ORIGINAL_LOGIN() = sp.NAME)
        BEGIN
        INSERT INTO DBAWork.dbo.AuditSysAdminLogin
            (EventTime, ServerLogin)
                VALUES
            (GETDATE(), ORIGINAL_LOGIN())
        END;
    END;
GO

A: Your script looks like it would work as designed.  Sounds like you actually have sysadmin accounts logging in 5 million times per day.  If you don't need to record every single login, and you're okay with just storing the most recent login time, you can change your trigger to perform a merge like the following (the table should be truncated before implementing this):
MERGE AuditSysAdminLogin AS audit
USING (SELECT sp.principal_id
        FROM sys.server_role_members srm
        JOIN sys.server_principals sp
        ON srm.member_principal_id = sp.principal_id
        WHERE role_principal_id = (
        SELECT principal_id
        FROM sys.server_principals
        WHERE NAME = 'sysadmin')
        AND ORIGINAL_LOGIN() = sp.NAME) AS NewLogin
ON NewLogin.Principal_Id = audit.ServerLogin
WHEN MATCHED THEN UPDATE SET audit.EventTime = GETDATE()
WHEN NOT MATCHED THEN INSERT (ServerLogin, EventTime) VALUES (Principal_ID, GETDATE());

If you'd like to capture login counts, you could also add a BIGINT field and have the merge statement increment it.
Note - running this type of trigger could have a dramatic impact on your SQL Server's performance.  I don't recommend running it long-term.


text:
Q: iOS6 + Storyboard + Seem to be getting doubles I have been having problems with my ios app ever since the upgrade to 6.  I'm sure that I have something configured wrong that up until now was hidden.
I am utilizing storyboard and have as my first view as just a regular old vanilla view controller.  This is my login page.  When you click on the "login" button it segues to "Tab Bar Controller" that has a bunch of tabs inside it including a tab that has a "logout" button.
EDIT: It's important to not that the login View Controller pushes a "MODAL" segue to the Tab Bar Controller.
The "logout" button will run a
[self dismissModalViewControllerAnimated:YES];

that sends it back to the login view.  The user may then go ahead and relog in and so on...
The problem is that it seems as if every single time I go from login to the tab view I'm getting some duplicates.  The reason I know this is because in one of the tab views I have a
    [[NSNotificationCenter defaultCenter] removeObserver:self];

// Register observer to be called when download of data is complete
[[NSNotificationCenter defaultCenter] removeObserver:self name:OBJECTS_LOADED_NOTIFICATION object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
                                        selector:@selector(coreDataViewController_downloadDataComplete:)
                                            name:OBJECTS_LOADED_NOTIFICATION
                                          object:nil];

Which is supposed to remove any observers already on the page and just add new ones.  However it just keeps adding in observers over and over and over.  Which leads me to believe that there are multiple versions of the page somewhere in memory.
Can someone PLEASE help!?  I have been trying to solve this thing for 4 straight days now with no results.  I'm sure it's something insanely stupid but I can't for the life of me figure out what.
Thanks
Matt
EDIT:
Per request I have added more code... :-)  I figured it was easier to just publish the whole project rather then post bits and pieces of it.
https://github.com/MCKRUZ/Iphone

A: Ok I solved / circumvented this problem.  Basically it is still recreating the VC's every single time I logout and log back in, however I reworked the code so that it doesn't matter if it does that since the object context I'm using is in a service and not on the page.
Still, it's odd behavior that apple wouldn't remove those instances of the VC's that aren't being used....I miss pageDidUnload...


text:
Q: Nested flexbox align-items center specific content I'm trying to build the simple form below.

I'm using flexbox and having trouble aligning the textarea properly. align-items: center aligns the whole div. I've tried taking the textarea div out and am having trouble aligning the textarea relative to the above flexbox container. How can I acheive the above textbox position while having the x, photo, name and aligned centered.
fiddle

.container {
  display: flex;
}
.content {
  flex-grow: 1;
}
textarea {
  width: 100%;
}
img {
  border-radius: 30px;
  margin: 0 10px;
}

    x

Brad

Boston

    <textarea></textarea>

A: CSS Grid
For a simple and efficient solution use Grid Layout. No need to set any fixed widths.

.container {
  display: grid;
  align-items: center;
  grid-template-columns: auto auto 1fr;
  grid-template-rows: auto auto;  /* optional; implicit rows are auto by default */
  grid-template-areas:  "close  avatar   name    "
                        "   .     .     textbox ";
}

.container > *:nth-child(1) { grid-area: close; }
.container > *:nth-child(2) { grid-area: avatar; }
.container > *:nth-child(3) { grid-area: name; }
.container > *:nth-child(4) { grid-area: textbox; }

img {
  vertical-align: top; /* remove descender space applied to inline-level elements */
  border-radius: 30px;
  margin: 0 10px;
}
.container > * {
  border: 1px dashed red;
  box-sizing: border-box;
}

x

Brad

Boston

  <textarea></textarea>

Flexbox
If you want to stick with flexbox, here's one method, but it requires more details to render properly.

*

*Allow the container to wrap items (flex-wrap: wrap)

*Force the textarea onto its own row (e.g. flex-basis: 100%)

*Define a width for the "x" and the avatar

*Subtract the width of the x & avatar from the textarea width

*Left-align the textarea with an auto margin

.container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.container > div:nth-child(-n + 2) {
  flex: 0 0 50px;
  text-align: center;
}

.container > div:nth-child(3) {
  flex: 1;
}

img {
  display:block;
  border-radius: 30px;
  margin: 0 10px;
}

textarea {
  margin-left: auto;
  flex: 0 0 calc(100% - 120px);
}

.container > * {
  border: 1px dashed red;
  box-sizing: border-box;
}

x

Brad

Boston

  <textarea></textarea>

A: You can try something like this:

.container {
  display: flex;
  align-items:center;
  flex-wrap:wrap; /* we force a wrap so textarea is in the next line*/
}
.content {
  flex-grow: 1;
}
textarea {
  flex-basis: 100%;
  margin-left:80px; /* use margin to adjust, change this value depending the icon and image width */
}
img {
  border-radius: 30px;
  margin: 0 10px;
}

    x

Brad

Boston

  <textarea></textarea>


text:
Q: Get title of post image is attached to So I found this post: Find the post an attachment is attached to and implemented Chip's suggestion but having a weird outcome. I am trying to pull the title of the post that the specific image is attached to. This is my query:
<?php
    $args = array(
        'post_type' => 'attachment',
        'posts_per_page' => -1,
        'post_status' => 'any',
        'post_parent' => null,
        'tax_query' => array(
            array(
                'taxonomy' => 'post_tag',
                'field' => 'slug',
                'terms' => 'logo'
            )
        )
    );

    $attachments = get_posts( $args );
    foreach ( $attachments as $image ) {
        // Get the parent post ID
        $parent_id = $image->post_parent;
        // Get the parent post Title
        $parent_title = get_the_title( $parent_id );
        // Get the parent post permalink
        $parent_permalink = get_permalink( $parent_id );
    }

    if ( $attachments ) {
        foreach ( $attachments as $post ) {

            $logoimg = wp_get_attachment_image($post->ID, 'Work Gallery');

This is the line where I am calling the title: echo ' ' . $parent_title . ' ';
This kind of works but it is outputting 1 post title in particular and for all the images on the page. Any thoughts as to why its not dynamically picking up each images associated post title?
Thanks!

A:
This kind of works but it is outputting 1 post title in particular and for all the images on the page. Any thoughts as to why its not dynamically picking up each images associated post title?

$attachments = get_posts( $args );
foreach ( $attachments as $image ) {

    // Get the parent post ID
    $parent_id = $image->post_parent;

    // Get the parent post Title
    $parent_title = get_the_title( $parent_id );

    // Get the parent post permalink
    $parent_permalink = get_permalink( $parent_id );
}

This code loops over each image. Let's debug it by hand.
As an example, let's assume there are 3 images.
The first image has a parent ID of 1, a title of "Foo" and link to that post,
The second image has a parent ID of 2, a title of "Bar" and link to that post,
The third image has a parent ID of 3, a title of "Baz" and link to that post,
So, the first time through the loop:
$parent_id is set to 1,
$parent_title is set to Foo,
$parent_permalink is set to the link to Foo.
The second time through the loop:
$parent_id is set to 2,
$parent_title is set to Bar,
$parent_permalink is set to the link to Bar.
All the data for the post "Foo" is overwritten with the data for post "Bar". Why? Because the code does not save that other data before writing the new data to $parent_id, $parent_title and $parent_permalink.
On the third trip through the loop:
$parent_id is set to 3,
$parent_title is set to Baz,
$parent_permalink is set to the link to Baz.
All the data for the post "Bar" is overwritten with the data for post "Baz".
When this loop is done, the $parent_id, $parent_title and $parent_permalink variables only hold whatever data is in the last item of the $attachments array. So, the reason that only the last parent post is being used is because that is what the code told PHP to do. The code says, "Throw away those other values."
What you probably want to do is something like this:
$images = get_posts( $args );

if ( $images ) {

    foreach ( $images as $image ) {

        // Get the parent post ID
        $parent_id = $image->post_parent;

        // Get the parent post Title
        $parent_title = get_the_title( $parent_id );

        // Get the parent post permalink
        $parent_permalink = get_permalink( $parent_id );

        $logoimg = wp_get_attachment_image( $image->ID, 'Work Gallery' );


text:
Q: Scope of shared pointer in this clippet   void RecHouse::createRec( const std::string& SourceId,
                                           const std::string& Name,
                                           const std::string& Location,
                                           const std::string& Description,
                                           const std::string& Address,
                                           const std::string& Content,
                                           const std::string& MaxTime,
                                           std::string& RecToken,
                                           bool defRec )
    {
       std::shared_ptr<Recording> rec = std::make_shared<Recording>(
            Recording( SourceId, Name, Location,
                       Description, Address, Content,
                       MaxTime, m_EventList,
                       m_eventServiceResource ));

        LOG("finished: create rec object");

        m_eventServiceResource->GetEventProducerManager()->RegisterEventProducer( std::weak_ptr<Recording>(recording) );
        RecordingToken = recording->getToken();
        if ( m_RecordingList.count( RecordingToken ) )
        {
            throw onvif_exception( BadConfiguration );
        }
        m_RecordingList[ RecordingToken ] = recording;
        updateFindRecordings();
        m_serialize.serialize( this );
        LOG ("fn end : create rec object");
    }

What is the scope of the shared pointer rec ? does it finish by the end of the function createRec because it is not transferred to another shared pointer ? It is sent to RegisterEventProducer as an argument but only as a weak pointer. This weak pointer is further stored in a list of weak pointers and is not getting put into a shared pointer for use elsewhere.

A: Yes, the shared pointer goes out of scope and the weak pointer, as expected, does not extend the lifetime. Here's one way to test this:
#include <iostream>
#include <memory>

int main() {
  std::weak_ptr<int> weak_rec;
  {
    std::shared_ptr<int> rec = std::make_shared<int>(200);
    weak_rec = rec;
  }
  std::cout << *weak_rec.lock() << "\n";
  return 0;
}

Compile & run valgrind
#> g++ -g test.cc
#> valgrind ./a.out

Output
==767972== Invalid read of size 4
==767972==    at 0x401257: main (test.cc:10)
==767972==  Address 0x0 is not stack'd, malloc'd or (recently) free'd


text:
Q: Inherit/Set the BackgroundView for RadioGroup generated DialogViewController TableView (MonoTouch.Dialog) I want to use MonoTouch.Dialog RadioElements for selecting data and it has to have a UIImageView for the TableView BackgroundViews.
I can set the BackgroundView on the initial DialogViewController's TableView so no problem there, but the TableView's generated for each RadioGroup has the default grey background image and I can't seem to find a way to change them to the same background style as the initial TableView.
Is it possible to change the generated TableView's BackgroundView (the TableView's generated for each RadioGroup) without having to go and modify the MonoTouch.Dialog source?
Thanks in advance.

A: AFAIK you'll need to create your own Element. But the good news is that's pretty easy to do, e.g.:
public class TransparentRootElement : RootElement {

    // add required .ctors

    public override UITableViewCell GetCell (UITableView tv)
    {
        var cell = base.GetCell (tv);
        cell.BackgroundColor = UIColor.Clear;
        return cell;
    }
}

Then you only have to use this new TransparentRootElement type where you create the RadioGroup.

A: public class CustomRootElement : RootElement
{
    public CustomRootElement(string caption, RadioGroup group) : base(caption, group)
    {

    }
    protected override MonoTouch.UIKit.UIViewController MakeViewController()
    {
        DialogViewController result = (DialogViewController)base.MakeViewController();
        // set the background here
        result.TableView.BackgroundColor = UIColor.ScrollViewTexturedBackgroundColor;

        return result;
    }

}


text:
Q: Computing some closed trajectories of meromorphic quadratic differentials I'm learning about meromorphic (!) quadratic differentials on Riemann surfaces, and would like to determine the closed trajectories [EDIT: I mean closed geodesics, not just closed trajectories; trajectories seems to usually mean horizontal geodesics] in some simple cases. I'll give an example that I think I understand, to illustrate what I'm trying to do, and another example that I don't quite understand and for which I'd like advice. Both examples are on the Riemann sphere $\mathbf{CP}^{1}=\mathbf{C} \cup \infty$, where $z$ is a coordinate on $\mathbf{C}$.
Example 1: Consider the meromorphic quadratic differential $q=dz^{2}/z^{2}$, which evidently has a pole of order $2$ at $0 \in \mathbf{C}$ and also at $\infty$. It's easy to check that the horizontal distribution associated to $q$ is just radial lines coming out of $0$, and that the vertical distribution is concentric circles centred at $0$. In particular, those concentric circles give closed geodesics (in fact, trajectories).
Moreover, I claim there are no other closed geodesics. Now, a piece of a closed trajectory through a point $z_{0}$ is the image of a straight line under the inverse of a coordinate defined in a neighbourhood of $z_{0}$. That's well-defined, because the coordinates are well-defined up to translation and multiplication by $-1$, and that doesn't change which lines are straight. Now to compute that coordinate, we take a square root of the quadratic differential and integrate. In a small neighbourhood of $z_{0}$, that will give $\log(z)$ up to a constant, so the inverse will be $\exp(z)$, and the only lines that map to periodic geodesics under $z \mapsto \exp(z)$ are vertical.
Example 2: Consider the quadratic differential $q=dz^{2}/(1-z^2)$, which has poles of order $-1$ at $1$ and $-1$ and a pole of order $2$ at $\infty$. Playing the same game with coordinates, we find that (up to a shift of variable) the inverse of the local coordinate is given by $z \mapsto \sin(z)$ (inverse of contour integral of $dz/\sqrt{1-z^{2}}$). Evidently, horizontal lines map to periodic geodesics (in fact, trajectories) under $z \mapsto \sin(z)$, by the usual periodicity of the $sin$ function, and in fact, those seem to be the only lines that map to closed geodesics .
Are there any other periodic geodesics that I'm missing? Can I not see them by picking a single coordinate like this, but have to patch them together somehow? How to do so, if necessary?


text:
Q: How to cross-compile a working Windows Tk dll? I've found to my surprise that I can't cross-compile a working Windows Tk dll from the latest release source using the Linux mingw tools.  Compiling a working tclsh.exe was no problem.  The compiled tk86.dll complains that it can't find resource files compiled in and crashes.
According to the build commands echoed from the make process, the resources appear to have been built and included as expected.
On 64-bit Linux with mingw cross-compile tools installed, I cross-compile Tk 8.6.8:
In the win subdir:
$ ./configure --with-encoding=utf-8 --host=x86_64-w64-mingw32 --enable-threads --enable-64bit --with-tcl=/opt/tcl8.6.8/win
$ make tk86.dll

To test the result, on my Windows 10 computer I download the binary Tcl/Tk distribution from Thomas Perschak as recommended at https://www.tcl.tk/software/tcltk/bindist.html
I put my new-compiled tk86.dll in place of the downloaded one.
> tclsh86.exe
% package require Tk
% button .b
FindResource() failed for buttons bitmap resource, resources in tk_base.rc must be linked into Tk dll or static executable

The interpreter then crashes.
I don't know if this is a bug in Tk or its build tools, or a configuration oversight on my part.  Work requirements disallow me from using precompiled binaries, so this is a showstopper for me.  Any hints appreciated.


text:
Q: no "auto-generate release notes" button on github enterprise? i'm trying to setup a new gitHub enterprise repo and looking at using "releases". i wanted to try the auto generate release notes feature but I don't have the button that is shown here...
https://docs.github.com/en/repositories/releasing-projects-on-github/automatically-generated-release-notes
is this a problem with my version of github enterprise server (3.3.6), github enterprise server in general or something else i'm not doing?

A: Looks like it is available from 3.4 release onwards.
https://docs.github.com/en/repositories/releasing-projects-on-github/automatically-generated-release-notes


text:
Q: how to display an image from second page in dom pdf? I am new to dom pdf. I am loading footer image in all the pdf pages using DOM pdf.and banner image only in first page of pdf.
From second page i want to display another image in header part.
How can i achieve this?

A: The header and footer you use is DOM PDF are on every page the same. If you want to have different images on each page you can use your own css to archieve this.
If you only want page 1 to be different, you need to take a look [here].(dompdf: How to add header on every page except first?). That question is already treated.


text:
Q: Having maven repository without using any repository manager I am owner of OSS project, which is now using Maven. Since we use a lot of outdated (and not available on Maven) libraries I decided to use Repository Manager (Nexus) to make all this dependencies available.
My OSS uses Maven for building and dependencies management, but we never deploy any artifacts (end product is not library but an application). I usually put all new dependencies manually in public repository of my Nexus, so that other developers can get to it.
Now question is, do I really need to have Nexus running (I have resources problem on my virtual hosted machine, so Nexus needs to be restarted regually), since we never deploy or install anything to it? Would it be enough if I made root of this public repository available through Apache? I don't use GUI of Nexus and like I said we don't deploy to it. Would it be perhaps enough just to start Nexus after I put new dependencies into repository (for reindexing, if it's required)?
Andy

A: It's "possible" to run a maven repository without a repository manager, as it simply depends on the files being in the standard layout. See the maven docs for more information: https://maven.apache.org/guides/introduction/introduction-to-repositories.html

Internal Repositories
  When using Maven, particularly in a corporate environment, connecting to the internet to download dependencies is not acceptable for security, speed or bandwidth reasons. For that reason, it is desirable to set up an internal repository to house a copy of artifacts, and to publish private artifacts to.
Such an internal repository can be downloaded from using HTTP or the file system (using a file:// URL), and uploaded to using SCP, FTP, or a file copy.
Note that as far as Maven is concerned, there is nothing special about this repository: it is another remote repository that contains artifacts to download to a user's local cache, and is a publish destination for artifact releases.


text:
Q: Is it possible to send push notification through APNS to device token generated via FCM? In the project , I am generating device token for both IOS and Android using FCM. And push notifications . In my research, I found push notifications can be sent with https://fcm.googleapis.com/fcm/send
But is it possible to send push notification to IOS device, By using APNS api.sandbox.push.apple.com to the token generated with FCM ?
Apple docs Link

A: No. Api.sandbox.push.apple.com can only be used with Tokens generated by Apple. You need to fetch the Apple token in the client using didRegisterForRemoteNotificationsWithDeviceToken and send it to your server.
BTW, the Firebase SDK does exactly that and fetches this token in order to send iOS notifications. For each FireBase token they fetch the relevant Apple token from the device and use it when connecting to the Apple servers.


text:
Q: Why is NavigationHandler.handleNavigation() not forwarding to view ID? Inside of a phase listener class that runs during the "RESTORE_VIEW" phase, I have some code like this:
public void afterPhase(PhaseEvent event) {
  FacesContext fc = event.getFacesContext();
  NavigationHandler nh = fc.getApplication().getNavigationHandler();
  nh.handleNavigation(fc, null, "/a/specific/path/to/a/resource.jspx");
}

Navigation to the new URL doesn't work here.  The request made will just receive a response from the original JSPX that was navigated to.
Code like this works fine:
public void afterPhase(PhaseEvent event) {
  FacesContext fc = event.getFacesContext();
  NavigationHandler nh = fc.getApplication().getNavigationHandler();
  nh.handleNavigation(fc, null, "OUTCOME_DEFINED_IN_FACES_CONFIG_XML");
}

Also the first snippet will work with an IceFaces Faces provider, but not Sun JSF 1.2 which is what I need to use.  Is there something I can do to fix the code so it is possible to forward to specific URLs?

A: Use ExternalContext#dispatch() instead.
Or, if it is supposed to be a redirect, use ExternalContext#redirect().
That it works in IceFaces must be a bug or impl-specific "feature". This is namely not what the NavigationHandler API contract definies.

A: I seemed to find an answer.  The code below works fine for me:
public void afterPhase(PhaseEvent event) {
  FacesContext fc = event.getFacesContext();
  NavigationHandler nh = fc.getApplication().getNavigationHandler();
  fc.getViewRoot().setViewId("/a/specific/path/to/a/resource.jspx");
}


text:
Q: I have created a contact us app and booking app for my website but I still having an issue What I want is that the sender be the email provided in email field and de receiver must be the website owner
Here is my view contact/views.py
# SPEEDING UP DJANGO EMAIL
class EmailThread(threading.Thread):
    def __init__(self, email):
        self.email = email
        threading.Thread.__init__(self)

    def run(self):
        self.email.send(fail_silently=False)

#  CONTACT US VIEW
def contact_us(request):
    # Contact Us & Booking Table
    if request.method == 'GET':
        return render(request, 'contact.html', {"values": request.POST})

    if request.method == 'POST':
        contact_name = request.POST['name']
        contact_email = request.POST['email']
        contact_subject = request.POST['subject']
        contact_message = request.POST['message']

        # ========== saving entries into database ======================
        # Let's save our datas in database
        contact = Contact() # here he call our Contact Class
                            # and then we can use its propriertes
        contact.contact_name = contact_name
        contact.contact_email = contact_email
        contact.contact_subject = contact_subject
        contact.contact_message = contact_message
        if len(contact_message)<20:
            messages.error(request, "Contenu du message trop court pour être envoyé. Veillez réessayer svp!")
            return render(request, 'contact.html')
        contact.save() # All our entries will be now saved in our database
        # ========== end saving entries into database ======================

        # ============ Let's send user infos and request through email
        message = f"NAME: {contact_name}\n\n\n\nMESSAGE:\n{contact_message}"
        to_mail = settings.EMAIL_HOST_USER

        email = EmailMessage(
            contact_subject,
            message,
            contact_email,
            to_mail
        )
        EmailThread(email).start() # Here we called our speeding email class :)

        messages.success(request,
                "Message sent successfully!\n \
                We will call you or send you an email or sms to inform you about your request\n \
                Thanks for waiting! \
        ")

        return render(request, 'contact.html', {"values": request.POST})


text:
Q: SAAJ: XML in TextNode. Quotes not Escaped together
I ty to build a SOAP Request with SAAJ. All works fine but now I have to send an other XMl Document inside the SOAP Body inside SOAP Element.
I tried follwing code:
SOAPElement file = service.addChildElement(new QName("nameOfTextNode"));
file.addTextNode(xmlString);

The Problem is most characters are correctly escaped (e.g. '<' -> <) but not single or double quotes. I can't use CDATA or let the quotes as they are, because i don't have control over the SOAP Service and they can't support CDATA or want to change anything.
When I use anothe Library to escape the String first. It will be escaped twice in the SOAP Request.
Do aynone have an idea? Please help.

A: SAAJ doesn't escape single or double quotes in this case because it's not required. If the service requires that, then it doesn't conform to the XML specification and therefore isn't a SOAP service. Since SAAJ implements SOAP, you won't be able to use it.


text:
Q: offset().top not returning correct value on appending element I have a box containing several inputs and a link, when I click on the link an input is appended to the box. Now each time the link is clicked I want the box to be scrolled to the last input in the box.
With the solution below it works fine at first but then it returns incorrect offset().top value.
How can I fix this?
in html I have:

      <input type="email" class="form-control form-input" aria-describedby="email" autocomplete="off">

      <input type="email" class="form-control form-input" aria-describedby="email" autocomplete="off">

      <input type="email" class="form-control form-input" aria-describedby="email" autocomplete="off">

   {% trans "add another" %}

in js I have:
$('#addAnother').click(function() {
    let height_diff = Math.round($('.container-fluid').innerHeight() - $('nav').innerHeight() - $('#spaceTeammatesBox').innerHeight()),
        emails_length = $('#spaceTeammatesBox .team-emails-inner').find('.forms').length,
        form_height = (Number(emails_length) * Number($('#spaceTeammatesBox .team-emails-inner').find('.forms').innerHeight())) + Number($('#spaceTeammatesBox .team-emails-inner').find('.forms').innerHeight());

        height_diff > 180 ? $('.team-emails-inner').css('height', form_height + 'px') : null;

    $('#spaceTeammatesBox').find('.form-group.forms').last().after(`

            <input type="email" class="form-control form-input" aria-describedby="email" autocomplete="off">

    `);
   // this section ***
   $('.team-emails-inner').animate({
      scrollTop: $(".forms").last().offset().top + Number($('#spaceTeammatesBox .team-emails-inner').find('.forms').innerHeight())
   }, 1000);
});


text:
Q: How to limit cell value in Excel to options from another sheet? In Excel (2003), I want to limit the selection of values in a cell to allowable values from another spreadsheet.
For example, in the sheet "Currencies" I have
EUR,1.1
GBP,1.0
USD,1.5
(That's two columns, three rows)
In my main sheet I'd like to have a Currency column, in which the only allowable values are from column A in the Currencies sheet, i.e. the cell can contain only 'EUR', 'GBP', or 'USD'.  (Elsewhere I'll be using that as a lookup to get the exchange rate, which is column B.)
How can I restrict the value in the cell?  Having a dropdown like a windows combo box populated from the other sheet would be great.
Any answers using formulas, VBA, or whatever will be fine.  Even a pointer to the relevant documentation would be great (I have looked, but I'm not sure what to look for).
Also helpful would be answers using LibreOffice, since I haven't finalized the choice of spreadsheet program, but I thought I'd have a better chance getting an answer in Excel.

A: Why not use a dropdown?
http://office.microsoft.com/en-us/excel-help/create-a-drop-down-list-from-a-range-of-cells-HP005202215.aspx

A: VBA isn't necessary in this case. Use the built-in "Data Validation" feature.
Select the cell you want to add the combo box to, and choose Data, Validation.
Select "List" as the option, and either put a cell range in the "Source" box, or a comma-delimited list of values (if you want to hard-code it).
If the range you want to populate the list is located on another worksheet, you can't refer to it using the standard =sheet2!a1:a4 style. You'll have to create a named range, and refer to it by that name.


text:
Q: Boot logs? Where can I look to figure out why my system will boot dual monitors with an OEM kernel but not any others? Related to this topic: Why aren't the stock and mainline kernels supporting Intel onboard graphics when the 20.04b kernel does? Z590 motherboard 11th gen i9 11900k
My new 11th gen i9 will boot to the desktop with dual monitors using kernel 5.10.0-1023-oem (20.04b) but for other kernels I have to unplug either monitor and can plug it back in after I am on the desktop. I am trying to figure out where to look to compare what is happening with the OEM kernel vs the mainline and stock kernels.
I don't know where to begin or what to look for. Hoping to figure out what is configured differently in boot up on the OEM vs. other kernels.
UPDATE: Same issue with 5.13-rc1 which I just installed. Hangs at "fb0: switching to inteldrmfb from VGA EFI". This one doesn't need a config line added to grub for force_probe of the i915 driver.


text:
Q: Input file reading error Hi i currently wrote a program but I'm having problems with reading the file. It seems to have read the last line twice, as a result, producing the same results twice.
I had put the getline() function to read the first line, in order to store the string for the variable G.
The rest, I had stored it in a vector of the class object.
basically the file is opened and it performs this loop
file.open("bodies1.txt");
getline(file, G1);
....

while(!file.eof)
{
  file >> body;
  bodies.push_back(body);
}

this is what the text file look like (this is just a sample. not the actual thing)
0.02932
Sun 32 42 53 2 2
Moon 49 32 4 2 1
Jupiter 32 53 2 3 2

I really was wondering why it read the last line twice. Any suggestions?

A: while(!file.eof())
{
  file >> body;
  bodies.push_back(body);
}

After reading the last object in to body, eof is the next character. Then
file >> body;

tries to read it and fails. So whatever was in body before is still there and will be pushed in to the vector.

instead you should read like
while(file >> body)
{
  bodies.push_back(body);
}

This way your while stops as soon as you encounter eof() and you will not do an extra push in to the vector.


text:
Q: each_line sanitize newlines between quotations marks I have a CSV file that contains line breaks inside quotation marks. I would like to get rid of those, (and replace them to \ ) so as to be able to CSV.parse line-by-line.
My original is a string containing
"a","b",c,"d
e",f,g,"h
i",j
k,"l","m
n","o"

and I would like to effectively be parsing a string containing :
"a","b",c,"d e",f,g,"h i",j
k,"l","m n","o"

How to do that in Ruby ?
An effective and down-to-earth solution thanks to user @sln
fichier = File.open ("baz.csv")

matchesBalancedLinesFromUser_sln = /^[^"]*(?:"[^"]*"[^"]*)*$/

mem = ""
fichier.each_line do |ligne|
  mem += ligne.delete("\n") # as long as we don't have balance for
                            # the quotations marks, we cat the lines
  if mem =~ matchesBalancedLinesFromUser_sln
    ligneReplaced = mem + "\n"
    doWhatYouWill(ligneReplaced)
    mem = ""
  end
end

fichier.rewind

Another way to do it without a regex, just counting the quotation marks
fichier = File.open ("baz.csv")

def doWhatYouWill (string)
  puts string
end

mem = ""
fichier.each_line do |ligne|
  mem += ligne.strip + " " # as long as we don't have balance for
                           # the quotations marks, we cat the lines
  if mem.scan(/"/).count.even? # if mem has even quotation marks
    ligneReplaced = mem + "\n"
    doWhatYouWill(ligneReplaced)
    mem = ""
  end
end

fichier.rewind

Note This solution assumes that the CSV file is valid in its balance of quotation marks. If this is not the case, see this comment by User @sln


text:
Q: How to listen to new Remote Desktop connections events on the client machine in C#? I'm working on a C# app that launches a Remote Desktop connection on behalf of the user. I do that by programmatically running mstsc.exe with the required config to automatically launch the session.
I'd like to know if the connection succeeded or not to handle the potential errors. Is there an event or something like that to notify me that the remote session was successfully opened (or if the connection failed)?
For now I found a few leads:

*

*This interface that seems to expose exactly what I want, but I don't see how to use it

*Looking at the Event Viewer in Windows, I found some events that seem to be triggered when the host is unreachable, but I'd like to know if there is a simpler solution than looking for these events:

*

*Event 1026: RDP ClientActiveX has been disconnected (Reason= 516)

*Event 1105: The multi-transport connection has been disconnected.

Thanks for your help!