text:
Q: Foreign key to get column from another model - Django I have been trying to add a new column to my TrainingSubject model called "email" and link its value to another model (Training) via foreign key, and then display it all on front end (back is django, front is react.
I've added this line to TrainingSubject model:
email = models.CharField(_('Email assigned'), max_length=100, default='', blank=True)

and this one to Training model:
email_to = models.ForeignKey(TrainingSubject, related_name='manager_email', default='', blank=True)

so it all reads as follows:
    class TrainingSubject(models.Model):
    """TrainingSubject model for storing subjects."""

    name = models.CharField(_('name'), max_length=160, unique=True)
    email = models.CharField(_('Email assigned'), max_length=100, default='', blank=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = _('Training subject')
        verbose_name_plural = _('Training subjects')

class Training(models.Model):
    """Training model for storing trainings."""

    subject = models.ForeignKey(TrainingSubject, verbose_name=_('subject'),
                                related_name='trainings')
    email_to = models.ForeignKey(TrainingSubject, related_name='manager_email', default='', blank=True)
    date = models.DateTimeField(_('date'))
    timezone = models.CharField(

The migration cannot be applied, I get this error every single time I start creating these things.
        Running migrations:
      Rendering model states... DONE
      Applying sonel_core.0089_training_email_to...Traceback (most recent call last):
      File "/home/vagrant/.pyenv/versions/cms/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
        return self.cursor.execute(sql, params)
    psycopg2.IntegrityError: column "email_to_id" contains null values

Previously I tried to add it all in one step only, now I have broken it down to two steps: 1. add email to TrainingSubject (which work perfectly well) and 2. add email_to to Training model and the be able to finally display this email on the front-end.
What am I doing wrong?

A: Define the field to accept null values, as the table already does have some data, when adding new FK field, null has to be given or a valid values.
email_to = models.ForeignKey(TrainingSubject, related_name='manager_email', default='', blank=True, null=True)


text:
Q: Error message not get cleared while clicking the reset button I am using jquery.validate.js file to validate an input form, It works fine, my problem is the error messages are not get cleared while clicking the reset button in the form.
how to get clear the form?
here is the code

  javascript function

      $(document).ready(function(){

        $("#demo-form").validate({
          rules: {
            name: "required",
            address: "required",
       }

HTML Code

<input type="text" id="name" name="name" />

<input type="text" id="address" name="address" />

 <input type="submit" id="submit" value="Validate!" />
      <input type="reset" id="reset" value="Reset" />

A: Basically, when you click the reset button. It will be responsible for clearing the fields, not the label. Normally, jquery validate plugin, keeps its validation messages in labels. So in order to clear them, use
$('label.error').remove();

call this on the click of reset button
where it is needed.

A: Try hiding them by calling CSS hide property on your error DIV's when you press reset button

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dot grid in latex as background I'm trying to make a printable daily planner using Tex. This would be my first project.
What I want to achieve is for all the pages to have a dot grid background with the standard 0.5 cm space between dots and the ability to vary opacity and color. I want to be able to put pictures, tables and text on top of it. When I do get something that resembles a dot grid using tikz or https://github.com/jrblevin/dot-grid-paper I cant seem to get the text to be on top of the grid.
Is there a way to do this? A similar example or package recommendation would be highly appreciated!


text:
Q: Problem with regex creation if excape character is at the end of the parameter value I get three parameters in a string. Each parameter is written in the form: Quotes, Name, Quotes, Equals sign, Quotes, Text, Quotes. The parameter separator is a space.
Example 1:
"param1"="Peter" "param2"="Harald" "param3"="Marie"

With java.util.regex.Matcher I can find any name and text by the following regex:
"([^"]*)"\s*=\s*"([^"]*)"

Now, however, there may be a quotation mark in the text. This is masked by a backslash.
Example 2:
"param1"="Peter" "param2"="Har\"ald" "param3"="Marie"

I have built the following regex:
"([^"]*)"\s*=\s*("([^"]*(\\")*[^"]*)*[^\\]")

This works well for example 2, but is not a universal solution.
If the backslash is at the end of a parameter-value, the solution does not work anymore.
Example 3:
"param1"="Peter" "param2"="Harald\" "param3"="Marie"

If the backslash is at the end of the value, the matcher interprets "Harald\" " as the value of parameter 2 instead of "Harald\".
Do you have a universal solution for this problem? Thanks in advance for your input.
Kind regards
Dominik

A: You may use this regex in Java:
\"([^\"]*)\"\h*=\h*(\"[^\\\"]*(?:\\(?=\"(?:\h|$))|(?:\\.[^\\\"]*))*\")

RegEx Demo
RegEx Demo:

*

*\"([^\"]*)\": Match quoted string a parameter name

*\h*=\h*: Match = surrounded with optional spaces

*(: Start capture group #1

*\": Match opening "

*[^\\\"]*: Match 0 or more of non-quote, non-backslash characters

*(?::

*

*\\: Match a \

*(?=\"(?:\h|$)): Must be followed by a " that has a whitespace or line afterwards

*|: OR

*(?:\\.[^\\\"]*))*: Match an escaped character followed by 0 or more of non-quote, non-backslash characters

*\": Match closing "

*): End capture group #1


text: Q: Executing python script on page load How can I execute python script on page load using Javascript. I need to get some information that this script is getting but I can't use python directly in this html file.


text:
Q: Using R and SQL together in sf - what is an efficient workflow? Do anyone have any tips/tricks/workflows for working with an SQL query within a read_sf/st_read function call in RStudio?
(I am struggling to figure out how to make a postgrsql/postgis example reproducible)
For example I have postgresql database I am querying with something like this:
  data = read_sf(conn, query = "SELECT h.col1, h.col2, h.geom
                      FROM table AS h
                      WHERE h.col1 = \'B\'")

First, I LOVE this because it returns an sf object and I get to stay in R but leverage the database. The problem is, I am finding it messy to contruct the query in RStudio as the query string doesn't format very nicely nor does the nested quotes thing work out very well here. So my question is what are people's workflows here? Obviously query can much more complicated than this and the formatting becomes very ugly. My junky solution right now is to open a SQL editor, write the query then paste it into read_sf.
tl;dr Combining R and SQL code into read_sf presents formatting challenges that make constructing queries inefficient.

A: If you use Emacs then you can use one of the "multiple major mode" systems to do syntax highlighting for multiple languages within a single file. For example polymode - here's some screenshots that show R and C++ syntax highlighting in the same file:
https://polymode.github.io/screenshots/
I suspect R and SQL should be doable too. Submit a feature request to RStudio if you want this there.
[Emacs can work as a full R IDE, running R code from within itself, and editing scripts with highlighting, bracket-match flashing, spell checking and so on.]


text:
Q: Converting JSON object to dictionary I'm calling the ethplorer.io api, and it returns the below json. I have generated the classes in visual studio via 'paste special -> paste json as classes'. My problem is that Tokeninfo declares price as an object, this is because it can either be false if it has no price information, or a dictionary if it has values. While I have successfully deserialised the response using JsonConvert.DeserializeObject(rawJSON),  I'm struggling to convert price in to c# dictionary if it has values.
public class Tokeninfo
{
    public string address { get; set; }
    public string name { get; set; }
    public object decimals { get; set; }
    public string symbol { get; set; }
    public string totalSupply { get; set; }
    public string owner { get; set; }
    public long lastUpdated { get; set; }
    public int issuancesCount { get; set; }
    public int holdersCount { get; set; }
    public object price { get; set; }
    public string description { get; set; }
    public float totalIn { get; set; }
    public float totalOut { get; set; }
}

JSON response:
{
  "address": "0xd8f41f341afe2c411b21b3f96263c6584b69baeb", //Not my address
  "ETH": {
    "balance": 762.13611095505,
    "totalIn": 1040.0907032491,
    "totalOut": 277.954592294
  },
  "countTxs": 22,
  "tokens": [
    {
      "tokenInfo": {
        "address": "0x355a458d555151d3b27f94227960ade1504e526a",
        "name": "StockChain Coin",
        "decimals": "18",
        "symbol": "SCC",
        "totalSupply": "10000000000000000000000000000",
        "owner": "0x",
        "lastUpdated": 1524401998,
        "issuancesCount": 0,
        "holdersCount": 86520,
        "price": {
          "rate": "0.0531126",
          "diff": 4.8,
          "diff7d": 19.82,
          "ts": "1524400762",
          "marketCapUsd": null,
          "availableSupply": null,
          "volume24h": "622004.0",
          "currency": "USD"
        }
      },
      "balance": 5000000000000000000,
      "totalIn": 0,
      "totalOut": 0
    },
    {
      "tokenInfo": {
        "address": "0xb679afd97bcbc7448c1b327795c3ef226b39f0e9",
        "name": "Win Last Mile",
        "decimals": "6",
        "symbol": "WLM",
        "totalSupply": "2000000000000000",
        "owner": "0x8e7a75d5e7efe2981ac06a2c6d4ca8a987a44492",
        "lastUpdated": 1524362946,
        "issuancesCount": 0,
        "holdersCount": 10945,
        "price": false
      },
      "balance": 66000000,
      "totalIn": 0,
      "totalOut": 0
    },
    {
      "tokenInfo": {
        "address": "0xae66d00496aaa25418f829140bb259163c06986e",
        "name": "Super Wallet Token",
        "decimals": "8",
        "symbol": "SW",
        "totalSupply": "8400000000000000",
        "owner": "0xba051682e9dbc40730fcef4a374e3a57a0ce3eff",
        "lastUpdated": 1524401948,
        "issuancesCount": 0,
        "holdersCount": 30276,
        "price": false
      },
      "balance": 11567900,
      "totalIn": 0,
      "totalOut": 0
    },
    {
      "tokenInfo": {
        "address": "0x8e4fbe2673e154fe9399166e03e18f87a5754420",
        "name": "Universal Bonus Token | t.me/bubbletonebot",
        "decimals": "18",
        "symbol": "UBT",
        "totalSupply": "1150000000000000000000000",
        "owner": "0xc2db6e5b96dd22d9870a5ca0909cceac6604e21d",
        "lastUpdated": 1524393745,
        "issuancesCount": 0,
        "holdersCount": 99896,
        "price": false
      },
      "balance": 10000000000000000000,
      "totalIn": 0,
      "totalOut": 0
    }
  ]
}

A: You need a custom deserializer to do what you want. It should be straight forward though. Here is some code which checks if the price is not false and then turns it into a Dictionary<string, string>. This code makes the assumption that your root object is named RootObject:
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    var jsonObject = JObject.Load(reader);
    var root = default(Rootobject);

    // Let's go through each tokenInfo and check if price is not false
    // so we can turn it into a dictionary.
    foreach (var thisToken in root.tokens)
    {
        if (thisToken.tokenInfo.price.ToString() != "false")
        {
            thisToken.tokenInfo.price = JsonConvert.DeserializeObject<Dictionary<string, string>>(thisToken.tokenInfo.price.ToString());
        }
    }

    serializer.Populate(jsonObject.CreateReader(), root);
    return root;
}

Please see the full example here and search for ProfessionConverter in that link for the full class.

A: I think it is not very good approach to use false in cases when there is no price. If there is no price it should be something like "price" :{} or price element shouldn't be there at all. In other words, it is not good idea to mixup boolean object and dictionaty imho.
I think you can use provided by VisualStudio class where Price is an object. And you can create a custom serializer which will treat false as an null (or object with empty fields) along with standart deserialization mechanism.


text:
Q: Почему встречается ошибка Microsoft.AspNetCore.Mvc.Razor.RazorPage.Model.get вернул null? Столкнулся с проблемой. Решения в интернете не нашёл. У меня есть 2 таблицы прикрученые к WEB-API и EF Core. Мне нужно вывести вторую таблицу, однако, почему то Model.get возвращает null. При выводе первой таблицы всё работает. Код страницы razor pages:
@model IEnumerable<ABSoftTT.Models.tabelTwo>
@{
    ViewBag.Title = "Таблица спец. запроса";
}

ID	Key	Value

    @foreach (var item in Model)
    {

            @item.Key
            @item.Count
            @item.CountMoreThenOne

    }

В строчке @foreach (var item in Model) Вылезает ошибка: System.NullReferenceException: "Object reference not set to an instance of an object." Microsoft.AspNetCore.Mvc.Razor.RazorPage.Model.get вернул null.

Код второй страницы анналогичен первой за некоторыми исключениями (передаваемыми данными)
Код страницы в контроллере:
public IActionResult SecondTabel()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> SecondTabel(Counter counter)
        {
            try
            {
                var dataProvaider = new DataProvider();
                dataProvaider.InitializateSecondTable(); // формирование 2ой таблице на основе первой.
            }
            catch{ }
            return RedirectToAction("Index");
        }

Я пробовал создавать объексты в ручную, а не с помощью команды:

InitializateSecondTable()

Сам вопрос заключается в том, почему возвращается null и как это исправить? Заранее спасибо!


text:
Q: Search & Replace Character In String I am trying to write a basic Perl script to do some string manipulation. I get the "Existing_Value_To_Be_Changed" and the "New_Value" as user inputs.
The file has multiple block of lines such as the following -
foo_bar_xyz000123 := abcd (100010
        01010111111001011010001010); - (Not in same line as previous)

The foo_bar_abc part of the string appears multiple times in the file. The only numbers following it uniquifies each appearance.
When I traverse line by line in Perl, how do I replace all the 0's(Existing_Value_To_Be_Changed) with 1's(New_Value) after the foo_bar_xyz has been matched (in all occurrences). But I need to start after the ( and keep going on to the following line(s) until the ); is encountered and stop after that.
Edit
I already completed the part about navigating my way into those specific blocks of lines. I am stuck in the character search & replacing part.
$var = 'false';
while <File> {
  if (pattern matches) {
    $var = 'true';
  }
  if ($var eq "true") {
    push(@array, $_);
    if ( $_ contains ");" ) {
      $var = 'false';
    }
  }
}

When the current line is stored in a variable, what is the best way to do the replace after the ( only until ); part?
Edit
The Existing_Value_To_Be_Changed and New_Value are user inputs, and if one is 0, then the other is 1 and vice versa as it is a binary string that contains only 0s and 1s.

A: It is simplest to perform the translation as each multi-line sequence is found. This short program demonstrates.
You haven't described the content of your input file, so I have had to guess at some test data. The tr/0/1/r within the executable substitution is the part that changes the data.
use strict;
use warnings;
use 5.014;    # For non-destructive substitution

while (<DATA>) {
  if (/foo_bar_xyz000123/) {
    $_ .= <DATA> until /\);/;
    s| ( \( [01\s]+ \) ) | $1 =~ tr/0/1/r |ex;
  }
  print
}
__DATA__
xx
yy
zz
foo_bar_xyz000123 := abcd (100010
        01010111111001011010001010);
aa
bb
cc
foo_bar_xyz000123 := abcd (100010
        01010111111001011010001010
        01010111111001011010001010
        01010111111001011010001010);
dd
ee
ff

output
xx
yy
zz
foo_bar_xyz000123 := abcd (111111
        11111111111111111111111111);
aa
bb
cc
foo_bar_xyz000123 := abcd (111111
        11111111111111111111111111
        11111111111111111111111111
        11111111111111111111111111);
dd
ee
ff


text:
Q: Retrieving YouTube subscriber thumbnails over https Is it possible to show the thumbnails for an embedded YouTube playlist that is subscribing to a feed over https instead of http?
I'm working on an area of a site that is https and retrieving these thumbnails over http is causing a security warning pop-up, which I am trying to get rid of.
The thumbnails are being requested as part of the YouTube API so unable to directly request them over https:
// loop through JSON and assign values to My obj
        for (var i = 0; i < len; i ++ ) {

            TheVideo.My[i] = {};
            ja = jsonArticles[0][i];

            TheVideo.My[i].img = ja.media$group.media$thumbnail[0].url;

        }

What i'm directly looking for is to call the thumbnail from https instead of http when .url is called in the last line above.
EDIT:
I've found a work around to the problem, but I've edited my original post to clarify a bit what the problem was.

A: The answer is a bit of an add-on but it does the job. I appended a replace method to request it from https instead of http:
// loop through JSON and assign values to My obj
        for (var i = 0; i < len; i ++ ) {

            TheVideo.My[i] = {};
            ja = jsonArticles[0][i];

            TheVideo.My[i].img = ja.media$group.media$thumbnail[0].url.replace('http://','https://');

        }

Nice to know that this is possible in these situations.
Hope that this can potentially answer questions for someone else.


text:
Q: Javascript prompt missed when reloading the site At the start of my page, there comes a prompt. This prompt is important for the following process (loading data from database). If i press F5 to reload the site, the prompt should pop-up again. In Chrome and Edge that is working fine. Just firefox doesn't show anything after a reload of the page. After pressing F5 again, the prompt is coming up regularly.
Here's my code:
function:
<script>
function feststellung(maxStationenanzahl) {
    var station = window.prompt("Bitte Stationsnummer eingeben", "");
    if (station != null && station != "" && station <= maxStationenanzahl && isNaN(station) == false) {
        location.href = "station.php?stationsnr=" + station;
    }
    else {
        alert("Die Eingabe ist Keine Zahl, entspricht nicht der Stationsnummer oder ist leer");
        location.reload();
    }
}

call:
if(isset($_GET['stationsnr']) && $_GET['stationsnr'] != "" ){
    echo("<body>");
}
else{
    echo("<body onload='feststellung(".$letzte_aufgabe.")'>");
}

How to fix this in Firefox?

A: *

*do not use body onload inline.

*have
if("" == trim($_GET['stationsnr'])){
  echo "<script>feststellung('".$letzte_aufgabe."')</script>";
}
just before the </body> tag to always execute

*better: Ajax the data in without reloading the page
The test could be written like this:
var reg = /^\d+$/;
function feststellung(maxStationenanzahl) {
  var station = window.prompt("Bitte Stationsnummer eingeben", "");
  if (station.trim() !="" && reg.test(station) && parseInt(station,10) <= maxStationenanzahl) {
    location..replace("station.php?stationsnr=" + station);
  }
  else {
    alert("Die Eingabe ist Keine Zahl, entspricht nicht der Stationsnummer oder ist leer");
    location.reload();
  }
}


text:
Q: Segmentation fault deleting a row from a matrix I tried to delete a row from a matrix, but I only get segmentation fault and I don't know what's wrong whith my code.
My code is:
void Matriz2D::DeleteRow(int delete_row)
{

    int new_size = total_rows-1;

    int **tmp = new int * [new_size];

    for(int i = 0; i < new_size; i++){
        tmp[i] = new int [size_cols];
    }

    for(int i = 0; i < total_rows; i++){
        if(i != delete_row){
            for(int j = 0; j < toal_cols; j++){
                tmp[i][j] = data[i][j];
            }
        }
    }

    for(int i = 0; i < total_rows; i++){
        delete [] data[i];
    }

    delete [] data;
    data = tmp;

    total_rows--;
}

A: The error is that you do not check the index of the rows after the deleted one
void Matriz2D::DeleteRow(int delete_row)
    {

        int new_size = total_rows-1;

        int **tmp = new int * [new_size];

        for(int i = 0; i < new_size; i++){
            tmp[i] = new int [size_cols];
        }

        for(int i = 0; i < total_rows; i++){
            if(i != delete_row){
                for(int j = 0; j < toal_cols; j++){
                    if (i < delete_row) {
                       tmp[i][j] = data[i][j];
                    } else {
                       tmp[i][j] = data[i-1][j];
                    }
                }
            }
        }

        for(int i = 0; i < total_rows; i++){
            delete [] data[i];
        }

        delete [] data;
        data = tmp;

        total_rows--;
    }


text:
Q: Spring + Spring MVC dependency injection without using @Autowire I'm building an application using Spring and Spring MVC. For me using @Autowired is not an option (is a requirement).
I have build a web.xml file like:
<!-- Spring context -->
<context-param>
<param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Spring MVC -->
<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>namespace</param-name>
        <param-value>mvc-dispatcher-context</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

So I load Spring context and Spring MVC Servlet.
My mvc-dispatcher-context.xml file looks like:
<beans ...>

    <mvc:annotation-driven />

    <context:component-scan base-package="com.pacage.controller"/>

    <mvc:resources mapping="/resources/**" location="/WEB-INF/static/" />

    <bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/pages/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
    </bean>
</beans>

So I can use @Controller annotation in my controllers...
And on my applicationContext.xml I have my Spring beans defined, such as my Services in this case "OneService.java"
I have One controller as:
@Controller
@RequestMapping("/main")
public class MainController {

    private OneService oneService;
    //getters and setters
    ...
}

Where I want to inject OneService which is defined in applicationContext.xml file.
I've tried several ways but I can't get it working, always getting an NullPointerException when using my service inside the controller.
Is there any way to use beans defined in applicationContext.xml inside this mvc servlet?
[UPDATE]
If I define all my applicatonContext inside my servlet I can't get it working. Is there any way to make servlet context a child of application context just to be able to use application context beans?

A: Application context is already the "father" so beans defined in there are available to beans defined in its children. But you can defined both in the application context if you want.
The problem may be how you are trying to inject the service.
If you add @Autowired to you service it will work because that bean is available in your controller, but if you don't want to use annotations then you need to explicitly create and inject the beans in your xml contexts.
First you need to add a setter in your controller:
public void setOneService(OneService oneService) {
    this.oneService = oneService;
}

Then in your application context you would do:
<bean id="mainController" class="com.package.controller.MainController">
    <property name="oneService" ref="oneService" />
</bean>
<bean id="oneService" class="com.package.service.OneService">
</bean>

You can still do this and keep the service declaration in the application context and the controller in the servlet context.


text:
Q: Is there a way to create GLX context after Xlib's window creation? I'm trying to create OpenGLx context after the Xlib's window creation. I'm trying to separate the Xlib window creation and opengl context creation into two different phases.
Win32 window-opengl context creation was rather simple but I couldnt find any resource that illustrates the same process with Xlib-opengl in linux
This is how its done for xlib-linux
GLint glxAttribs[] = {
    GLX_RGBA,
    GLX_DOUBLEBUFFER,
    GLX_DEPTH_SIZE,     24,
    GLX_STENCIL_SIZE,   8,
    GLX_RED_SIZE,       8,
    GLX_GREEN_SIZE,     8,
    GLX_BLUE_SIZE,      8,
    GLX_SAMPLE_BUFFERS, 0,
    GLX_SAMPLES,        0,
    None
};

XVisualInfo* visual = glXChooseVisual(display, screenId, glxAttribs);
XSetWindowAttributes windowAttribs;
windowAttribs.border_pixel = BlackPixel(display, screenId);
windowAttribs.background_pixel = WhitePixel(display, screenId);
windowAttribs.override_redirect = True;
windowAttribs.colormap = XCreateColormap(display, RootWindow(display, screenId), visual->visual, AllocNone);
windowAttribs.event_mask = ExposureMask;
window = XCreateWindow(display, RootWindow(display, screenId), 0, 0, 320, 200, 0, visual->depth, InputOutput, visual->visual, CWBackPixel | CWColormap | CWBorderPixel | CWEventMask, &windowAttribs);

This is how its done in windows
const WindowsWindow* pWin32Window = (const WindowsWindow*)pOwnerWindow;

        HWND windowHandle = pWin32Window->GetWin32WindowHandle();
        HDC windowDeviceContext = pWin32Window->GetWin32WindowDeviceContext();

        /*
        * Create pixel format
        */
        PIXELFORMATDESCRIPTOR pfd = { sizeof(pfd),1 };
        memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
        pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
        pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
        pfd.iPixelType = PFD_TYPE_RGBA;
        pfd.nVersion = 1;
        pfd.cColorBits = OpenGLDeviceUtilsWin32::GetColorBits(desc.SwapchainBufferFormat);
        pfd.cAlphaBits = OpenGLDeviceUtilsWin32::GetAlphaBits(desc.SwapchainBufferFormat);
        pfd.cDepthBits = OpenGLDeviceUtilsWin32::GetDepthBits(desc.SwapchainDepthStencilBufferFormat);
        pfd.cStencilBits = OpenGLDeviceUtilsWin32::GetStencilBits(desc.SwapchainDepthStencilBufferFormat);
        pfd.cAuxBuffers = 3;
        pfd.iLayerType = PFD_MAIN_PLANE;

        const int pixelFormatIndex = ChoosePixelFormat(windowDeviceContext, &pfd);
        ASSERT(pixelFormatIndex != 0,"OpenGLDevice","Invalid pixel format");

        ASSERT(SetPixelFormat(windowDeviceContext, pixelFormatIndex, &pfd), "OpenGLDevice", "Win32 window rejected the specified pixel format");

        HGLRC tempContext = wglCreateContext(windowDeviceContext);
        ASSERT(tempContext != NULL, "OpenGLDevice", "Creation of wgl dummy context failed!");

        wglMakeCurrent(windowDeviceContext, tempContext);

        PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = NULL;
        wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");
        ASSERT(wglCreateContextAttribsARB != NULL, "OpenGLDevice", "WGL get proc address failed!");

But I would expect something like this.

*

*Create xlib window

*Check for glx attribs if the window can support that pixel format

*Create glx context using pixel format

But instead it goes as

*

*Create window with your specific glx attribs

*Create glx context

I wonder if there is a way for us to create window without letting xlib know we are going to use it for opengl and implement OpenGL specific setup for window creation process.

A: Honestly, I do not understand your motivation.
Many implementations like GLFW gets Visual from GLX/EGL APIs (including glXChooseFBConfig) and use it when creating a window. The GLX/EGL stuff part can be abstracted by writing wrappers, so I don't see the need to go to the trouble of avoiding it.
That being said, it is still possible to avoid it, so I wrote the sample code for you.
// To build, execute the command below.
// c++ -Wall -Wextra -std=c++17 -o main main.cpp -lX11 -lGLX -lGL

#include <cstdio>

#include <chrono>
#include <thread>

#include <sys/time.h>
#include <unistd.h>

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <GL/glx.h>
#include <GL/glxext.h>

#define OGL_MAJOR_VERSION 3
#define OGL_MINOR_VERSION 3

#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 360
#define FPS 60

static double get_time() {
    static timeval s_tTimeVal;
    gettimeofday(&s_tTimeVal, NULL);
    double time = s_tTimeVal.tv_sec * 1000.0; // sec to ms
    time += s_tTimeVal.tv_usec / 1000.0;      // us to ms
    return time;
}

struct TestWindowConfig {
    int width = 640;
    int height = 360;
};

class TestWindow final {
  public:
    explicit TestWindow(const TestWindowConfig& config) : m_config(config) {}
    virtual ~TestWindow() {
        if (m_display) {
            if (m_xid) {
                XDestroyWindow(m_display, m_xid);
            }
            XCloseDisplay(m_display);
        }
    }

    bool create() {
        m_display = XOpenDisplay(NULL);
        if (!m_display) {
            fprintf(stderr, "XOpenDisplay() failed\n");
            return false;
        }

        XSetWindowAttributes x_attr;
        x_attr.override_redirect = False;
        x_attr.border_pixel = 0;

        m_xid = XCreateWindow(m_display, DefaultRootWindow(m_display), 0, 0, m_config.width,
                              m_config.height, 0, CopyFromParent, InputOutput, CopyFromParent,
                              CWOverrideRedirect | CWBorderPixel, &x_attr);
        if (!m_xid) {
            fprintf(stderr, "XOpenDisplay() failed\n");
            return false;
        }
        XStoreName(m_display, m_xid, "X11-GLX Sample");
        XMapWindow(m_display, m_xid);

        m_wm_delete_window = XInternAtom(m_display, "WM_DELETE_WINDOW", True);
        XSetWMProtocols(m_display, m_xid, &m_wm_delete_window, 1);

        return true;
    }

    void show() const {
        if (m_display && m_xid) {
            XMapRaised(m_display, m_xid);
        }
    }

    bool poll_events() {
        if (!m_display) {
            fprintf(stderr, "Display is null\n");
            return false;
        }

        while (XPending(m_display) > 0) {
            XEvent ev;
            XNextEvent(m_display, &ev);
            if (ev.type == ClientMessage) {
                if ((Atom)ev.xclient.data.l[0] == m_wm_delete_window) {
                    m_should_close = true;
                }
            }
        }

        return true;
    }

    bool should_close() const { return m_should_close; }

    Display* display() const { return m_display; }

    Window xid() const { return m_xid; }

    int screen_id() const { return DefaultScreen(m_display); }

  private:
    TestWindowConfig m_config;
    Display* m_display = nullptr;
    Window m_xid = 0;
    Atom m_wm_delete_window;

    bool m_should_close = false;
};

class TestGLContext final {
  public:
    explicit TestGLContext() = default;

    virtual ~TestGLContext() = default;

    bool create(const TestWindow& window) {
        // clang-format off
        int visual_attr[] = {
            GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
            GLX_RENDER_TYPE,   GLX_RGBA_BIT,
            GLX_RED_SIZE,      8,
            GLX_GREEN_SIZE,    8,
            GLX_BLUE_SIZE,     8,
            GLX_ALPHA_SIZE,    8,
            GLX_DEPTH_SIZE,    0,
            GLX_STENCIL_SIZE,  0,
            GLX_DOUBLEBUFFER,  True,
            None
        };
        // clang-format on
        int cfg_count;
        auto fb_configs =
            glXChooseFBConfig(window.display(), window.screen_id(), visual_attr, &cfg_count);
        if (!fb_configs || (cfg_count < 1)) {
            fprintf(stderr, "glXChooseFBConfig(): No config found\n");
            return false;
        }
        PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB =
            (PFNGLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddressARB(
                (const GLubyte*)"glXCreateContextAttribsARB");
        if (!glXCreateContextAttribsARB) {
            fprintf(stderr, "Failed to load glXCreateContextAttribsARB\n");
            return false;
        }
        // clang-format off
        int ctx_attr[] = {
            GLX_CONTEXT_PROFILE_MASK_ARB,  GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
            GLX_CONTEXT_MAJOR_VERSION_ARB, OGL_MAJOR_VERSION,
            GLX_CONTEXT_MINOR_VERSION_ARB, OGL_MINOR_VERSION,
            0, 0
        };
        // clang-format on
        m_ctx = glXCreateContextAttribsARB(window.display(), fb_configs[0], NULL, True, ctx_attr);
        if (!m_ctx) {
            fprintf(stderr, "Failed to create GLX Context\n");
            return false;
        }

        m_should_destroy = true;

        return true;
    }

    bool make_current(const TestWindow& window) {
        if (glXMakeCurrent(window.display(), window.xid(), m_ctx) != True) {
            fprintf(stderr, "glXMakeCurrent() Failed\n");
            return false;
        }
        return true;
    }

    void swap_buffers(const TestWindow& window) { glXSwapBuffers(window.display(), window.xid()); }

    static void* get_proc_address(const char* name) {
        return reinterpret_cast<void*>(glXGetProcAddress((const GLubyte*)name));
    }

    void destroy(const TestWindow& window) {
        glXDestroyContext(window.display(), m_ctx);
        m_should_destroy = false;
    }

    bool should_destroy() const { return m_should_destroy; }

  private:
    GLXContext m_ctx;

    bool m_should_destroy = false;
};

int main() {
    // 1. Prepare Window and OpenGL Context
    // In normal design, TestWindow should have its GLContext within itself.
    // But, in order to fit your needs, I separated these explicitly.

    TestWindowConfig config{.width = WINDOW_WIDTH, .height = WINDOW_HEIGHT};
    TestWindow window{config};
    TestGLContext glctx{};

    if (!window.create()) {
        return 1;
    }

    if (!glctx.create(window) || !glctx.make_current(window)) {
        if (glctx.should_destroy()) {
            glctx.destroy(window);
        }
        return 1;
    }

    // 2. Load OpenGL functions
    // In normal cases, you are always recommended to use loader libraries like glad.
    // In this example, I omited the loading part.
    //
    // if (!gladLoadGLLoader((GLADloadproc)glctx.get_proc_address)) {
    //     fprintf(stderr, "Failed to load OpenGL functions\n");
    //     return 1;
    // }

    // 3. Show the window and call OpenGL APIs
    // As above, there are various problems in this implentation for real use.
    window.show();

    double last_time = get_time();
    while (true) {
        if (!window.poll_events() || window.should_close()) {
            break;
        }

        auto delta_ms = get_time() - last_time;
        if (auto diff = (1000.0 / FPS) - delta_ms; diff > 0) {
            std::this_thread::sleep_for(std::chrono::milliseconds((long)diff));
            continue;
        }
        // fprintf(stderr, "delta: %f\n", delta_ms);

        glViewport(0, 0, config.width, config.height);
        glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        glctx.swap_buffers(window);

        last_time = get_time();
    }

    glctx.destroy(window);

    return 0;
}

A:
I'm trying to create OpenGLx context after the Xlib's window creation.

I don't really see your problem. On Win32 the usual stanza is:

*

*Create window

*Select pixelformat

*Set pixelformat on window

*Get HDC from window and use it to create context

On GLX the stanza is:

*

*Select visual for window

*Create window that's compatible with visual

*Create OpenGL context with the selected visual

Take note that in both Win32 and GLX there is no hard tie between the window and the OpenGL context. As long as the pixelformat/visual of a OpenGL context and a window are compatiple, you can use them with each other.
The only difference between GLX and Win32 is, how the pixelformat/visual is communicated to OpenGL context creation. In GLX it's done directy, in Win32 the pixelformat is communicated in a rather convoluted way by means of the HDC of a window. And take note that in order to obtain a modern OpenGL context you actually have to go the route of OpenGL context creation with attributes which works exactly the same in Win32 and GLX (with Win32 needing the added steps of creating a dummy OpenGL context first in order to obtain the function pointers to the wglCreateContextAttribsARB functions, which are directly available in GLX).


text:
Q: Access to visual studio variables from Wix I have Visual Studio 2015 with Wix Extension 0.9.21.62588 and v4 toolset. According to the document these are the project references and variables I can use.  In the pre build and post build steps I can access these fine
However I cant seem to access the other available options that a C++ project has access to example $(WindowsSdkDir), $(UniversalCRT_LibraryPath_x86) etc.  Is it possible, if not is there a workaround

A: Usually you can do this by updating the $(DefineConstants) property in the project manually or through visual studio project properties > Build > Define preprocessor variables
You just need to use a semi-colon separated list of variable names-value pairs.
WindowsSdkDir=$(WindowsSdkDir);UniversalCRT_LibraryPath_x86=$(UniversalCRT_LibraryPath_x86)

In this format the $(VarName) references are the MSBuild properties. The name you want to use for your wix variables $(var.Name) can be anything you like.
Then in your wxs wix code you can access these values using $(var.WindowsSdkDir) or $(var.UniversalCRT_LibraryPath_x86)


text:
Q: Exception for ns4 not resolved I am trying to run a python script that uses soapclient.
I am running into the following exception. I googled around and couldn't get any details related to this exception.
Can anyone provide inputs on how to overcome the exception?
request = self.search_soapclient.factory.create('ns4:SearchRequest')

File "build\bdist.win32\egg\suds\client.py", line 232, in create
File "build\bdist.win32\egg\suds\resolver.py", line 107, in find
File "build\bdist.win32\egg\suds\resolver.py", line 129, in root
File "build\bdist.win32\egg\suds\resolver.py", line 194, in qualify
File "build\bdist.win32\egg\suds\xsd\__init__.py", line 56, in qualify
Exception: prefix (ns4) not resolved


text:
Q: "Page build failed" after auto merging pull request to GitHub-Pages master branch The comments system on my Github Pages blog (https://github.com/artandsuffering/artandsuffering.github.io) creates each comment on a new branch and then creates a pull request to merge the branch to master. If I commit the request myself, the page rebuilds and works fine. But I want the requests to merge without me having to do anything, so I've tried a few Github apps like Mergify to automate the process. Mergify successfully merges the requests, but the blog doesn't update, and in my GitHub Pages settings I get a "Page build failed" notification.
If I make a small change, like add a space to one of my SCSS files, and commit, the blog builds and updates fine. How can I automatically merge pull requests and have my blog build properly? My .mergify.yml looks like this:
    pull_request_rules:
  - name: automatic merge on CI success
    conditions:
      - author=artandsuffering
      - base=master
    actions:
      merge:
        method: merge
      delete_head_branch: {}


text:
Q: Linking static singleton class when i try to link a SIngleton class a get
sources/singleton.cpp:8:41: error: no se puede declarar que la función miembro 'static myspace::Singleton& myspace::Singleton::Instance()' tenga enlace estático [-fpermissive]
sources/director.cpp:19:35: error: no se puede declarar que la función miembro 'static void myspace::Singleton::Destroy()' tenga enlace estático [-fpermissive]
myspace: *** [objects/singleton.o] Error 1

the Singleton class:
#Singleton.h
#include <stdlib.h>

namespace myspace {

    class Singleton
    {
    public:
        static Singleton& Instance();
        virtual ~Singleton(){};
    private:
        static Singleton* instance;
        static void Destroy();
        Singleton(){};
        Singleton(const Singleton& d){}
    };
}

#Singleton.cpp
#include "../includes/Singleton.h"

namespace myspace {
    Singleton* Singleton::instance = 0;

    static Singleton& Singleton::Instance()
    {
        if(0 == instance) {
            instance = new Singleton();

            atexit(&Destroy);
        }

        return *instance;
    }

    static void Singleton::Destroy()
    {
        if (instance != 0) delete instance;
    }
}

i need some LDFLAGS to the linker?

A: You can only declare methods static in the declarations, it's not allowed in the implementations. Just change your implementations to;
Singleton& Singleton::Instance()
{

and
void Singleton::Destroy()
{

and you should be fine.

A: You need to remove static from the definitions in the cpp file: the compiler already knows the Singleton::Instance and Singleton::Destroy are static from their declarations. Everything else looks right.


text:
Q: What does "set" mean in programming languages like C#? I've been reading a book about C#. What does the word 'set' mean in the following excerpt?

Pattern matching with the switch statement: Like the if statement, the switch statement supports pattern matching in C# 7.0 and later.
The  case values no longer need to be literal values; they can be
patterns. Let's see an example of pattern matching with the switch
statement using a folder path. If you  are using macOS, then swap the
commented statement that sets the path variable and replace  my
username with your user folder name:

*

*Add the following statement to the top of the file to import types for working with  input/output: using System.IO;

*Add statements to the end of the Main method to declare a string path to a file, open it  as either a readonly or writeable stream, and
then show a message based on what type  and capabilities the stream
has, as shown in the following code:

// string path ="/Users/markjprice/Code/Chapter03";
string path => @"C:\Code\Chapter03";
Write("Press R for readonly or W for write: ");
ConsoleKeyInfo key = ReadKey();
WriteLine(); ...

My question is about the following part:

If you are using macOS, then swap the commented statement that sets the path variable and replace my username with your user folder name

Would anybody explain it to me?

A: In this context, the word set means to assign a value to a variable.
This can correspond to several of the many dictionary definitions of the English word set, as a transitive verb.

*

*to cause to assume a specified condition, relation, or occupation

*

*slaves were set free → foreach (Slave s in slaves) s.IsFree = true;

*set the house on fire → house.IsOnFire = true;

*to cause to assume a specified posture or position

*

*set the door ajar → door.Position = AJAR;

*to adjust (a device and especially a measuring device) to a desired position

*

*set the alarm for 7:00 → alarm.Time = new TimeOfDay(7, 0);

*set a thermostat at 68 → thermostat.Temperature = 68;

*to fix at a certain amount

*

*set bail at $500 → bail = 500.00;
The C# language in particular often uses the keywords get and set in combination to define what it calls a property.

A: This question is one of English semantics, not programming, which initially urged me to vote to close this question as being off topic.
However, because "set" is notoriously the word with the most numerous and widely ranging definitions in the English dictionary (link - 430 definitions in the OED, a whopping 60,000 word long entry), it seems on topic enough to focus on what it specifically means to a programmer when referring to code.

Homing in on the intention:

the [..] statement that sets the path variable

Very specifically, this means the following code (I assume the => was a typo on your part):
string path = @"C:\Code\Chapter03";

This statement sets a value (@"C:\Code\Chapter03") in the variable (path).
That's really all there is to say here. "To set" means "to define a value".

You mean that "set" is kind of synonym to 'initialize'?

No.
Firstly, you declare a variable:
string path;

Note that this does not set a value (For those who disagree: I'm ignoring default values here - the compiler warns you about uninitialized variables even if the variable's type has a default value).
Then, when you first assign a value, that's what we call initialization:
string path;          // declaration
path = "...";         // initialization

// OR

string path = "...";  // declaration + initialization

However, "setting" a value happens any time you change the value of the variable. After the first time, it's no longer called initialization; but it is still "setting" the value.
All initializations are also inherently a case of setting a value. But not all cases of a value being set are also an initialization.
string path;
path = "A";
path = "B";
path = "C";

The path variable was initialized once but its value was set three times.


text:
Q: The code isn't running successfully nor showing any errors Replacing {{name}} by name string.
Question: After exchanging {{name}} for tushar I am expecting the output thanks tushar for purchasing {{item}} from our outlet {{outlet}} but when I run the program it prints empty lines or nothing. What is wrong?
I use vs code and mingw compiler
i cannot figure out why is this happening, and i just wanted to work on my own logic instead of seeing the solution, guide me if the logic i'm using is completely wrong
#include <stdio.h>
#include <conio.h>
#include <string.h>

void func(char *string, char *name, char *outlet, char *item)
{
    for (int i = 0; i < strlen(string); i++)
    {
        if (string[i] == '{')
        {
            if (string[i + 2] == 'n')
            {
                int n = i;
                for (int k = 0; k < strlen(name) - 8; k++)
                {
                    for (int l = strlen(string); l >= 15; l--)
                    {
                        string[l + 1] = string[l];
                    }
                }

                for (int j = 0; j < strlen(name); j++)
                {
                    string[n] = name[j];
                    n++;
                }
                i = i + strlen(name);
                continue;
            }

            if (string[i + 2] == 'i')
            {
                continue;
            }

            if (string[i + 2] == 'o')
            {
                continue;
            }
        }
    }
}

int main()
{
    FILE *ptr = NULL;
    char string[80] = "thanks {{name}} for purchasing {{item}} from our outlet {{outlet}}";
    char name[50] = "tushar";
    char item[80] = "laptop";
    char outlet[50] = "meerut";
    /*ptr = fopen("file.txt","r+");
    fscanf(ptr,"%[^\n]s",string);
    printf("the content of this file has %s\n",string);*/
    func(string, name, outlet, item);
    printf("%s\n", string);
    // fputs(str,ptr);
    // fclose(ptr);
    return 0;
}

A: There are several errors in the code, and I will suggest code that fixes these, and lets the program yield the output you expect.  That said, I will suggest a few changes to make your code more readable and reliable.
Getting it to work
The purpose of these loops
for (int k = 0; k < strlen(name) - 8; k++)
{
    for (int l = strlen(string); l >= 15; l--)
    {
        string[l + 1] = string[l];
    }
}

is to shorten or lengthen the input string to accommodate for the name being shorter or longer than your keyword {{name}}.  However, it handles only ONE case, lengthening.  Your name tushar is shorter than the keyword, so the final string needs to be shortened.
Use this:
for (int k = 0; k < 8 - strlen(name); k++)  // number chars to delete from 'string'
{
    for (int l = 14; l <= strlen(string); l++)  // also copy null-terminator
    {
        string[l-1] = string[l];
    }
}

Some suggestions
Use the debugger in VS Code to help you track variables as they change value, so you can see if your string and array accesses go "out-of-bounds". There are also online debuggers you can use, for example onlinegdb, which is what I used to verify the loop changes I added.
Your code is quite brittle meaning it will work for only very specific and well-behaved input data, and the code is difficult to change. For example, you're not actually testing for {{name}}, but only the first { and n.  So if you want your input string to contain both {{name}} and {{number}} (and similar) you're in trouble.  Also, there are a few places you traverse or check the string in such a way that you could end up beyond the end of the string.  This is not generally allowed in C.  Many of these problems and risks can be avoided by using library functions instead.
Make use of standard C libraries, with functions that already do parts of what you want to achieve, for example sprintf() to print a string into a buffer, or strchr() to find a character in a string, or strstr() to find a string in a string.

A: Mail-merge is hard to get right. You are defining your own regular language. The standard library has very basic tools for this job, but fortunately, there are a lot of tools that are specifically designed for this purpose.
#include <stdio.h>
#include <errno.h>
#include <limits.h>

struct mail_merge { const char *name, *item, *outlet; };

static int mail_merge(FILE *fp, const char *text,
    const struct mail_merge *const mail) {
    const char *YYCURSOR = text, *YYMARKER, *sub0, *sub1;
    /*!stags:re2c format = 'const char *@@;\n'; */
loop:
    /*!re2c
    re2c:yyfill:enable = 0;
    re2c:define:YYCTYPE = char;
    // Used a brace in the text? Can't do that, (this is the simplest.)
    * { return errno = EILSEQ, 0; }
    // Everything except braces and nul gets echoed to the file.
    @sub0 [^{}\x00]+ @sub1
        { fwrite(sub0, 1, (size_t)(sub1 - sub0), fp); goto loop; }
    // These are the special symbols.
    "{{name}}" { fprintf(fp, "%s", mail->name); goto loop; }
    "{{item}}" { fprintf(fp, "%s", mail->item); goto loop; }
    "{{outlet}}" { fprintf(fp, "%s", mail->outlet); goto loop; }
    // A nul-terminator means we are done.
    "\x00" { return 1; }
    */
}

int main(void) {
    const struct mail_merge tushar = { "tushar", "laptop", "meerut" };
    return mail_merge(stdout,
        "thanks {{name}} for purchasing {{item}} from our outlet {{outlet}}\n"
        "thanks again {{name}}\n", &tushar) ? 0 : (perror("mail-merge"), 1);
}

For example, running this though re2c and then running the generated .c through your compiler produces the output expected. Using a lexer is generally much simpler, more robust, faster to develop, and faster to run.


text: Q: How to insert an overlay element and not affect page formatting I have been working on this site (https://moodkeyboard.neocities.org/) and am trying to make it so when you add a gif image (on the bottom of the menu) it does not change the height of its container div. Essentially I want to add the element as if it had no height or width, since I just want it to be an overlay element.


text:
Q: Convert character string list into dataframe in R I am scraping the Newark Liberty International Airport's website to keep track of their daily schedules. Here is the piece of code I have developed:
library(rvest)

url <- read_html('https://www.airport-ewr.com/newark-departures-terminal-C?
tp=6&day=tomorrow')

population <- url %>% html_nodes(xpath = '//*[@id="flight_detail"]') %>%
              html_text() %>% gsub(pattern = '\\t|\\r|\\n', replacement = ' ') %>%
              trimws() %>% gsub(pattern = '\\s+', replacement = " ")

gsub() is for removing the leading and trailing whitespaces and extra spaces within the text. The code works well and I have attached the snippet of the output:

I want to convert this character string into a dataframe which would contain values as shown below:

Any help is appreciated !!

A: Try this out:
library(rvest)

url <- read_html('https://www.airport-ewr.com/newark-departures-terminal-C?tp=6&day=tomorrow')

population <- url %>% html_nodes(xpath = '//*[@id="flight_detail"]') %>%
              html_text()

First we read in the raw text rows. Then I noticed that each column is separated by \n but sometimes there's more than one, so first we gsub out the extra \n delimiters, then string split by \n, and rbind the output into a data.frame
popDF <- as.data.frame(
  do.call('rbind',strsplit(gsub("(\\n)+", "\\\n",population),split="\n", fixed=TRUE))
)

  V1               V2                V3      V4       V5                V6 V7      V8                       V9
1      Austin  (AUS)   United Airlines  UA 2427 06:00 am Depart:  06:00 am  C Term. C  Scheduled - On-time [+]
2      Austin  (AUS)               SAS  SK 6868 06:00 am Depart:  06:00 am  C Term. C  Scheduled - On-time [+]
3      Boston  (BOS)   United Airlines  UA 1699 06:00 am Depart:  06:00 am  C Term. C  Scheduled - On-time [+]
4    Columbus  (CMH)          CommutAir C5 4973 06:00 am Depart:  06:00 am  C Term. C  Scheduled - On-time [+]
5    Columbus  (CMH)   United Airlines  UA 4973 06:00 am Depart:  06:00 am  C Term. C  Scheduled - On-time [+]
6     Detroit  (DTW)  Republic Airlines YX 3482 06:00 am Depart:  06:00 am  C Term. C  Scheduled - On-time [+]


text:
Q: How cgroup can limit the command dd to write to the disk Right now I am working on cgroup devices subsystem, I want to allow only some process to access my USB drive. for example: If dd is not in allowed process, the dd command shouldnt able to write to the device.
I have tried putting "a 8:* mr" into device allow list, but how to set the trusted process here. Trusted process means, a process for  which I gave permission to access the device.


text:
Q: styling columns in table that uses CSV data through php I am looking to style my table columns for example make Author columns display for example "the book titles" in bold red while the prices in italic blue etc...
2012-03-11,paul,the book title,386,10,256

my php code
echo "
   \n\n

Date
Author
Title
Prices
Sales
Rank

";
$f = fopen("local/bookdata.csv", "r");
$i = 0;

while (($line = fgetcsv($f)) !== false) {
     echo "
";
        foreach ($line as $cell) {
                echo "" . htmlspecialchars($cell) . "	";
        }
        echo "
\n";
    $i++;
}

fclose($f);
echo "\n
";

Any help most welcome

A: php
$classes = array('', '', 'title', 'price' , '', '');
// ...
foreach ($line as $idx=>$cell) {
    echo "". htmlspecialchars($cell) . "	";
}

css
td.title { font-weight: bold; color: red; }
td.price { font-style: italic; color: blue;  }


text:
Q: Web scrape request does not work for long date range input in R The code here works for web scraping by sending repeated request based on the input date range (startDate and endDate). Then data will be saved in csv file. I have used this code before for different xPath @ html_node() argument, and it works fine. Now with different xPath, seems like it cannot works for longer date range. With this one, I also can't detect which data went missing because the code fails to work when the heading element applied as attr(). I've tried increase the range slowly and it only works until [1:29]. After that, no matter what the range used, it keep showing the old return. In some cases, I can see str(new_df) complete the request, but it keep saving the old return, as if the bind_rows fail. Sometimes (by using date of different year), I was able to extract the range desired by slowly increase the range (desired range is [1:92]). It makes me excited, but when I change the date input to get other different year it return the last record. sometimes with error, and sometimes the error not appear. I include the lengthy code here so anyone can reproduce it. I wonder if the website burdened by repeated request or my pc getting muzzy. Kindly help.
get_sounding_data <- function(region = c("naconf", "samer", "pac", "nz", "ant",
                                     "np", "europe", "africa", "seasia", "mideast"),
                          date,
                          from_hr = c("00", "12", "all"),
                          to_hr = c("00", "12", "all"),
                          station_number = 48615) {

  # we use these pkgs (I removed the readr and dplyr dependencies)
  suppressPackageStartupMessages({
require("xml2", quietly = TRUE)
require("httr", quietly = TRUE)
require("rvest", quietly = TRUE)
  })

  # validate region
  region <- match.arg(
arg = region,
choices = c(
  "naconf", "samer", "pac", "nz", "ant",
  "np", "europe", "africa", "seasia", "mideast"
    )
  )

  # this actually validates the date for us if it's a character string
  date <- as.Date(date)

  # get year and month
  year <- as.integer(format(date, "%Y"))
  stopifnot(year %in% 1973:as.integer(format(Sys.Date(), "%Y")))

  year <- as.character(year)
  month <- format(date, "%m")

  # we need these to translate day & *_hr to the param the app needs
  c(
"0100", "0112", "0200", "0212", "0300", "0312", "0400", "0412",
"0500", "0512", "0600", "0612", "0700", "0712", "0800", "0812",
"0900", "0912", "1000", "1012", "1100", "1112", "1200", "1212",
"1300", "1312", "1400", "1412", "1500", "1512", "1600", "1612",
"1700", "1712", "1800", "1812", "1900", "1912", "2000", "2012",
"2100", "2112", "2200", "2212", "2300", "2312", "2400", "2412",
"2500", "2512", "2600", "2612", "2700", "2712", "2800", "2812",
"2900", "2912", "3000", "3012", "3100", "3112"
  ) -> hr_vals

  c(
"01/00Z", "01/12Z", "02/00Z", "02/12Z", "03/00Z", "03/12Z", "04/00Z",
"04/12Z", "05/00Z", "05/12Z", "06/00Z", "06/12Z", "07/00Z", "07/12Z",
"08/00Z", "08/12Z", "09/00Z", "09/12Z", "10/00Z", "10/12Z", "11/00Z",
"11/12Z", "12/00Z", "12/12Z", "13/00Z", "13/12Z", "14/00Z", "14/12Z",
"15/00Z", "15/12Z", "16/00Z", "16/12Z", "17/00Z", "17/12Z", "18/00Z",
"18/12Z", "19/00Z", "19/12Z", "20/00Z", "20/12Z", "21/00Z", "21/12Z",
"22/00Z", "22/12Z", "23/00Z", "23/12Z", "24/00Z", "24/12Z", "25/00Z",
"25/12Z", "26/00Z", "26/12Z", "27/00Z", "27/12Z", "28/00Z", "28/12Z",
"29/00Z", "29/12Z", "30/00Z", "30/12Z", "31/00Z", "31/12Z"
  ) -> hr_inputs

  hr_trans <- stats::setNames(hr_vals, hr_inputs)

  o_from_hr <- from_hr <- as.character(tolower(from_hr))
  o_to_hr <- to_hr <- as.character(tolower(to_hr))

  if ((from_hr == "all") || (to_hr == "all")) {
from_hr <- to_hr <- "all"
  } else {

from_hr <- hr_trans[sprintf("%s/%02dZ", format(date, "%d"), as.integer(from_hr))]
match.arg(from_hr, hr_vals)

to_hr <- hr_trans[sprintf("%s/%02dZ", format(date, "%d"), as.integer(to_hr))]
match.arg(to_hr, hr_vals)

  }

  # clean up the station number if it was entered as a double
  station_number <- as.character(as.integer(station_number))

  # execute the API call
  httr::GET(
url = "http://weather.uwyo.edu/cgi-bin/sounding",
query = list(
  region = region,
  TYPE = "TEXT:LIST",
  YEAR = year,
  MONTH = sprintf("%02d", as.integer(month)),
  FROM = from_hr,
  TO = to_hr,
  STNM = station_number
    )
  ) -> res

  # check for super bad errors (that we can't handle nicely)
  httr::stop_for_status(res)

  # get the page content
  doc <- httr::content(res, as="text")

  # if the site reports no data, issue a warning and return an empty data frame
  if (grepl("Can't get", doc)) {
 doc <- xml2::read_html(doc)
 msg <- rvest::html_nodes(doc, "body")
 msg <- rvest::html_text(msg, trim=TRUE)
 msg <- gsub("\n\n+.*$", "", msg)
 warning(msg)
 return(data.frame(stringsAsFactors=FALSE))
  }

  # turn it into something we can parse
  doc <- xml2::read_html(doc)

  # get the metadata
  #meta <- rvest::html_node(doc, "h2")
  #meta <- rvest::html_text(meta, trim=TRUE)
  #attr(doc, "meta") <- meta

  raw_dat <- doc %>%
   html_nodes("pre + h3") %>%
   html_text()

  indices <- doc %>%
    str_split(pattern = "\n", simplify = T) %>%
    map_chr(str_squish) %>%
    tibble(x = .) %>%
    separate(x, into = c("Station", "Value"), sep = ": ") %>%
    filter(!is.na(Value))

  data <- tidyr::spread(indices, Station, Value)
  data

}

startDate <- as.Date("01-11-1984", format="%d-%m-%Y")
endDate <- as.Date("04-11-1984",format="%d-%m-%Y")
#startDate <- as.Date("01-11-1984", format="%d-%m-%Y")
#endDate <- as.Date("31-01-1985",format="%d-%m-%Y")

days <- seq(startDate, endDate, "day")

#wanted to have [1:92], but its not working
lapply(days[1:4], function(day) {
  get_sounding_data(
    region = "seasia",
    date = day,
    from_hr = "00",
    to_hr = "00",
    station_number = "48615"
  )
}) -> soundings_48615

warnings()
new_df <- map(soundings_48615, . %>% mutate_all(parse_guess))
#str(new_df)

library(tidyr)
library(tidyverse)
library(dplyr)
dat <- bind_rows(new_df)
dat <- dat %>% separate(col =`Observation time`, into = c('Date', 'time'), sep = '/')

dat$Date <- as.Date(dat$Date, format = "%y%m%d")

#save in text file
library(xlsx)
write.csv(dat, 'c:/Users/Hp/Documents/1984.csv')
get_sounding_data <- NULL

error
Error in bind_rows_(x, .id) :
 Column `1000 hPa to 500 hPa thickness` can't be converted from numeric to character
dat <- dat %>% separate(col =`Observation time`, into = c('Date', 'time'), sep = '/')
 Error in eval_tidy(enquo(var), var_env) :
  object 'Observation time' not found

I've install different R version, but this error keep come out. So I ignore it.
Error: package or namespace load failed for 'xlsx':
.onLoad failed in loadNamespace() for 'rJava', details:
call: fun(libname, pkgname)
error: No CurrentVersion entry in Software/JavaSoft registry! Try re-
installing Java and make sure R and Java have matching architectures.


text:
Q: Web service for deep linking This is my first time create an ios application that required deep linking. I need to create a web service for my custom url scheme for ios in order to publish it online. Please give some pointer on regarding which web service i should use or is there an alternative way to create a deep linking for custom url scheme for iOS. Thanks.

A: You can do it yourself with any server platform - Rails, PHP, Dot.Net, etc.
Here is a very simple PHP snippet. Replace "myappname" with your app's URL scheme. The param/value query is optional - you can use any other text and parse it in your App Delegate's openUrl method.
if (strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone OS') !== FALSE) {
  // redirect
  header("location: myappname://?key=value");
  exit();
}

Client use-cases:

*

*iOS Safari, your app installed - will open your app.

*iOS Safari, your app not installed - Safari will complain that it cannot open the link.

*Another iOS app, your app installed - will switch to your app.

*Another iOS app, your app not installed - same as Safari. However, if the other app is implementing UIApplication's canOpenURL: - it may gracefully take the user to the App Store, but it's up to the other app developer.

*Any other device or browser - will continue to render the page, where you can add your html including AppStore links.

A: If you don't want to create the server code, you can use a tool I created for this purpose. You have it here:
http://www.uppurl.com/
It's mainly a short link tool that checks for user device and give him the right url based on his devices. With this tool you don't need to write any server code and it also takes care of different devices, operating systems and browsers.
Take care of Tal answer as latest versions of Chrome has changed the way to open app and now you need to provide a link in different format, they use something like "intent://..."


text:
Q: Collapse event doesn't work in angular js I've recently got stuck with such a problem.
I use angular-ui bootstrap and I want to call show.bs.collapse callback for collapse, but nothing happens. Here's my plunk .

A: You can use a watch
  $scope.$watch('isCollapsed', function(isCollapsed){
    if(isCollapsed){
      alert("BOL");
    }
  });


text:
Q: How to make pytest to pass test if any parametrized test passed? We have a cluster where only a single server (master) can return a meaningful result. The master is selected automatically and at test time I don't know who is master and who is not. In our tests we are using testinfra which gives us a fixture 'host' for each host in cluster.
We have a test which looks like this:
def test_cluster(host):
    assert host.run_command('cluster --is_ok').stdout == 'OK'

The problem is that there are N hosts, and only one of them can return OK, others says "I'm not a master".
The normal output looks like this:
test_cluster[host1] .... FAIL
test_cluster[host2] .... OK
test_cluster[host3] .... FAIL
test_cluster[host4] .... FAIL

I want to find a way to mark the test test_cluster as pass if any of tests is pass (and fail if all tests are failed).
If testinfra is too much for the test, here the more concise example with pytest only:
@pytest.fixture.parametrize("num", [0, 0, 1, 0])
def test_example(num):
     asssert num > 0

I need pytest to pass if there is at least one 1 in 'num' fixture.


text:
Q: TFS how to terminate/close a project I am migrating from TFS to SVN, however want to keep TFS repository for reference. Is is possible to make the TFS project read-only? So no one can commit new changes.

A: You can right-click on the root folder for project in source control, and select 'lock'

A: The correct way is to change user permissions to read-only.


text:
Q: How To Get Image With Correct Direction From Asset How to rotate image with correction direction
I have placed below code , But not Working
UIImage *images  = [UIImage imageWithCGImage:[rep fullScreenImage] scale:[rep scale] orientation:0];

A: UIImageOrientation specifies the possible orientations of an image:
typedef enum {
   UIImageOrientationUp,
   UIImageOrientationDown ,   // 180 deg rotation
   UIImageOrientationLeft ,   // 90 deg CW
   UIImageOrientationRight ,   // 90 deg CCW
   UIImageOrientationUpMirrored ,    // as above but image mirrored along
       // other axis. horizontal flip
   UIImageOrientationDownMirrored ,  // horizontal flip
   UIImageOrientationLeftMirrored ,  // vertical flip
   UIImageOrientationRightMirrored , // vertical flip
} UIImageOrientation;

In your code you are passing 0, which means UIImageOrientationUp enum value, for you it looks like default image of course.
So you need to specify this parameter to what kind of orientation you want.
E.g. following code will do vertical image flip:
UIImage *images = [UIImage imageWithCGImage:[rep fullScreenImage] scale:[rep scale] orientation: UIImageOrientationLeftMirrored];


text:
Q: custom template not working in django formtools I have been trying to add a multi page form in my Django application using the formtools wizard. I need to setup custom forms for each step. There are 2 steps in total. Here is the code that I have:
views.py
TEMPLATES = {"initial": "my_app/form_initial.html",
         "final": "my_app/form_last.html"}

class ModelCreateView(SessionWizardView):
    model = MyModel
    template_name = "my_app/model_form.html"
    file_storage =
    FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'custom'))

    def get_template_names(self):
        return [TEMPLATES[self.steps.current]]

my_app/model_form.html
{% extends "my_app/base.html" %}

{% block extra_css %}
{{ wizard.form.media }}
{% endblock %}

{% block content %}
<form action="" method="post">
{% csrf_token %}
    {{ wizard.management_form }}

{{ wizard }}

    {% if wizard.form.forms %}

{{ wizard.form.forms }}

        {{ wizard.form.management_form }}
        {% for form in wizard.form.forms %}
            {{ form }}
        {% endfor %}
    {% else %}
        {{ wizard.form }}
    {% endif %}
    <input type="submit" value="submit"/>
</form>
{% endblock content %}

my_app/form_initial.html
 <-- custom form template for step 1 -->

my_app/form_last.html
 <-- custom form template for step 2 -->

if I understand it correctly, the custom form templates will replace the
{{ form }}

tag in the base template being called(my_app/model_form.html).
My problem here is that, with the current code, the  my_app/form_initial.html is being called directly.
Also if I try to just include
{{ wizard.management_form }}

in my_app/form_initial.html and enclose the necessary form elements, on submit, it just reloads the current page rather than taking me to my_app/form_last.html
Please let me know what am I doing wrong here.
UPDATE: I fixed the issue with custom template by properly extending the base form template. But now when I submit on the first step, the same step page reloads rather than going to the next step. Please let me know how do I debug this?
UPDATE 2: I tried debugging more and found this, my fields are not getting validated even though the post request contains the fields, the form.is_valid() returns false. The form.errors says that all the fields are missing

A: I got the wizard working in my app with an extra list of tuples to map the forms. Try this and see if it works.
WIZARD_FORMS = [("initial", InitailFormName),
                ("final" , FinalFormName),
            ]

TEMPLATES = {"initial": "my_app/form_initial.html",
             "final": "my_app/form_last.html"}

class ModelCreateView(SessionWizardView):
    model = MyModel
    template_name = "my_app/model_form.html"
    file_storage =
    FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'custom'))

    def get_template_names(self):
        return [TEMPLATES[self.steps.current]]

A: There were 2 problems in the method that I had implemented the templates.

*

*I had assumed that the custom step form templates would be substituted in their own once a base template is defined in the view. The correct method to do this is define the base template template and extend it in the custom step template.

eg:
base_form_template.html
{% block content %}
<form style="height:inherit;" action="" method="post">
{% csrf_token %}
    {{ wizard.management_form }}
    {{ wizard.form.errors}}
    {{ wizard.form.non_field_errors}}
    {% block custom_form %}
    {% endblock %}
</form>
{% endblock content %}

step1.html
{% extends "my_app/base_form_template.html" %}

<-- custom form template code goes here -->

step2.html
{% extends "my_app/base_form_template.html" %}

<-- custom form template code goes here -->

*In my custom form template, the name attribute of the input fields need to be set to wizard.form.<model_attribute>.html_name. This was difficult to find. I had initially just set it wizard.form.<model_attribute> and wondered why it didn't work. Did some more digging and found this. The html_name is different as its of the format <step_name>_<field_name>. Looking at it now it does make sense to have names like this.

A: What Keval said is correct - the main issue that caused self.cleaned_data['field'] to be empty is that I needed to use form.field.html_name instead of form.field.name for the name field of the template.
However, this isn't all that clear from the documentation provided. Here's an excerpt from my template page, so it's even clearer:

  {{ form.account_name.label }}
  <input name="{{ form.account_name.html_name }}"
         value="{{ form.account_name.value|default_if_none:'' }}"
         class="form-control">


text:
Q: Linq: get a custom class joining to tables I'm developing a WCF RESTful service with C#, .NET Framework 4.0 and Entity Framework Code First.
I have this class:
[DataContract]
public class Group
{
    [DataMember]
    public int GroupId { get; set; }

    [DataMember]
    public String Name { get; set; }

    [DataMember]
    public String Description { get; set; }

    [DataMember]
    public String City { get; set; }

    [DataMember]
    public String Country { get; set; }

    public byte[] Photo { get; set; }

    public virtual ICollection<User> Users { get; set; }
}

And this class:
public class User
{
    [DataMember]
    public int UserId { get; set; }

    [DataMember]
    public string Name { get; set; }

    public virtual ICollection<Group> Groups { get; set; }
}

I want to retrieve a group using its GroupId and all its members (as an array of UserId).
Now, I have this sentence:
var groups = from g in context.Groups
where g.GroupId == groupId
select g;

But I don't know how can I get member's UserId.
I want to get a custom class like this one:
[DataContract]
public class CustomGroup
{
    [DataMember]
    public int GroupId { get; set; }

    [DataMember]
    public String Name { get; set; }

    [DataMember]
    public String Description { get; set; }

    [DataMember]
    public String City { get; set; }

    [DataMember]
    public String Country { get; set; }

    [DataMember]
    public ICollection<int> UsersIds { get; set; }
}

How can I do that?

A: var result = context.Groups.Where(g=>g.GroupId == groupId)
                    .Select(e=> new CustomGroup(e));
//With your CustomGroup class should looks like this:

[DataContract]
public class CustomGroup  //You should consider some inheritance relationship here
   public CustomGroup(Group g){
      GroupId = g.GroupId;
      Name = g.Name;
      Description = g.Description;
      City = g.City;
      Country = g.Country;
      UsersIds = g.Users.Select(u=>u.UserId).ToList();
   }
   //....
   [DataMember]
   public ICollection<int> UsersIds { get; set; }
}

A: If I understood your question correctly, you'd do this:
var members = context.Groups.Where(group => group.GroupId == groupId).SelectMany(g => g.Users.Select(usr => usr.UserId));


text:
Q: Storing values from a cookie into an array in PHP? I've looked through a million different websites and I can't seem to find an answer—is there a way to get info from a cookie and put it into an array? I've tried directly storing $_COOKIE['name'] into an array, and that causes a server error. I've tried storing $_COOKIE['name'] as a $variable, but when I print out the array, it literally just returns $variable. Any words of wisdom out there from someone who has done this successfully?
Code (other than the actual array code, the entire page works fine):
 $productarray = array("$_COOKIE['gatq']"=>'The Great Gatsby ',
                 "$_COOKIE['catcherq']"=>'Catcher in the Rye ',
                  "$_COOKIE['wavesq']"=>'The Waves ',
                  "$_COOKIE['strangerq']"=>'The Stranger ',
                  "$_COOKIE['ulyssesq']"=>'Ulysses ',
                  "$_COOKIE['prideq']"=>'Pride and Prejudice ',
                  "$_COOKIE['mockingbirdq']"=>'To Kill a Mockingbird ',
                  "$_COOKIE['roadq']"=>'On the Road '
                  );

if ($_COOKIE['fname'] == NULL or $_COOKIE['lname'] == NULL or $_COOKIE['address'] == NULL or $_COOKIE['city'] == NULL or $_COOKIE['state'] == NULL or $_COOKIE['zip'] == NULL)
{echo "";
}

else
    {
        if ($_COOKIE['gatq'] == NULL &&
            $_COOKIE['catcherq'] == NULL &&
            $_COOKIE['wavesq'] == NULL &&
            $_COOKIE['strangerq'] == NULL &&
            $_COOKIE['ulyssesq'] == NULL &&
            $_COOKIE['prideq'] == NULL &&
            $_COOKIE['mockingbirdq'] == NULL &&
            $_COOKIE['roadq'] == NULL)

                {echo "";
                }

                        else
                            {

                                asort($productarray);
                                foreach ($productarray as $book=>$info)
                                            {if ($book != NULL)
                                                    echo $book . "$info\n";
                                            }
                                echo $productarray;
                                echo "testing";

                            }

    }
?>

The error just says "server error," which is the same error I get anytime I have any kind of syntax error.

A: Variables aren't expanded inside single-quoted strings. Just use $_COOKIE['name'] as the array key directly.
$productarray = array($_COOKIE['gatq']=>'The Great Gatsby ',
                  $_COOKIE['catcherq']=>'Catcher in the Rye ',
                  $_COOKIE['wavesq']=>'The Waves ',
                  $_COOKIE['strangerq']=>'The Stranger ',
                  $_COOKIE['ulyssesq']=>'Ulysses ',
                  $_COOKIE['prideq']=>'Pride and Prejudice ',
                  $_COOKIE['mockingbirdq']=>'To Kill a Mockingbird ',
                  $_COOKIE['roadq']=>'On the Road '
                  );

I'm not sure what you're really trying to do here, though. Why would the values of cookies be the keys of an associative array? What's in $_COOKIE['gatq'], for instance?
I think what you really want is a 2-dimensional array:
$productarray = array(
                  array('quantity'=>$_COOKIE['gatq'], 'title'=>'The Great Gatsby '),
                  array('quantity'=>$_COOKIE['catcherq'], 'title'=>'Catcher in the Rye '),
                  array('quantity'=>$_COOKIE['wavesq'], 'title'=>'The Waves '),
                  array('quantity'=>$_COOKIE['strangerq'], 'title'=>'The Stranger '),
                  array('quantity'=>$_COOKIE['ulyssesq'], 'title'=>'Ulysses '),
                  array('quantity'=>$_COOKIE['prideq'], 'title'=>'Pride and Prejudice '),
                  array('quantity'=>$_COOKIE['mockingbirdq'], 'title'=>'To Kill a Mockingbird '),
                  array('quantity'=>$_COOKIE['roadq'], 'title'=>'On the Road ')
                  );

To display this in quantity order, you can use usort() with a function that compares $element['quantity'].

A: $_COOKIE is already an array.
print_r($_COOKIE);

You would handle it like any other array.
if(!empty($_COOKIE['catcherq'])){
  $catcherq = $_COOKIE['catcherq'];
  echo $catcherq;
}

foreach($_COOKIE as $key=>$value){
  echo ("$key:$value\n");
  ${$key}=$value;
}


text:
Q: File and bundleresource:// URLs I've been breaking my head over this for quite a while now and cant find a solution for this problem:
I have an Eclipse RCP application that uses a custom library packaged as jar. From the plugin, i am calling a method within the jar.
Within this method, i am "getting" a resource using this.class.getResource(relPath), whereas relPath is a hardcoded relative path to a file i need. This returns me an URL which i can use to construct a File.
Now, this works perfectly if i am not calling this method from the plugin, but from a simple Java-Program.
The difference: Eclipse RCP's classloader returns an URL of protocol bundleresource:// which is not supported by File, whereas when running a simple Java-program, a file://-URL is returned which is completely fine to construct a File.
I am aware of the FileLocator-class of the Eclipse SDK (which resolves bundleresource-URLs to file-URLs), but i cannot use it within the library because i dont want to tie it to the Eclipse RCP platform - it should be possible to use this lib from non-Eclipse-RCP sources as well.
Anyone any idea on how i can load this resource from a relative path in a manner that will work both when the method is called from an Eclipse RCP-Plugin or any other client?
I need to construct a File on the directory of this relative path to search for files within. I am completely stuck on this...
UPDATE: If there is a possibility other than using File#list() to get directory contents this would already help me..
any hints greatly appreciated,

A: Couldn't you simply invert the dependency. I.e., your module retrieving the resource as URL defines an interface
interface Locator { URL resolve(URL url); }

and you can use a default implementation
class StandaloneLocator implements Locator {
   public URL resolve(URL url) { return url; }
}

In case of Eclipse, this default locator is to be replaced by
class EclipseLocator implements Locator {
  public URL resolve(URL url) { return FileLocator.resolve(url); }
}

Now, your library has no dependencies to Eclipse, and you can still use the FileLocator. Since you won't get any bundleresource-URLs w/o Eclipse, this should work.
Cheers,
Jens

A: That is not possible to enumerate files in jar file using methods from Class. You either need to create resourcelist file which will contain all your resources names, or open jar file like zip archive and enumerate files like in zip archive. File class can not handle protocols other than file://. If your rescource is in jar file, you should use Url class and get stream using Url.openSteram method to get file contents.
UPD regarding running simple java application: you probably does not pack it into jar file, so your classes and resources are placed in file system and not in archive. That is why you get file:// protocol. If you pack into jar file, protocol will not be file:// it will be jar:// (not sure about exact protocol name).


text:
Q: Заморочка с if Добрый день господа, есть некий код:
#include <iostream>
using namespace std;
void main()
{
    int kol=0,n,ob,sum=0;
    cout<<"Enter the nubmer: ";
    cin>>n;
    if(n<0) n=-n;
    if(n<850000000)
    {
        cout<<"Telo"<<endl;
    }
    else cout<<"Number too great or incorrect!\n";
}

Так вот, если мы вводим числа содержащие 10 и более знаков, а также буквы, то мы успешно получаем "Number too great or incorrect!". Но, если нам убрать строчку "if(n<0) n=-n;" из кода, то при вводе букв и чисел, содержащих 10+ знаков мы будем входить в цикл и получать надпись "Telo". Почему так происходит и как тогда сделать правильную проверку, если ввели число превышающее 850000000 или букву(символ)?
A: Переполнение типа. int чаще всего вмещает 32 бита информации, один из которых знаковый. Таким образом, переходя некий порог, число становится отрицательным (если тип signed). int обычно представляет собой 32 бита, один из которых - знаковый.
unsigned int отличен тем, что те же 32 бита считаются положительными, мы имеем 2^32 значений, что почти в два раза больше максимального signed int.
Стоит почитать о представлении типов данных в памяти компьютера. С float/double там еще интереснее.
Для очень больших целых чисел есть еще long и long long (с версиями unsigned)
http://ru.wikipedia.org/wiki/Limits.h
A: Вводите строку и пробуйте распарсить её в число (надеюсь, вы знаете, как). Если не получилось — число слишком большое, или содержит нечисловые символы, или ещё что-нибудь такое.


text:
Q: remote: fatal: unresolved deltas left after unpacking Im working on window environnement and I have a remote git repository on the network.
Created using
git init --bare

Then I clone the project on my local, I can work on it commit and push.
But at a moment, i could'nt push anymore with the following error:
Counting objects: 21, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (19/19), done.
Writing objects: 100% (21/21), 1.93 KiB | 0 bytes/s, done.
Total 21 (delta 15), reused 0 (delta 0)
remote: error: object directory /SERVER/Apps/myApp.git/objects does not exist; check .git/objects/info/alternates.
remote: fatal: unresolved deltas left after unpacking
error: unpack failed: unpack-objects abnormal exit
To //SERVER/Apps/myApp.git
 ! [remote rejected] master -> master (unpacker error)
error: failed to push some refs to '//SERVER/Apps/myApp.git'

So I tried to create another repo and same happend...
do you have any clue about how this error happened and how to fix it ?
Thanks
EDIT
core.symlinks=false
core.autocrlf=true
core.fscache=true
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=true
help.format=html
http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
diff.astextplain.textconv=astextplain
rebase.autosquash=true
credential.helper=manager
user.name=Flim
user.email=flim@myMail.com
alias.tree=log --oneline --decorate --all --graph
core.repositoryformatversion=0
core.filemode=false
core.bare=false
core.logallrefupdates=true
core.symlinks=false
core.ignorecase=true
remote.origin.url=//SERVER/Apps/myApp.git
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
branch.master.remote=origin
branch.master.merge=refs/heads/master

A: So close! This will be fixed in the upcoming Git 2.12 (Q1 2017).
See "Git push fail to a Windows share"

normalize_path_copy() is not prepared to keep the double-slash of a
  //server/share/dir kind of path, but treats it like a regular POSIX
  style path and transforms it to /server/share/dir.

So it works the first time, then the wrong path gets registered and then, it does not work anymore.
As a workaround for now, see if you can not map that shared path to a drive letter.
net use z: \\SERVER\Apps

See "Map network drive command line".
Then use that path as your remote origin url.
cd C:\path\to\my\local\repo
git remote set-url origin Z:\myApp.git


text:
Q: After upgrade to 20.04: "Sorry, there is nothing that matches your search" I just upgraded from 18.04LTS to 20.04, and now my desktop search function for applications always says "Sorry, there is nothing that matches your search".  The search for other types of files is not working either.
I do not think I have any gnome-shell-extensions either, as another post has suggested as a problem.
Any ideas?

A: I solved my problem.  Somehow during the upgrade I got switched to Unity.  Switching back to gnome solved the problem.


text:
Q: Splitting multiple joined words without delimiters I'm building a word ranking system which should be noise-tolerant, meaning that it should work with words like aaaaabbccccc, where aaaaa, bb and ccccc are some random words.
The problem itself requires a dictionary, which I'm not allowed to use, but in my instances there are big chances to have the single words in the dataset, so I thought to exploit this information to create a splitter that works without an explicit dictionary.
What I'd like to do tho is to have this working in a single iteration while adding words to results map.
Here's a quick scenario of what I mean:
input words
word1
composedword1
1
abiggercomposedword1
bigger
abigger

*

*Step 1

*

*Read word1

*Check if result contains a word containing word1 or a word contained by word1

*No, add word1 to result
result:
{word1}

*

*Step 2

*

*Read composedword1

*Check if result contains a word containing composedword1 or a word contained by composedword1

*Yes, word1 is contained in composedword1

*Add spaces before and after word1 inside composedword1

*Remove word1 from result

*Add composed word1 to result
result:
{composed word1} // Note that this is still a single word!

*

*Step 3

*

*Read 1

*Check if result contains a word containing 1 or a word contained by 1

*Yes, 1 is contained in composed word1

*Add spaces before and after 1 inside composed word1

*Remove composed word1 from result

*Add composed word 1 to result
result:
{composed word 1}

Things work fine until the next step.

*

*Step 4

*

*Read abiggercomposedword1

*Check if result contains a word containing abiggercomposedword1 or a word contained by abiggercomposedword1

*No, because result contains a single word separated by spaces. It would've worked if that word was separated in different strings.
Now, given this scenario, here's the code that I'm using (the one working until step 4):
// Map between word and score
for (Map.Entry<String, Integer> word : words.entrySet()) {
    boolean hasMergedWords = false;
    // result is the final HashMap, calling new to avoid concurrent modification
    for (Map.Entry<String, Integer> resultWord : new LinkedHashMap<>(result).entrySet()) {
        String wordToCheck = resultWord.getKey().trim();
        String currentWordToCheck = word.getKey().trim();
        if (currentWordToCheck.contains(wordToCheck)) {
            // Merge provided word into topWord
            result.put(currentWordToCheck.replace(wordToCheck, " " + wordToCheck + " ").trim().replaceAll(" +", " "), result.get(wordToCheck) + word.getValue());
            result.remove(wordToCheck);
            hasMergedWords = true;
        } else if (wordToCheck.contains(currentWordToCheck)) {
            result.put(wordToCheck.replace(currentWordToCheck, " " + currentWordToCheck + " ").trim().replaceAll(" +", " "), result.get(wordToCheck) + word.getValue());
            result.remove(wordToCheck);
            hasMergedWords = true;
        }
    }
    if (!hasMergedWords) {
        // Nothing was merged so we add current word
        result.put(word.getKey(), word.getValue());
    }
}

Finally, the question: can someone help me dealing with the case found in step 4? My first idea was to split each word in result using spaces as separators, but this will cause issues when merging their scores.
EDIT: expected result is result = {a bigger composed word 1}, a single string in which each word is separated by a space.


text:
Q: Receive syntax error when installing gem on Ruby I'm trying to install a gem using Ruby. I keep getting a weird syntax error when I do. Using rvm, latest version, to install. The error message is:
  /Users/george/.rvm/rubies/ruby-2.1.5/lib/ruby/2.1.0/psych.rb:370:in `parse': (<unknown>): mapping values are not allowed in this context at line 2 column 30 (Psych::SyntaxError)
    from /Users/george/.rvm/rubies/ruby-2.1.5/lib/ruby/2.1.0/psych.rb:370:in `parse_stream'
    from /Users/george/.rvm/rubies/ruby-2.1.5/lib/ruby/2.1.0/psych.rb:318:in `parse'
    from /Users/george/.rvm/rubies/ruby-2.1.5/lib/ruby/2.1.0/psych.rb:245:in `load'
    from /Users/george/.rvm/rubies/ruby-2.1.5/lib/ruby/site_ruby/2.1.0/rubygems/config_file.rb:333:in `load_file'
    from /Users/george/.rvm/rubies/ruby-2.1.5/lib/ruby/site_ruby/2.1.0/rubygems/config_file.rb:198:in `initialize'
    from /Users/george/.rvm/rubies/ruby-2.1.5/lib/ruby/site_ruby/2.1.0/rubygems/gem_runner.rb:74:in `new'
    from /Users/george/.rvm/rubies/ruby-2.1.5/lib/ruby/site_ruby/2.1.0/rubygems/gem_runner.rb:74:in `do_configuration'
    from /Users/george/.rvm/rubies/ruby-2.1.5/lib/ruby/site_ruby/2.1.0/rubygems/gem_runner.rb:39:in `run'
    from /Users/george/.rvm/rubies/ruby-2.1.5/bin/gem:21:in `<main>'

I also get this error when trying to set rvm to use a different ruby version.

A: There's an error in your rubygems config file. If you're not using a custom config file, look for a file .gemrc in your home folder. It seems there's incorrect content on line 2.
Psych is a YAML parser, so look for something that is incorrect YAML.

A: It looks like there was an issue in the .gemrc file as well as some other files created in the root folder that were affecting RVM from installing Ruby correctly.
Re-storing the files to the previous state and removing the junk files with rm -rf got everything working.