text:
Q: Keep java 6 along with newer java versions (for photoshop cs5)? I have adobe photoshop cs5 on a mac that was updated to yosemite. The yosemite update brought me to java v7. Trying to start photoshop now results in an error dialog telling me that photoshop needs java 6. There's a link in the error dialog about downloading the legacy version:
https://support.apple.com/kb/DL1572?locale=en_US
is it possible to just install that legacy version and leave it side by side with the newer version 7? I don't want to install the legacy java6 version if it'll overwrite my v7 java install.
Thanks


text:
Q: copy output in front of specific characters (:*:) from each line in a list using Notepad ++ or in linux I have a list where I would like to copy every word in from of :* on each line to create a new list.
for example
current list -
 - ftp1:*:1737:199:User &:/home/ftp1:/bin/clish
 - juan:*:1738:199:User &:/home/juan:/bin/clish
 -  kevin:*:1739:199:User &:/home/kevin:/bin/clish
 -  mailer:*:1740:199:User &:/home/mailer:/bin/clish

new list or file -
 - ftp1
 - juan
 - kevin
 - mailer

A: *

*Ctrl+H

*Find what: ^([^:]+).*$

*Replace with: $1

*Replace all
Explanation:
^         : begining of line
  ([^:]+) : group 1, every thing that is not a colon
  .+      : 0 or more any character
$         : end of line

Replacement:
$1        : group 1

Result for given example:
ftp1
juan
kevin
mailer

A: cat inputfile | sed 's/:.*//' > outputfile

I would just delete everything from the first colon onward. I recommend you look for sed examples. There are many.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating html page header with php Firstly I'm very new to web development so forgive me if this is a stupid or repeated question.
All my web pages have the same header so I simply add the following line to the top of every page:
    <?php require('header.html') ?>

This works fine. But now I'd like to vary the image in the header depending on which page it is on. I'm thinking about using a php function like this:
    function create_header($image){
        //1. echo contents of header.html

        //2. replace default image location with $image if not null
    }

Problem is I don't know how to do steps 1 or 2.  Is this possible and/or is there a better way of doing what I want?

A: You could always use a PHP page for your header, and pass it whatever image you wanted through GET.
header.php
<?php
    if (isset($_GET['img']))
        echo ''; //The brackets allow for complex variables in double quoted strings
    else
        echo ''
?>

page.php
<?php
    function create_header($image) {
       require('header.php?img=' . $image);
    }
?>

A: You should use some basic form of templating.
Let's say your header looks like this:

Welcome to my site!

If we modify it to turn the image into a variable we get this:

    <img src="images/<?php echo $header_image; ?>" alt="" />

Welcome to my site!

Now all you have to do is set your variable before you include your header file like so:
<?php
$header_image = "image2.jpg";
include "header.html";
?>

This concept of basic templating can be applied to an entire page template and is not limited to header files.


text:
Q: Lift of a continuous map $f:Y\to X$ to a covering space $Z$ given that loops in $Y$ lift to loops in $Z$ Suppose $X, Y$, and $Z$ are topological spaces. If necessary, you may assume that they are nice (manifolds). I am looking for the following result to be true even without this assumption however, so any comments to that effect would also be appreciated.
Let $p:Z\to X$ be a covering map. Let $f:Y\to X$ be a continuous map. Let $x_0\in X$, $y_0\in Y$, $z_0\in Z$ be such that $f(y_0)=x_0=p(z_0)$. Assume that for each loop $\gamma$ at $y_0$ in $Y$, there is a loop $\tilde{\gamma}$ at $z_0$ in $Z$ such that $f\circ \gamma$ is homotopic to $p\circ \tilde{\gamma}$ in $X$ with endpoints both fixed at $x_0$ by the homotopy.
Prove that $f$ lifts to a continuous map $\tilde{f}:Y\to Z$ with $\tilde{f}(y_0)=z_0$.
Overall, it is entirely unclear to me why such a lift should even exist. The standard results concerning relations between fundamental groups are not something that I wish to employ since there are no restrictions on the spaces, nor do I think this would even be helpful. Any comments at all would be appreciated.

A: You say you do not want to use fundamental groups, but this does not make sense.
In terms of fundamental groups, your condition means that $f_*(\pi_1(Y,y_0)) \subset p_*(\pi_1(Z,z_0))$. It is a well-known theorem that for $Y$ path-connected and locally path-connected this condition is equivalent to the existence of a lift of $f$. See for example Proposition 1.33 in Hatcher's "Algebraic Topology". Hatcher also gives an example showing that the local path-connectedness assumption cannot be omitted.
You can of course copy Hatcher's (fairly short) proof without mentioning fundamental groups, but what would be the benefit?


text:
Q: How can I set specific compiler flags for a specific target in a specific build configuration using CMake? I've got a CMakeLists where I want to build some targets using the dynamic version of the C runtime, and some other targets using the static version.
Because this needs to be set per target, the default method of setting CMAKE_CXX_FLAGS_<Config> does not work; this overrides for all targets.
To that end, I tried something like the following:
# @fn       set_target_dynamic_crt
# @brief    Sets the given target to use the dynamic version of the CRT (/MD or
#           /MDd)
# @param    ...  A list of targets to which this setting should be applied.
function( set_target_dynamic_crt )
    if ( MSVC )
        message (WARNING ${CMAKE_BUILD_TYPE})
        if (CMAKE_BUILD_TYPE STREQUAL "Debug")
            set_target_properties ( ${ARGN} PROPERTIES COMPILE_FLAGS "/MDd" )
        else()
            set_target_properties ( ${ARGN} PROPERTIES COMPILE_FLAGS "/MD" )
        endif()
    endif()
endfunction()

However, this always chooses the release version  (/MD) and when I query for the build type (the message call above) I get the empty string. (I suspect this is because I'm using the Visual Studio generator; I've seen more than one reference that says CMAKE_BUILD_TYPE is for makefiles only...)
How can I set compile options like this per target?

A: In CMake 2.8.12 I added a target_compile_options command to address this need:
http://public.kitware.com/Bug/view.php?id=6493
http://www.cmake.org/cmake/help/git-master/manual/cmake-generator-expressions.7.html
target_compile_options(tgt PRIVATE "/MD$<$<CONFIG:Debug>:d>")

See
http://www.cmake.org/cmake/help/git-next/manual/cmake-buildsystem.7.html#build-specification-with-generator-expressions
for more relating to CMAKE_BUILD_TYPE and several reasons why the generator expression is better (eg IMPORTED target config mapping).

A: The only option I know of for this scenario is to split your project into subdirectories on a per-target basis and use add_subdirectory.
Depending on how your project is currently set up, this could be a painful process I guess.
The result would be a top-level CMakeLists.txt that looked like e.g.
cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
project(Test)
add_subdirectory(libB)
add_subdirectory(libA)
add_executable(main_exe "main.cpp")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MD")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MDd")
target_link_libraries(main_exe lib_a lib_b)

then libA/CMakeLists.txt could specify MD and MDd flags:
project(LibA)
add_library(lib_a a.cpp a.hpp)
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MD")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MDd")

and libB/CMakeLists.txt for MT and MTd flags:
project(LibB)
add_library(lib_b b.cpp b.hpp)
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MTd")

You can of course add all targets needing linked to the static CRT in the one subdirectory and CMakeLists.txt and all the dynamic CRT ones in the other if you have a lot of targets.

A: CMAKE_BUILD_TYPE is only valid for single-configuration generators. The multi-configuration generators (MSVC and Xcode) can build for multiple configurations in one build-directory and as such the CMAKE_BUILD_TYPE flag wouldn't have a meaning.
The COMPILE_FLAGS target property does not distinguish different configurations (See kitware bugtracker for more information).
A workaround would be to have two build-directories, similar to how people use the Makefile generators, and define an additional flag when building binaries for distribution. (ie, the Release configuration)

A: Assume that I want to add -On options to vmovq_n_u8.c and generate vmovq_O3.out and vmovq_O0.out. I had it done with target_compile_options by following:
add_executable(vmovq_O3.out vmovq_n_u8.c)
add_executable(vmovq_O0.out vmovq_n_u8.c)

target_compile_options(vmovq_O3.out PRIVATE -O3)
target_compile_options(vmovq_O0.out PRIVATE -O0)


text:
Q: Angular2, How to use JSON data in service.ts? todo.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';

@Injectable()
export class TodoService {

    public todos
    constructor(private http:Http) { }
    getDatas(){
        this.http.get('../json/test_data.json')
            .map((res:Response) => res.json())
            .subscribe(
            data => {this.todos = data},
            err => console.error(err),
            () => console.log('done')
        );
    }
    get(query = ''){
      return new Promise(resolve => {
        var data;
        var todos = this.getDatas();
        console.log("todos ================== " + todos)
        if(query === 'completed' || query === 'active'){
          var isCompleted = query === 'completed';
        //   data = todos.filter(todo => todo.isDone === isCompleted);
        } else {
          data = todos;
        }
        resolve(data);
      });
    }
}

todo.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { TodoService } from './todo.service';

@Component({
  selector: 'app-todo',
  templateUrl: './todo.component.html',
  styleUrls: ['./todo.component.css'],
  providers: [TodoService]
})
export class TodoComponent implements OnInit {

    private todos;
    private activeTasks;
    private newTodo;
    private path;

    constructor(private todoService: TodoService, private route: ActivatedRoute) { }

    getTodos(query = ''){
      return this.todoService.get(query).then(todos => {
        this.todos = todos;
        // this.activeTasks = this.todos.filter(todo => todo.isDone).length;
      });
    }

    ngOnInit() {
        this.route.params.subscribe(params => {
            this.path = params['status'];
            this.getTodos(this.path);
        });
    }
}

I think, If i use "getDatas(){...getJSON...}"
I can get this data from "test_data.json" file.
and i think, i can put this data to "this.getDatas();"
But when i use "console.log("todos ================== " + todos)" in todo.service.ts file, Result is "undefined".
What's the problem?

A: You can't switch back from async execution to sync execution.
If you want to execute code after data from an async call arrived, you always have to chain the calls (then, map, ...):
getDatas(){
  return this.http.get('../json/test_data.json') // <<< return the observable
        .map((res:Response) => res.json())
        .map( // <<<=== instead of subscribe
        data => {
          this.todos = data; // <<< might not be necessary (done at caller site as well)
          return data;
        } //,
        // err => console.error(err), // <<< use catch if you need to handle errors here
        // () => console.log('done') // <<< use finally if you need to do something when the request is completed
    );
}
get(query = ''){
    // var data; // <<< redundant
    return this.getDatas().map(todos =>
      console.log("todos ================== " + todos)
      if(query === 'completed' || query === 'active'){
        var isCompleted = query === 'completed';
        return data = todos.filter(todo => todo.isDone === isCompleted);
      } else {
        return todos;
      }
    });
}

getTodos(query = ''){
  return this.todoService.get(query).subscribe(todos => {
    this.todos = todos;
    // this.activeTasks = this.todos.filter(todo => todo.isDone).length;
  });
}


text:
Q: HTML How to Transition Between Pages I am currently trying to make a transition between pages on a website.
Eg: If a user were on www.example.com/About and they clicked on a link to go to www.example.com/Contact, the about page would fly out to the left, whilst the contact page would fly in from the right.
So far all I could find online was how to do this on the same page with hashtags. But I want to do this with separate pages.
is it possible?
if not is there an alternative and how to do it?
UPDATE
Ok so I did a bit more research and I found this thing called barba.js(http://barbajs.org) that seemed to do what I'm looking for. So I installed the js script file followed the instructions on the site...and it didn't work! All it did was not load my pages correctly and didn't do what it was supposed to do. Anyone know how I can use this(or if there is a better option than barba.js).
-Thanks!

A: I don't think you can do that with pure html &  js, as you load the entire page each time you click on a link if it's not an anchor.
However you can load just a part of the page,  and so apply a transition of your choice with Ajax and js
But in the end, you won't really switch from page to page, but only load the parts that you want to update. This is approximately how modern front end frameworks like Angular, React,...  are working
Here is a pure js example http://www.w3schools.com/js/tryit.asp?filename=tryjs_ajax_first
Here is a jQuery example http://www.w3schools.com/jquery/ajax_ajax.asp

A: You are talking about is page transition and it normally happens in SPA (Single Page Application) where there is no hard refresh.
If you are not working in a SPA application I don't think you can do that where you are moving from one page to another by link/button click and a hard refresh happens.
You can choose angularjs one of the famous spa/mvc framework in jvascript and us ui-router to move from one page to another. there are many other you can explore.


text:
Q: Unity - Scriptable object automation I have a requirement to automate the creation of X amount of scriptable objects from a CSV file, in the image below is an example of a manually completed one, the minimum amount of automation I need for this is the name/description/stat modifier.
The CSVtoSO class below successfully creates a SO with the name and description passed in as strings, the simple method that is called is in the base Inventoryitem class as below, the problem I have lies in the fact that I need to expose the class stat which is an enum and almost cast this as a string read in from the CSV
Ive dropped the statsEquippableItem Class at the bottom and within here I think I need an equivalent setter method but almost passing a string as the argument cast as the stats class which I dont think is possible, hopefully I have explained this post well enough, any tips would be great !
    public enum Stat
    {
        Mana,
        Stamina,
        Spirit,
        Intellect,
        Strength,
        Agility
    }

This method lives in InventoryItem
     public void SetDescription(string Description)

        {
            this.description = Description;
        }

using UnityEngine;
using UnityEditor;
using System.IO;

public class CSVToSO
{
    private static string EquipCSVLocation = "/Inventories/TestItemCSV.csv";
    [MenuItem("Utilities/generate equipment")]
    public static void GenerateEquip()
    {
        string[] allLines = File.ReadAllLines(Application.dataPath + EquipCSVLocation);

        foreach (string s in allLines)
        {
            string[] splitData = s.Split(',');

            StatsEquipableItem NewItem = ScriptableObject.CreateInstance<StatsEquipableItem>();
            NewItem.SetDisplayName(splitData[0]);
            NewItem.SetDescription(splitData[1]);

            AssetDatabase.CreateAsset(NewItem,$"Assets/Game/EquippableItems/Resources/Rare/{NewItem.GetDisplayName()}.asset");
        }
        AssetDatabase.SaveAssets();

    }

}

StatsEquipableItem Class
using System.Collections.Generic;
using UnityEngine;

      public class StatsEquipableItem : EquipableItem, IModifierProvider
    {
        [SerializeField]
        Modifier[] additiveModifiers;
        [SerializeField]
        Modifier[] percentageModifiers;

        [System.Serializable]
        struct Modifier
        {
            public Stat stat;
            public float value;
        }

        public IEnumerable<float> GetAdditiveModifiers(Stat stat)
        {
            foreach (var modifier in additiveModifiers)
            {
                if (modifier.stat == stat)
                {
                    yield return modifier.value;
                }
            }
        }

        public IEnumerable<float> GetPercentageModifiers(Stat stat)
        {
            foreach (var modifier in percentageModifiers)
            {
                if (modifier.stat == stat)
                {
                    yield return modifier.value;
                }
            }
        }
    }

A: I believe your question is "How do convert a string to an Enum value?".  If so, enum has the Parse and TryParse methods which take in a string and attempt to convert it to the enum value.
if (System.Enum.TryParse(statStringValue, out Stat statValue))
{
    Debug.Log($"Converted {statStringValue} to Stat value {statValue}");
}
else
{
    Debug.Log($"Unable to convert {statStringValue} to Stat value");
}


text:
Q: Cannot read property 'getContext' of null with a closure Usually when rendering a canvas you wrap the code in
$(function() { ....});

However, the code I am using has a closure on the outside so it is formatted like..
(function () {...})();

I cannot fix the canvas getContext error with the $. Any ideas?

A: The problem is not because you use closure or you need to use ready handler.
But the problem is when you use jQuery the method and try to combine the  getContext method of core javascript would throw an error indicating undefined function. To  fix this you need to do like this:
var $canvas = $('#jCanvas'); //From jQuery object
$canvas[0] //To JavaScript ::  [0] is first matched element
  .getContext('2d');

Now, this way the getContext is used over javascript element and works fine.

But for simplicity I wouldn't wrap them in jQuery but just use the JavaScript:
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');


text:
Q: Using geocoder only in development or production environment I use the geocoder gem in my app, and when I run my tests, I meet the limit query error from Google. So I don't want to use it when I'm in a test environment, and I want some of my pages not to display some information when I'm in test, in order not to use the geocoder utility.
I tried this but it didn't worked, can you help me ?
app/models/location.rb

after_validation :geocode, if: :address_changed? && (Rails.env.production? || Rails.env.development? )

And
app/helpers/location.rb used in the app/views/products/index.html.erb
if Rails.env.test?
  t('location.distance.test')
else
  here.location.distance_to(there.location, :km)
end

That got me the following error message for every test I run :
 NoMethodError:
   undefined method `after_validation' for false:FalseClass

And if I remove everything in my helper and the following code in my model, I have no more error.
&& (Rails.env.production? || Rails.env.development? )

A: Write it like that:
unless Rails.env.test?
  after_validation :geocode, if: :address_changed?
end


text:
Q: Javascript regexp that matches '.' not preceded by '\' (lookbehind alternative) I am making a (Excel like) number formater function in javascript. I want to use templates like "0 000.00" and "000.000.000" which would produce:
format(123456789,"0 000.00") >> "123 456 789.00"
format(123456789,"000\.000\.000") >> "123.456.789"

So I need to match '.' not preceded by '\'. Since there is no lookbehind in javascript, what would be the regexp for splitting the whole and decimal part of a template?
This unfortunately doesn't work :-(
template.split(/(?<!\\)\./);

A: Reverse the string and use a negative lookahead instead.
template.split("").reverse().join("")
        .split(/\.(?!\\)/)
        .split("").reverse().join("");

That's a "fun" way of doing it but for your case there are other ways that may be better. Like replacing all \. with a magic string like __MAGIC__, splitting by ., then undoing the magic strings.


text:
Q: Webpack umd library return Object.default I'm writing a lib with webpack with these settings:
output: {
    path: path.join('build'),
    filename: 'my_lib.js',
    library: 'MyLib',
    libraryTarget: 'umd'
  },

MyLib:
export default function() {
  console.log('MyLib');
}

The problem is, when I try to load the build/my_lib.js in a browser, the only way to access MyLib is through MyLib.default...
Any idea?

A: the key is to use libraryExport: "default" like this:
  module.exports = {
    entry: ...,
    output: {
      path: __dirname + "/dist/",
      filename: "Template.js",
      library: "Template",
      libraryTarget: "umd",
      libraryExport: "default",
      globalObject: "this",
    },

A: If you are asking about any idea of why?
If you are using Babel to enable ES6 features then you are probably facing one of the changes between Babel5 and Babel6.
With Babel5 your code is transpiled to this:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});

exports['default'] = function () {
  console.log('MyLib');
};

module.exports = exports['default'];

But with Babel6 you get:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

exports.default = function () {
  console.log('MyLib');
};

Do you spot the difference?
module.exports = exports['default'];

This line was killed in Babel6. Here it was decided:

To always export a default to exports.default

If you are asking about any idea to workaround it?
You can add this line yourself or use some kind of babel plugin that adds it for you.
const myLib = function () {
  console.log('MyLib');
};

export default myLib;

module.exports = myLib;

A: You should set libraryExport  to default;
https://webpack.js.org/configuration/output/#outputlibraryexport


text:
Q: Intuition behind the Minkowski dimension and measure Can someone please explain the intuition behind the Minkowski dimension and measure?
I am using the definition of the Minkowski measure as
$$M^{\alpha}(K)=\lim_{\epsilon\rightarrow0}\frac{\mu(V_{\epsilon}(K))}{\epsilon^{n-\alpha}} $$
Where $K\subset\mathbb{R^n}$, $\alpha\in(0,\infty)$, and $\mu$ is the $n$-dimensional Lebesgue measure and $V_{\epsilon}$ is an $\epsilon$-neighborhood of $K$.
And the definition of the Minkowski dimension is
$$\dim_{M}(K)=\lim_{\epsilon\rightarrow0}\frac{N_{\epsilon}(K)}{\ln(\frac1{\epsilon})}$$
Where $N_{\epsilon}(K)$ is the minimum number of non-overlapping $n$-dimensional boxes of side length $\epsilon$ necessary to cover $K$.
I know these are largely used when working with fractals, but how does the notion of counting boxes relate.


text:
Q: Validate Map object matches json schema I have a json schema, for example:
{
  "type": "object",
  "ignoreUnknown": true,
  "properties": {
    "address" : {
      "type" : "string"
    }
  }
}

I want to check whether an object of type Map<String,Object> matches the schema or not.
The schema is received as a String.
How can I achieve this in Java? (Preferably using Jackson)
Thanks.

A: Although it isn't Jackson-based, you can do that using the everit-org/json-schema library as follows:
Map<String, Object> myInstance = ...
SchemaLoader.builder()
    .schemaJson(new JSONObject("{my-schema-json}"))
    .build().load().build().validate(new JSONObject(myInstance));

Disclaimer: I am a developer of this library


text:
Q: Animate in Y axis without moving elements below in X axis I'm trying to achieve an effect that displays more content of a section when clicked [Just like red squares in the image]using CSS and Javascript but without disturbing nearly elements "X-axis" position and without defining statically the column amount. By now what i have done moves the block below the animated content to the right. Any suggestion or library?
Thank you very much.
Image: https://www.dropbox.com/s/un0ta6ch5xr17nk/question.png?dl=0
EDIT:
Here is the fiddle, showing what happens when clicking elementos un the left:
https://jsfiddle.net/2y2vwy0b/
And the correspondiente code
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>

1

2

3

4

5

6

A: If you're not worried about supporting older browsers, you should definitely look into CSS3 Flexbox. It can do exactly what your image is describing using only CSS3 and possibly some media queries if you need to target different layouts for mobile devices.


text:
Q: Trying to relate tables in Django trying to POST request and create new location. now the filed country_id cues many troubles.
those are the classes
class Country(models.Model):
id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
country_name = CharField(max_length=255)
federal_rate = FloatField()
social_security = FloatField()
comment = CharField(max_length=255)

class Location(models.Model):
participant_id = ForeignKey('Participant', on_delete=CASCADE, related_name="locations")
country_id = ForeignKey('Country', on_delete=CASCADE, related_name="country")
start_date = DateField()
end_date = DateField()
region = CharField(max_length=255)
tax_policy = CharField(max_length=255, null=True)

Serializer
class CountrySerializer(serializers.ModelSerializer):

class Meta:
    model = Country
    fields = "__all__"

class LoactionSerializer(serializers.ModelSerializer):
country_id = CountrySerializer(many=False)

class Meta:
    model = Location
    fields = "__all__"

now the only why that I mange to join the tables are adding the country_id line in the seirializer, and whem im trying to create new location, an error occur
this is the way I'm trying to add new location
{
"start_date": "2021-10-10",
"end_date": "2021-11-18",
"region": "markian-land",
"tax_policy": "N/A",
"participant_id": "c5c1a00c-4263-418a-9f3a-3ce40a1ea334",
"country_id": "9067e71f-c6b9-4ecc-ad6b-461843063aee"
}

the Error - {"country_id": {"non_field_errors": ["Invalid data. Expected a dictionary, but got str."]}}
when i mange to send as dict, but i have another error that asking for all Country fields, so i get the specific country from data base, and when im sending it i got json error

A: You can have more details in this answer
Django Rest Framework doesn't provide this functionality, you need to create a serializer field first.
from rest_framework import serializers

class RelatedFieldAlternative(serializers.PrimaryKeyRelatedField):
    def __init__(self, **kwargs):
        self.serializer = kwargs.pop('serializer', None)
        if self.serializer is not None and not issubclass(self.serializer, serializers.Serializer):
            raise TypeError('"serializer" is not a valid serializer class')

        super().__init__(**kwargs)

    def use_pk_only_optimization(self):
        return False if self.serializer else True

    def to_representation(self, instance):
        if self.serializer:
            return self.serializer(instance, context=self.context).data
        return super().to_representation(instance)

Then use this new serializer field in Location serializer as,
class LoactionSerializer(serializers.ModelSerializer):
    country_id = RelatedFieldAlternative(queryset = Country.objects.all(),
                     serializer=CountrySerializer)

    class Meta:
        model = Location
        fields = "__all__"

Please note: You have a typo in LoactionSerializer.

A: this
country_id = ForeignKey(Country, on_delete=CASCADE, related_name="country")

A: You defined country_id as a CountrySerializer in the LocationSerializer and in the CountrySerializer, fields = "__all__" means you need to pass all the country object fields to make it work.
Try to delete country_id = CountrySerializer(many=False) in the LocationSerializer and try again.


text:
Q: force different npm modules to share same dependency Sorry for the NOOB question, I am new to npm and front end development.
I have a library (A) which needs to be a singleton but has an init to pass start up config.  I also have a library B which has library A as a dependency.  In my web client I need to reference library A directly and also library B.  I init library A in my web client.
From my investigation it looks like my web client and library B are using there own copy of library A and therefore because library A only works as a singleton, library B's call to library A is failing with undefined.
library A

library B
 |----library A

web-client
 |----library A
 |----library B
       |----library A

In my web client library A and B are referenced in package.json.  My question is is there a way to tell library B to use the library A the web-client has referenced directly?

A: This is supported in NPM 3 and higher.
One copy of library A will be installed and will be used by both library B and web-client, as long as library A version constraints match in library B and web-client dependencies.
If version constraints don't match, library B and web-client will have their own copies of library A.
It's possible to get multiple copies of library A if project dependencies weren't installed simultaneously.
In this case
npm dedupe

or removing node_modules and reinstalling dependencies with
npm i

will help.


text:
Q: Static build with PCL and OpenCV in Visual Studio 2010 I have a running project in Visual Studio 2010 using OpenCV 2.49 and Point Cloud Library 1.6 .  I am trying to make a standalone executable so I don´t need to install OpenCV and PCL in other computers to make it run.
OpenCV and PCL were installed using the precompiled binaries, and PCL also included boost (1.49) and vtk (5.8) libraries, among others.
For making the static build, I changed the Runtime Library in VS to /MT. Then, some Boost static libraries were missing, so I installed boost again (version 1.56, I believe I needed the libs with the 's').
Then I had errors like:
1>MSVCRT.lib(MSVCR100.dll) : error LNK2005: _malloc already defined in LIBCMT.lib(malloc.obj)

so I added msvcrt.lib, msvcprt.lib to the section "Ignore Specific Defaul Libraries".
Now I have errors like:
1>vtkCommon.lib(vtkVoidArray.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) public: class std::basic_ostream<char,struct std::char_traits<char> > & __thiscall std::basic_ostream<char,struct std::char_traits<char> >::operator<<(void const *)" (__imp_??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@PBX@Z)

1>vtkCommon.lib(vtkVariantArray.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) public: class std::basic_ostream<char,struct std::char_traits<char> > & __thiscall std::basic_ostream<char,struct std::char_traits<char> >::operator<<(void const *)" (__imp_??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@PBX@Z)

1>vtkCommon.lib(vtkTimerLog.obj) : error LNK2001: unresolved external symbol __imp__strncpy

1>vtkCommon.lib(vtkMath.obj) : error LNK2001: unresolved external symbol __imp__modf

1>vtksys.lib(SystemTools.obj) : error LNK2001: unresolved external symbol __imp___utime64

1>OLDNAMES.lib(unlink.obi) : error LNK2001: unresolved external symbol __imp__unlink

The vtk library is included exactly the same way as in the non-static release build. And, if I understood it correctly, .lib is an extension for a static libray.
What am I doing wrong?
EDIT: I tried using CMake, but I am getting the same kind of errors (There are a lot more):
2>vtksys.lib(SystemTools.obj) : error LNK2019: unresolved external symbol __imp___time64 referenced in function _time

2>vtkCommon.lib(vtkVariant.obj) : error LNK2019: unresolved external symbol "__declspec(dllimport) public: class std::basic_istream<char,struct std::char_traits<char> > & __thiscall std::basic_istream<char,struct std::char_traits<char> >::operator>>(short &)" (__imp_??5?$basic_istream@DU?$char_traits@D@std@@@std@@QAEAAV01@AAF@Z) referenced in function "short __cdecl vtkVariantStringToNumeric<short>(class vtkStdString,bool *,short *)" (??$vtkVariantStringToNumeric@F@@YAFVvtkStdString@@PA_NPAF@Z)

This is my CMakeList.txt:
cmake_minimum_required(VERSION 2.8 FATAL_ERROR)

project(3DVisualizerCM)

set(BUILD_SHARED_LIBS OFF)

SET(CMAKE_EXE_LINKER_FLAGS "/NODEFAULTLIB:msvcrt.lib
                            /NODEFAULTLIB:msvcprt.lib")

find_package(PCL 1.4 REQUIRED)
find_package(OpenCV REQUIRED)

include_directories(${PCL_INCLUDE_DIRS} )
link_directories(${PCL_LIBRARY_DIRS} )
add_definitions(${PCL_DEFINITIONS} )

add_executable (3D_v4
        3D_v4.cpp
        C3DVisualizer.cpp
        C3DVisualizerMultiple.cpp
        C3DVisualizerSingle.cpp
        CCameraParameters.cpp
        CImageTrack.cpp
        CImg.cpp
        CImgMultiple.cpp
        CImgSingle.cpp
        helpers.cpp
)

target_link_libraries (3D_v4 ${PCL_LIBRARIES} ${OpenCV_LIBS})

A: The precompiled vtk libraries you are using from PCL must have been compiled using /MD flag (Multithreaded DLL) in Visual Studio.  You need to recompile them using the /MT flag (Multithreaded static link).


text:
Q: How search for method in VSCode? Is there's any functionality simillar to CTRL+R of sublime in VSCode?

A: Go to Symbol workbench.action.gotoSymbol Ctrl+Shift+O (Cmd+Shift+O on a Mac).
You can reassign it to Ctrl+R.
You can also group them by typing colon @:.

A: For search method name you can use CTRL + P and then start search with #
for example : #register
Or press CTRL + T and type method name

A: Having same issue in Visual Studio editor. I simply install PHP IntelliSense extension.
You can find this extension in ctrl + shift + x search IntelliSense and install it. And then type ctrl + shift + o so you can see all method and function.

A: I found multiple options to search function/definition.
According to your convenience, you can choose one of the below options :

*

*Best shortcut: Ctrl+Shift+O and type your function name.

*Press Ctrl+P for "quick open", then you can use @ or @: The latter is handy to see all the symbols in the file grouped by classes, constants, fields, methods

*Press Ctrl+T to searches across files, not just the current file.
Thanks, @kevinvictor and @alex

A: The answer is to use Ctrl + T and start typing a method name.
(It searches for the method name in multiple files. You can use Ctrl + F to do the search in the current file.)
More detailed answer -
There are several ways to do a search in VS Code. One global way to do a search is to use Ctrl + P.
When you first click on Ctrl + P (Go to File), it shows the recently opened files.

*

*Then when you start typing in the search box not beginning with a special character like # or @, it will search for files.

*But when you start typing in the search box beginning with a special character like # or @, it will search for other things.
Ctrl + P + # - show all symbols including methods in all files
(same as shortcut: Ctrl + T)
Ctrl + P + @ - go to symbol (same as shortcut: Ctrl + Shift + O)

A: If you want to check for multiple uses of a function in VSCode another quick way to do this is
By using CTRL+CLICK (Windows) or CMD+CLICK (Mac) on the function name and then you would see a column on the right which would tell you all the other places in the file system that function has been used.


text:
Q: Reference an item in the second layer of a nested enumeration I have a nested enumeration in my Appendix that looks a little like this:

*

*Something

*Interview

       2.1 First Interview
       2.2 Second Interview

I use the following code in the Appendix:
\begin{enumerate}
\item Firstelement
\label{app:1}
\item Interviews
\label{app:interviews}
    \begin{enumerate}
    \item  first interview \label{app:int1}
    \item  second interview \label{app:int2}
    \end{enumerate}
\end{enumerate}

Now, whenever I reference one of the nested items in the text I get item 22.1 instead of item 2.1. like I would want to.
I use \ref{app:int2} when referencing in the Text.
How can I achieve this?
Note I am using a template provided by my school, which uses the following code to achieve the nested list:
\renewcommand{\labelenumii}{\theenumii}
\renewcommand{\theenumii}{\theenumi.\arabic{enumii}.}


text:
Q: How do I reference supplementary files such as tables in Excel format? Some of the information I need to include in my thesis are extremely long tables that will only be provided in the digital copy as supplementary files, most likely in Excel's XLS format or similar.
Now, these supplementary tables obviously need to be named and referenced and I would like to use the LaTeX way, i.e., not writing:
...the full list is provided in Supplementary Table 2.4.

but rather:
...the full table is provided in Supplementary Table~\ref{tab:FullList}.

and then have the expected output.
I understand this is a not-so-common scenario, so I'm wondering if this is even possible. If yes, what's the right way to do it?


text:
Q: How to make Svelte aware of custom *.d.ts files? I want to import some *.txt file as a string into a svelte component. The following typescript code raises no warning in VS Code:
// global.d.ts
declare module "*.txt" {
    const content: string;
    export default content;
}

// test.ts
import txt from "./test.txt";

However, if I try to import the same text file into a Svelte component (while global.d.ts still exists):
// Test.svelte
<script type="typescript">
    import txt from "./test.txt";
</script>

, VS Code will complain Cannot find module './test.txt' or its corresponding type declarations. ts(2307). So how to properly tell Svelte about the declarations inside global.d.ts?


text:
Q: Can apache mahout ALS work without hadoop? I tried using ParallelALSFactorizationJob, but it crashes here:
Exception in thread "main" java.lang.NullPointerException
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:1012)
    at org.apache.hadoop.util.Shell.runCommand(Shell.java:445)
    at org.apache.hadoop.util.Shell.run(Shell.java:418)
    at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:650)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:739)

Command line help mentions using filesystem, but it seems it wants hadoop. How can I run it on Windows, mahout.cmd file is broken:
"===============DEPRECATION WARNING==============="
"This script is no longer supported for new drivers as of Mahout 0.10.0"
"Mahout's bash script is supported and if someone wants to contribute a fix for this"
"it would be appreciated."

So is that possible (ALS + Windows - hadoop)?

A: Mahout is a community-driven project and its community is very strong.

"Apache Mahout is one of the first and most prominent Big Data machine
  learning platforms. It implements machine learning algorithms on top
  of distributed processing platforms such as Hadoop and Spark."

-Tiwary, C. (2015). Learning Apache Mahout.
Apache Spark is an open-source, in-memory, general purpose computing system that runs on both Windows and Unix like systems. Instead of Hadoop-like disk-based computation, Spark uses cluster memory to upload all the data into the memory, and this data can be queried repeatedly.

"As Spark is gaining popularity among data scientists, the Mahout
  community is also quickly working on making Mahout algorithms function
  on Spark's execution engine to speed up its calculation 10 to 100
  times faster. Mahout provides several important building blocks to
  create recommendations using Spark."

-Gupta, A (2015). Learning Apache Mahout Classification.
(This last book also provides a step by step guide Using Mahout's Spark shell (they don't use Windows and it isn't clear if they use Hadoop or not though). For more information on that topic, see the implementation section at https://mahout.apache.org/users/sparkbindings/play-with-shell.html.)
In addition to this, you can build recommendation engines using Spark such as DataFrames, RDD, Pipelines, and Transforms available in Spark MLlib and

in Spark, (...) the Alternating Least Squares (ALS) method is used for
  generating model-based collaborative filtering.

-Gorakala, S. (2016). Building Recommendation Engines.
At this point, there's one question still to answer before answering your question: can we run Spark without Hadoop?.
So, yes, it's possible to use ALS method on Windows using Spark (without Hadoop).


text:
Q: rails accepts_nested_attributes_for and validations... Rails 2.3.11 I have two models
class Group < AR
  has_many :permissions
  accepts_nested_attributes_for :permissions, :allow_destroy => true
end

class Permission < AR
  validates_uniqueness_of :action, :scope => [:role]
end

I can't seem to get the unique constraint on permissions to work when creating a new group, only on update.  Here's a sample output.  Does anyone know the best way to get validation to work on nested attributes and unique constraints?
sample output
> g = Group.create(:permissions_attributes => [{:role => 'admin', :action => 'one'}])
> # Now add the same permissions, should not be valid
> g.permissions_attributes = [{:role => 'admin', :action => 'one'}]
> g.valid?  # => false

That is expected.  However if I create the Group with the same permissions_attributes twice, it doesn't invalidate:
> g = Group.new(:permissions_attributes => [{:role => 'admin', :action => 'one'}, {:role => 'admin', :action => 'one'}]
> g.valid?  # => true        BUT THIS SHOULD BE FALSE!!
> g.save # => true           Oh Nos!!!

A: class Group < AR
  has_many :permissions
  accepts_nested_attributes_for :permissions, :allow_destroy => true
  validates_associated :permissions
end


text:
Q: how to change this query to use join? SELECT breakgame, Streak,
((SELECT (maxGameId - gameId) as gameGap
FROM game_result
WHERE game_result.breakgame >= kokopam.game_streak.breakgame
ORDER BY gameId DESC LIMIT 1)/ Streak) as nowWeight
FROM kokopam.game_streak, (SELECT max(gameId) as maxGameId FROM game_result ORDER BY gameId DESC LIMIT 1) maxGameId
WHERE breakgame>= 2

how to change this query to use join?
please help me

A: In first place, you should've a condition in the "where" clause that states the ID that the rows share.
Anyway, the method you're using works the same as inner join.
Select *
From tableA a, tableB b
Where a.id=b.id

Is the same as
Select *
From tableA a
Inner join tableB b on b.id=a.id

I could help you a bit more if you specify what you were trying do in the query and the columns that the tables have.


text:
Q: How to refetch graphQL useQuery? So Im trying to use client.refetchQueries.
This is my query:
  const {
    loading,
    data: resp,
    error,
    refetch,
    fetchMore,
  } = useQuery<any, getCoursesParams>(getCourses, {
        variables: {
          count: 5,
          offsetId: "",
          filter: {},
        },
        fetchPolicy: "cache-and-network",
        nextFetchPolicy: "cache-first",
        errorPolicy: "ignore",
        notifyOnNetworkStatusChange: true,
      })

And Im refetching like this:
  const refetchQv = async () => {
    const result = await client.refetchQueries({
      include: [getCourses],
      updateCache: (cache) => {
        cache.evict({ fieldName: "courses" });
      },
    });
  };

I get the result while refetching, but I dont want this result, I want the original query to be refetched, with its loading state.


text:
Q: How to keep the intersection of two borders? Im working on a maze generation webapp and i'm having troubling finding out how to render the generated maze. Its simple to create the grid, but when removing walls between cells im getting a square gap in the bottom corner of the cell where the two previous borders overlapped. Is there any way to make it so the bottom corner is always filled in?

.container{
  width: 150px;
  height: 150px;
  border-top: 10px solid black;
  border-left: 10px solid black;
}

.row{
  display: flex;
}

.cell{
  width: 50px;
  height: 50px;
  box-sizing: border-box;
  border-bottom: 10px solid black;
  border-right: 10px solid black;
}

/* CODE THAT CAUSES ISSUE */
.c5{
  border-bottom: None;
  border-right: None;
}

A: You could use pseudo class :after. Make your .c5 class position: relative and then make your .c5:after pseudo class position: absolute set your bottom and right positions to 0px and set a width and height the same as your border, 10px. It will place a 10px box over the bottom right corner of your div.
EDIT:
To make this more dynamic with changing sizes to your border, use a CSS variable to set the border-size on your maze elements, then use that same variable on your pseudo ::after class for height and width.
Note on CSS variables: CSS variables can be declared globally (:root element) or locally (selector that is using it). Since this will be used by multiple elements, declare it globally on the :root element, this way any of the roots children will have access to the variable.

Javascript in snippit is purely for display purposes to show ability to change dynamically within the roots variable, all the changing is done inside the CSS

const root = document.documentElement

const input = root.querySelector('#border-size')

input.addEventListener('change', (e) => {
if(e.target.value >= 3 && e.target.value < 25)
  root.style.setProperty('--maze-border', `${e.target.value}px`)
})
/* Set the size of your border here then
each relavent size will change dynamically */
:root {
  --maze-border: 5px;
}

p {
  width: 300px;
}

.container{
  width: 150px;
  height: 150px;
  border-top: var(--maze-border) solid black;
  border-left: var(--maze-border) solid black;
}

.row{
  display: flex;
}

.cell{
  width: 50px;
  height: 50px;
  box-sizing: border-box;
  border-bottom: var(--maze-border) solid black;
  border-right: var(--maze-border) solid black;
}

/* CODE THAT CAUSES ISSUE */
.c5{
  border-bottom: None;
  border-right: None;
  position: relative
}

.c5::after {
  content: '';
  width: var(--maze-border);
  height: var(--maze-border);
  position: absolute;
  bottom: 0px;
  right: 0px;
  background: black;
}

Set a size for your border and the pseudo ::after class selectors height and width rule will change dynamically to the variable value set in the root element for --maze-border:

<input type="number" size="5" id="border-size"> Input has a greater than 3 and a less than 25 pixel size restraint

--EDIT: Removed other example


text:
Q: C: Are #define directives global? I'm somewhat confused by #define statements. In libraries, they seem to be a means of communication across different files, with lots of #ifdefs and #ifndefs.
Having said that, I now have two files file1.c and file2.c compiled together, with #define TEST 10 inside file2.c. Yet, when I use TEST inside file2.c the compiler gives the following error message:
'TEST' undeclared (first use in this function)

Are #define directives global?

A: #defines are not global, they are just a substitution where ever they are used (if declared in the same compile unit)
They are not globals, they are not symbols, they are irrelevant at linkage, they are only relevant at pre-compilation.

A: #defined macros are global in that they do not follow normal C scoping rules.  The textual substitution from the macro will be applied (almost) anywhere the macro name appears after its #define. (Notable exceptions are if the macro name is part of a comment or part of a string literal.)
If you define a macro in a header file, any file that #includes that header file will inherit that macro (whether desired or not), unless the file explicitly undefines it afterward with #undef.
In your example, file2.c does not know about the TEST macro.  How would it know to pick up the #define from file1.c?  By magic?  Since macros perform textual substitution on the source code, there is no representation of them in the generated object files. file2.c therefore needs to know that substitution rule itself, and if you want that shared across multiple files, that #define needs to live in a common header file that your .c files #include.
If you're asking specifically about how many of the #ifdefs that you see in libraries work, many of them are likely checking against pre-defined macro names provided by the compilation environment.  For example, a C99 compiler defines a __STDC_VERSION__ macro that specifies the language version; a Microsoft compiler defines an _MSC_VER macro. (Often these predefined macros start with leading underscores since those names are reserved for the compiler.)
Additionally, most compilers allow defining simple macros as command-line arguments.  For example, you might compile your code via gcc -DNDEBUG file1.c to compile file.c with NDEBUG defined to disable asserts.

A: In case somebody reads this later, and to add some practical information:

*

*Some environments like atmel, vs, or iar, allow you to define global #define directives. They basically pass these defined values to the precompiler in some commandline format.

*You can do the same in batch commands or makefiles, etc.

*Arduino always adds a board variant (usually located at hardware\arduino\variants) to all compilations. At that point you can create a new board that contains your global define directives, and use it that way. For example, you can define a mega2560(debug) board out of the original mega2560 that contains some debug directives. You will add a reference to that variant in "boards.txt", by copy pasting some text, and properly modifying it.

At the end of the day, you will have to give that global hfile or global directive to the compiler in one way or another.

A: you should make a file1.h and put your defines there. Then in file2.c
#include "file1.h"

easy as a pie :)


text:
Q: div underneath dropdown div on mobile view I'm working on a responsive website for mobile/desktop.  Working on the nav, finally got it to display the way I wanted.  The nav menu has no dropdowns in desktop mode, so no problem there.  The problem is, when going into mobile view, that the dropdown from a hamburger menu, does not go over the div below, but instead pushes the div below down.
Here is my sample html:
    <!DOCTYPE html>

        <meta charset="utf-8">
        <title>test menu</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" type="text/css" href="css/styles.css">
        <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Lato&subset=latin,latin-ext">
        <link rel="stylesheet" type="text/css" href="css/bootstrap3.3.6.min.css">

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar2">
          Toggle navigation

        </button>

Home

About

Contact

            Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

Here is the css:
/**********************************
Responsive navbar-brand image CSS
- Remove navbar-brand padding for firefox bug workaround
- add 100% height and width auto ... similar to how bootstrap img-responsive class works
***********************************/

.navbar-brand {
  padding: 0px;
  height: 80px;
}
.navbar-brand>img {
  height: 100%;
  padding: 2px;
  width: auto;
}

/*************************
EXAMPLES 2-7 BELOW
**************************/

/* EXAMPLE 2 (larger logo) - simply adjust top bottom padding to make logo larger */
.example2 .navbar-brand {
  height: 80px;
  background-color: #fff;
}

.example2 .navbar-brand>img {
  max-width: 120px;
  height: auto;
}

.example2 .nav >li >a {
  padding-top: 30px;
  padding-bottom: 30px;
}
.example2 .navbar-toggle {
  padding: 10px;
  margin: 25px 15px 25px 0;
}
.example2 .navbar-default {
    -webkit-box-shadow: 2px 7px 6px -2px rgba(0,0,0,0.34);
    box-shadow: 2px 7px 6px -2px rgba(0,0,0,0.34);
    border-bottom: 2px solid rgba(221, 221, 221, 0.82);
    border-top: 3px solid #fff;
    text-transform: uppercase;
    color: #6d6d6d!important;
    background-color: #fff;
}
.example2 .navbar-default a {
    color: #6d6d6d!important;
    background-color: #fff;
}
.example2 .container-fluid {
  background-color: #fff;
}

.navbar-primary {
      box-shadow: 1px 1px 1px rgba(0,0,0,0.1);
    border-bottom: 2px solid rgba(221, 221, 221, 0.82);
    border-top: 3px solid #3e476d;
      text-transform: uppercase;
    color: #6d6d6d!important;
}
.navbar-primary a {
    color: #6d6d6d!important;
}

/* CSS Transform Align Navbar Brand Text ... This could also be achieved with table / table-cells */
.navbar-alignit .navbar-header {
      -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
  height: 50px;
}
.navbar-alignit .navbar-brand {
    top: 2%;
    display: block;
    position: relative;
    height: auto;
    transform: translate(0,-50%);
    margin-right: 15px;
  margin-left: 15px;
}

.navbar-nav>li>.dropdown-menu {
    z-index: 9999;
}

body {
  font-family: "Lato";
}

I took this code and modified it from codeopen
Can anybody help?

A: A bit late maybe, but your problem can be solved by setting position:absolute` on the brand name element. This way it steps out of the normal flow and doesn't bother the hamburger menu.
.navbar-brand{
    position:absolute;
}
/* This is needed to overlap the brand name */
.navbar-toggle.collapsed{
    z-index:1;
    background-color:white;
}


text:
Q: How can I use XSLT 1.0 to add structure to a non-heirarchal XML file? I have some non-heirarchal xml that has pseudo-structure. Every object declares a parent (except the "root" object) and zero or more children, but does so using ids and reference attributes rather than a nested structure. I would like to convert this to a nested structure.
<document>
    <object id="6" children="12,15"/>
    <object id="12" parent="6" children="13,18"/>
    <object id="13" parent="12" children="14,16,17"/>
    <object id="14" parent="13"/>
    <object id="15" parent="6" children="21,22"/>
    <object id="16" parent="13"/>
    <object id="17" parent="13"/>
    <object id="18" parent="12" children="23,25"/>
    <object id="19" parent="23"/>
    <object id="21" parent="15"/>
    <object id="22" parent="15"/>
    <object id="23" parent="18" children="19,24"/>
    <object id="24" parent="23"/>
    <object id="25" parent="18"/>
</document>

For the record, the actual document also contains object definitions, which the objects also reference in an attribute, similar to a class but I need to retrieve the element name from the definition by, again, reference id. At some point in the process I convert the names of each "object" to "template" or "subsection". If it simplifies things I can perform this operation after applying the structure. I also have a tokenize "function" for the children attribute, as I am using XSLT 1.0, which doesn't have it built-in.
So for the example above I would like this output:
<document>
    <object id="6">
        <object id="12">
            <object id="13">
                <object id="14"/>
                <object id="16"/>
                <object id="17"/>
            </object>
            <object id="18">
                <object id="23">
                    <object id="19"/>
                    <object id="24"/>
                </object>
                <object id="25"/>
            </object>
        </object>
        <object id="15">
            <object id="21"/>
            <object id="22"/>
        </object>
    </object>
</document>

Please keep in mind that these object elements contain other information, attributes, data, etc. These have been removed to simplify the example, but may add a layer of complexity to the problem.
If possible I would like to do this in an elegant and extensible way. I am not forced to but would prefer to use XSL 1.0 (so that it can be integrated with the existing server software).
Thank you kindly to anyone who can help me or point me in the right direction!

A: Without doing the full XSLT,  you could structure your transform like below: Basically, the template for Books would call an apply-templates for chapters,  and the template for chapters would apply-templates for topics, etc.
The key here, is putting the id from the parent into a variable, so that you can use it in subsequent apply-template calls to find the children.
<document>
   <xsl:apply-templates select="/document/book" />
</document>

<xsl:template match="/document/book">
   <xsl:variable name="bookid">
      <xsl:value-of select="@id"/>
   </xsl:variable>
   <xsl:element name="book">
      <xsl:attribute name="id">
         <xsl:value-of select="@id"/>
      </xsl:attribute>
      <xsl:apply-templates select="/document/chapter[@parent=$bookid]" />
   </xsl:element>
</xsl:template>

<xsl:template match="/document/chapter">
   Template for chapter would be replicated from the book template above
   .
   .
   .
</xsl:template>

A: This short and simple, complete transformation:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:key name="kChildren" match="object" use="@parent"/>

 <xsl:template match="/*">
   <document>
     <xsl:apply-templates select="*[not(@parent)]"/>
   </document>
 </xsl:template>

 <xsl:template match="object">
  <object id="{@id}">
    <xsl:apply-templates select="key('kChildren', @id)"/>
  </object>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:
<document>
    <object id="6" children="12,15"/>
    <object id="12" parent="6" children="13,18"/>
    <object id="13" parent="12" children="14,16,17"/>
    <object id="14" parent="13"/>
    <object id="15" parent="6" children="21,22"/>
    <object id="16" parent="13"/>
    <object id="17" parent="13"/>
    <object id="18" parent="12" children="23,25"/>
    <object id="19" parent="23"/>
    <object id="21" parent="15"/>
    <object id="22" parent="15"/>
    <object id="23" parent="18" children="19,24"/>
    <object id="24" parent="23"/>
    <object id="25" parent="18"/>
</document>

produces the wanted, correct result:
<document>
    <object id="6">
        <object id="12">
            <object id="13">
                <object id="14"/>
                <object id="16"/>
                <object id="17"/>
            </object>
            <object id="18">
                <object id="23">
                    <object id="19"/>
                    <object id="24"/>
                </object>
                <object id="25"/>
            </object>
        </object>
        <object id="15">
            <object id="21"/>
            <object id="22"/>
        </object>
    </object>
</document>

Explanation: Proper use of keys.


text:
Q: Converting to new firebase - enums Today I tried to move to the new (Google)Firebase.
Not only is the API different, but also the way data is stored in the database is different.
For instance, numbers (Double) saved in the database as "7.5" is not parsed correctly (identified as string) when it was originally written to the database this way by the old Firebase. Had to manually rewrite the database for Doubles ("7.5" to 7.5), Booleans ("true" to true) etc.
Now I come upon a new issue. I get an error when trying to write enums to the database:

FATAL EXCEPTION: main
                                                                                Process: com.aayaffe.sailingracecoursemanager, PID: 21845
                                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aayaffe.sailingracecoursemanager/com.aayaffe.sailingracecoursemanager.map.GoogleMapsActivity}: com.google.firebase.database.DatabaseException: No properties to serialize found on class com.aayaffe.sailingracecoursemanager.communication.ObjectTypes
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:172)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:145)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5832)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
                                                                                Caused by: com.google.firebase.database.DatabaseException: No properties to serialize found on class com.aayaffe.sailingracecoursemanager.communication.ObjectTypes
                                                                                at com.google.android.gms.internal.zzaix$zza.(Unknown Source)
                                                                                at com.google.android.gms.internal.zzaix.zzj(Unknown Source)
                                                                                at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                                at com.google.android.gms.internal.zzaix.zzaD(Unknown Source)
                                                                                at com.google.android.gms.internal.zzaix$zza.zzaE(Unknown Source)
                                                                                at com.google.android.gms.internal.zzaix.zzaw(Unknown Source)
                                                                                at com.google.android.gms.internal.zzaix.zzav(Unknown Source)
                                                                                at com.google.firebase.database.DatabaseReference.zza(Unknown Source)
                                                                                at com.google.firebase.database.DatabaseReference.setValue(Unknown Source)
                                                                                at com.aayaffe.sailingracecoursemanager.communication.Firebase.writeBoatObject(Firebase.java:135)
                                                                                at com.aayaffe.sailingracecoursemanager.map.GoogleMapsActivity$5.run(GoogleMapsActivity.java:284)
                                                                                at com.aayaffe.sailingracecoursemanager.map.GoogleMapsActivity.onStart(GoogleMapsActivity.java:407)
                                                                                at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1234)
                                                                                at android.app.Activity.performStart(Activity.java:6258)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2621)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2723)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:172)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:145)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5832)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

Ideas?
--EDITED--
Code:
public enum ObjectTypes {
  Gate,
  Other
}
FirebaseDatabase.getInstance().getReferenceFromUrl(c.getString(R.string.firebase_base_url)).child("test").setValue(ObjectTypes.Gate);

A: My feeling with Firebase 9.0.0 is that it adheres much more to the documentation.
Json supported formats are ( String, Long, Double, Boolean, Map, List) - from firebase docs.
The previous SDK - using Jackson - was more flexible. Eg. A String could easily be parsed to a Long in the model, as long as it's a numeric. Lists could be parsed into Arrays [], and so on... Not anymore.
This may be good or not. In one hand you lose flexibility but in the other it makes you more conscious on the defined model and what you actually deploy to the network.
With respect to enums this post may help.


text:
Q: Return Objects in php laravel I'm trying to return an object from a function but I'm getting the error is there any way I can do that?
<?php

namespace App\GraphQL\Mutations;

final class Login
{
    /**
     * @param  null  $_
     * @param  array{}  $args
     */
    public function __invoke($_, array $args)
    {

        return{
            ok: false,
            Error: "password not correct"
            token: "jhfkjnfknkfdj"
        };
}

A: Use an array casted as an object:
return (object)[
    'ok' => false,
    'Error' => "password not correct",
    'token' => "jhfkjnfknkfdj",
];

For Laravel:
return response()->json([
    'ok' => false,
    'Error' => "password not correct",
    'token' => "jhfkjnfknkfdj",
]);


text:
Q: Do you know good JMonkeyEngine tutorials and docs? I'm interested in JMonkey for some fun projects, but when I search Google to find tutorials and docs, I can only find either really basic and/or incomplete stuff, like these on http://jmonkeyengine.org/, or really specific ones. Do you know some "from beginner to expert" tutorial for JMonkey?

A: Actually, the best I found is this one:
http://www.theprogrammersweblog.com/2008/12/3d-game-programming-in-java-using.html
It's incomplete (but maybe it will be completed someday), but 11 parts are already available.
The aim is to create a complete Asteroid game.

A: Hey check this Game Making PDF

A: http://jmonkeyengine.org/wiki/doku.php/jme3 has a complete series of tutorials for jME3. They just haven't been accessible via google until now..
http://jmonkeyengine.org/wiki/doku.php/jme2:jme2 has a series of tutorials for the now community-supported old jME2


text:
Q: Asp.Net Core 3.1 server starts and then stops immediately - Why? This is a simple repro of a problem that I'm having in a larger project. I started with a basic .Net Core 3.1 CLI App and I'm just trying to start a web server listening on localhost:42420.
Here's the output and as you can see it starts and then immediately shuts down. Why? What do I have to add to the configuration make it keep running?
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:42420
infoWeb server stopped.
: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: C:\Users\skrym\source\repos\wstest\wstest\bin\Debug\netcoreapp3.1\
info: Microsoft.Hosting.Lifetime[0]
      Application is shutting down...
info: Microsoft.Hosting.Lifetime[0]
      Waiting for the host to be disposed. Ensure all 'IHost' instances are wrapped in 'using' blocks.

Note: I intentionally did not dispose the host so that I can see the extra log messages.
This is my project file:
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>
</Project>

This is all the code:
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace wstest
{
    class Program
    {
        static void Main(string[] args)
        {
            // Don't dispose this so we get all the log messages
            var host = CreateHost();
            host.Start();
            Console.WriteLine($"Web server stopped.");
        }

        private static IHost CreateHost()
        {
            var host = Host.CreateDefaultBuilder()
                .UseConsoleLifetime()
                .ConfigureWebHostDefaults(x => ConfigureWebHostBuilder(x));
            return host.Build();
        }

        private static IWebHostBuilder ConfigureWebHostBuilder(IWebHostBuilder builder)
        {
            return builder.UseStartup<SimpleStartup>()
                .UseUrls("http://localhost:42420")
                .UseContentRoot(AppContext.BaseDirectory);
        }
    }

    class SimpleStartup
    {
        public void Configure()
        {
        }
    }
}

A: The issue is with host.Start();. If you want the host to block until shut down, you need to use host.Run();.
Per the doc for IHost:

Start: Starts the host synchronously.

Run: Runs an application and block the calling thread until host shutdown.


text:
Q: Create Cookie with cross domain in laravel I have two laravel project with virtual host name 1) my.dev.com and 2) your.dev.com
I have create api for set cookie for cross domain and api is located at your.dev.com
Route::middleware('cors')->get('/hello', function () {
$cookie = Cookie::make('custom_cookie', 'hello_world', 10, "/", '.dev.com');
return response()->json('Hello worlds')->withCookie($cookie);

});
I make api call from my.dev.com and code is like this
<html>
<head>
    <title>CORS</title>
</head>
<body>
    <button type="button">Call API</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(function(){
            $("body").on("click","button",function () {
                $.get("http://my.dev.com/api/hello",function(data){
                    alert(data);
                });
            })
        });
    </script>
</body>

When I click Call API button from my.dev.com I get response Hello worlds but Cookie is not set your.dev.com

Even Cookie not set any .dev.com virtual host
I want to set Cookie at your.dev.com from my.dev.com with help of Ajax and code already posted here.
Your help would be appreciated.


text:
Q: Error module "QtQuick.Dialogs" is not installed I've got the following error upon trying to add QtQuick.Dialogs 1.(0/1/2) to my project:
qrc:/qml/main.qml:4 module "QtQuick.Dialogs" is not installed

Now here is the thing, if I create a completely new app (standard empty QtQuick application) and add this line and the file dialog example from QML FileDialog documentation, then there is no problem.
Any ideas on what the problem might be?

A: Solved it!! It turns out that the problem was that I had used windeployqt on the output folder. This conflicted with adding new qtquick components. The solution was to delete everything in the output folder and generate a clean compiled and it worked. In case it helps anyone else.


text:
Q: Python and time / datetime I've recently began work on a Python program as seen in the fragment below.
# General Variables
running = False
new = True
timeStart = 0.0
timeElapsed = 0.0

def endProg():
    curses.nocbreak()
    stdscr.keypad(False)
    curses.echo()
    curses.endwin()
    quit()

# Draw
def draw():
    stdscr.addstr(1, 1, ">", curses.color_pair(6))
    stdscr.border()
    if running:
        stdscr.addstr(1, 3, t.strftime( "%H:%M.%S", t.ctime( timeStart - timeElapsed ) ) )

        stdscr.redrawwin()
    stdscr.refresh()

# Calculate
def calc():
    if running:
        timeElapsed = t.clock() - timeStart

stdscr.border()
stdscr.addstr(1, 3, t.strftime( "%H:%M.%S", t.gmtime( t.clock() - t.clock() ) ) )

# Main Loop
while True:
    # Get Input
    kInput = stdscr.getch()

    # Close the program
    if kInput == ord('q'):
        endProg()

    # Stop the current run
    elif kInput == ord('s'):
        stdscr.addstr(1, 3, t.strftime( "%H:%M.%S", t.gmtime( t.clock() - t.clock() ) ) )
        running = False
        new = True

    # Start a run
    elif kInput == ord(' ') and new:
        running = not running
        new = not new
        timeStart = dt.datetime.now()

    # Toggle the timer
    elif kInput == ord('p') and not new:
        timeStart = dt.datetime.now() - timeStart
        running = not running

    calc()
    draw()

My program is a bit between solutions currently, sorry if something doesn't look right. I'll be more than happy to explain.
I've spent the last several hours reading online about the time and datetime modules for python, trying to figure out how I can use them to accomplish my goals, but however I've tried to implement them it's been no use.
Essentially, I need my program to measure the elapsed time from when a button is pressed and be able to display it in a hour:minute.second format. The subtraction has made it very difficult, having to implement things such as timedelta. From what I have read online there is no way to do what I'm wanting without the datetime module, but it's given me nothing but problems.
Is there an easier solution, does my code have any outstanding errors, and how stupid am I?

A: Using ˋtime.time`:
import time

star = time.time()
# run long processing...
elapsed = time.time() - start

Et voilà !

A: def draw():
    stdscr.border()
    if running:
        stdscr.addstr(1, 1, ">", curses.color_pair(8))
        stdscr.addstr(1, 3, t.strftime( "%H:%M.%S", t.gmtime( timeElapsed ) ) )

    if not running:
        stdscr.addstr(1, 1, ">", curses.color_pair(7))

    stdscr.redrawwin()
    stdscr.refresh()

# Calculate
def calc():
    if running:
        timeElapsed = t.time() - timeStart

stdscr.border()
stdscr.addstr(1, 3, t.strftime( "%H:%M.%S", t.gmtime( t.time() - t.time() ) ) )

# Main Loop
while True:
    # Get Input
    kInput = stdscr.getch()

    # Close the program
    if kInput == ord('q'):
        endProg()

    # Stop the current run
    elif kInput == ord('s'):
        running = False
        new = True

    # Start a run
    elif kInput == ord(' ') and new:
        running = not running
        new = not new
        timeStart = t.time()

    # Toggle the timer
    elif kInput == ord('p') and not new:
        running = not running
        timeStart = t.time() - timeStart

    calc()
    draw()

Well, I managed to get rid of all of the errors I was encountering. However, the time displayed is incorrect.
Since we're looking to find the elapsed time, it should start at 0 and increase. My program is starting at 12:21.xx and increasing.
Looking at my code I don't see any errors, but there's obviously one in there somewhere.


text:
Q: Generating the ADF test distribution I am trying to replicate the distributions for the Dickey-Fuller Unit Root test, but I had no success.
I tried reading the original paper (but explains more of the 70's computing than about the simulation itself) and also following the steps on Enders' "Applied Econometric Time Series" book.
Does anybody have a good source for replicating this simulation? A book? A paper? Code on any language?


text:
Q: Sending Email's using tomcat server through a PHP aplication I have deployed a PHP application on my tomcat server(Tomcat 6.0).Previously I was using XAMPP,but this needs specifically to be run on tomcat.I used this java bridge for that.Now I am not able to send mail through this,from localhost using gmail SMTP.
In XAMPP I used the sendmail.exe client for sending mails through LOCALHOST,but i don't know how to do it using tomcat.Tried to search but found hardly anything!!Badly stuck!Any pointers would be appreciated.
Thanks

A: If you are trying to send email from within your PHP application, then you want to us the built-in mail function ( http://us2.php.net/manual/en/function.mail.php). You can configure how mail behaves with various options documented on http://www.php.net/.
From PHP, you aren't going to be able to use any services provided by Tomcat for SMTP.


text:
Q: FragmentTabHost & Fragments - How do I pass data between tabs? I have a MainActivity (FragmentActivity) that has a FragmentTabHost.
public class FragmentTabs extends FragmentActivity {
    private FragmentTabHost mTabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.fragment_tabs);
        mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        mTabHost.addTab(mTabHost.newTabSpec("classA").setIndicator("Class A"),
            ClassA.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("classB").setIndicator("Class B"),
            ClassB.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("classC").setIndicator("Class C"),
            ClassC.class, null);
    }
}

ClassA, ClassB and ClassC are all Fragments (android.support.v4.app.Fragment).
I need to pass data (and call methods) on the Fragments. How can I get a reference of each of the Fragments, like this:
ClassA mClassAFragment = ???;

I've tried using getSupportFragmentManager().findFragmentByTag() and I've also tried exploring the capabilities of mTabHost. Nothing can get them.
Can you suggest a way to do this or suggest an alternative approach?

A: You can get your fragment like this:
YourFragment frag = (YourFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.fragmentid));

To send data to a fragment you can follow this approach, creating a new transaction and sending the data through a bundle.
Bundle arguments = new Bundle();
arguments.putString("some id string", "your data");
YourFragment fragment = new YourFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction().add(R.id.fragmentid, fragment).commit();

A: This can be accomplished by the 3rd argument of android.support.v4.app.FragmentTabHost.addTab(TabSpec, Class, Bundle args),
then the args can be retrieved via android.support.v4.app.Fragment.getArguments()
public class Tab1Fragment extends BaseFragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // do something with the arguments
    Log.i("DEBUG", "" + getArguments());
    // ...
}

}

A: OP here. To solve this problem I have overloaded the onAttachFragment method in my FragmentActivity:
public class FragmentTabs extends FragmentActivity {
    private FragmentTabHost mTabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
    }

    @Override
    public void onAttachFragment(Fragment fragment) {
    super.onAttachFragment(fragment);

    if (fragment.getClass() == ClassA.class) {
        ClassA mClassAFragment = (ClassA)fragment
            ...
        }
    }
}


text:
Q: exception trace does not show line number for private method after use ProGuard for example, the followng error message shows that NullPointerException thrown from line number 435 in GameController.java:
java.lang.NullPointerException
at com.fuu.mahjong.game.GameController.boolean showHint(boolean)(GameController.java:435)
at com.fuu.mahjong.game.GameViewActivity.boolean onTouch(android.view.View,android.view.MotionEvent)(GameViewAct
ivity.java:1552)
at android.view.View.dispatchTouchEvent(View.java:7122)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2176)
...

where line number 435 in GameController.java is
clearCurrentSelections();

clearCurrentSelections() is a private method in GameController, the error message does not show trace information inside clearCurrentSelections(), if I change clearCurrentSelections() to public, then the error message shows that which line in clearCurrentSelections() cause the NullPointerException.
Is there any way to show the trace information inside a private method after use ProGuard?

A: ProGuard's optimization step has probably inlined the method. The virtual machine then produces fewer lines in the stack trace. If you want to avoid this, you can disable method inlining:
-optimizations !method/inlining/*

On the Dalvik virtual machine, method inlining improves the performance though.
Whether the method is private or not shouldn't matter for the optimization, unless your configuration explicitly keeps public methods.


text:
Q: Retroactively allocating key ranges in appengine I've got about 1.5M entities in my datastore. Because of a lack of understanding on my part, some of those entities have ids that I generated myself according to an algorithm that I wrote, and others have ids that were automatically allocated by the datastore.  I understand now that this could eventually cause a conflict, since the id allocator doesn't know about the ids I generated myself.
So.  Now I want to save those entities with my ids from being overwritten by accident later.  Can I just troll through every single entity I have and use allocateKeyRange for its id? I stopped generating my own ids a long time ago - there are just a few entities in danger - but I don't know which ones.  What's the best way to save my at-risk entities?
Edit: I should note that I do store references to ids in other entities, so it will be difficult to change the id of entities without lots of cascading lookups.

A: As discussed in the comments, if the id range is different you should be able to use DatastoreService.allocateIdRange in order to reserve the ids that you already assigned to your entities manually.


text:
Q: PHP imagejpeg - Trigger Download I am using PHP imagejpeg to create a simple image like this..
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Set the content type header - in this case image/jpeg
header('Content-Type: image/jpeg');

// Output the image
imagejpeg($im);

// Free up memory
imagedestroy($im);

This is working, but i would like it to automatically trigger a download inside the browser instead of display the image.
How can I do this, do I need to set a header?

A: All you have to do is set an extra header:
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// Set the content type header - in this case image/jpeg
header('Content-Type: image/jpeg');
header('Content-Disposition: attachment; filename=file-name.jpg'); // This will tell the browser to download it

// Output the image
imagejpeg($im);

// Free up memory
imagedestroy($im);

Here is the documentation

A: I believe you need at least 3 headers:
header("Content-Type: image/jpeg"); // Content type
header("Content-Disposition: attachment; filename=file-name.jpg"); // Content deposition
header("Content-Length: $fileSize"); // YOUR FILE SIZE

otherwise, the download will not work in firefox.


text:
Q: Dividing / Shifting Assembly Differences Good morning, afternoon or night,
Having been looking at assembly code of a debug build with "Suppress JIT optimization (...)" option turned off, I have noticed the following strange behaviour (bitCount is ulong):
          int BitQuotient = (int)(bitCount / 32);

00000110  push        dword ptr [ebp+0Ch]
00000113  push        dword ptr [ebp+8]
00000116  push        0
00000118  push        20h
0000011a  call        738EF4D5
0000011f  mov         dword ptr [ebp-44h],eax

as opposed to
          int BitQuotient = (int)(bitCount >> 5);

00000110  mov         eax,dword ptr [ebp+8]
00000113  mov         edx,dword ptr [ebp+0Ch]
00000116  shrd        eax,edx,5
0000011a  shr         edx,5
0000011d  mov         dword ptr [ebp-44h],eax

Why is there such a difference in assembly? Shouldn't the compiler detect that dividing by 32 is the same as shifting right by 5 and replace the code? Also, what is that call instruction doing on the first piece of code? I suspect it has to do with the operator / being applied to non-native ulong, but that also means the compiler doesn't inline this kind of operators?
Edit: Have a look at int BitRemainder = (int)(bitCount % 32) as opposed to int BitRemainder = (int)(bitCount & 31):
00000120  mov         eax,dword ptr [ebp+8]
00000123  mov         edx,dword ptr [ebp+0Ch]
00000126  mov         ecx,20h
0000012b  cmp         edx,ecx
0000012d  jb          00000139
0000012f  mov         ebx,eax
00000131  mov         eax,edx
00000133  xor         edx,edx
00000135  div         eax,ecx
00000137  mov         eax,ebx
00000139  div         eax,ecx
0000013b  mov         eax,edx
0000013d  xor         edx,edx
0000013f  mov         dword ptr [ebp-48h],eax

and
00000120  mov         eax,dword ptr [ebp+8]
00000123  and         eax,1Fh
00000126  mov         dword ptr [ebp-48h],eax

Thank you very much.

A: The code in your first snippet performs a 64-bit divide.  The x86 jitter doesn't generate machine code for that inline, there would be too much of it.  It relies on a helper function named JIT_ULDiv.  This is a common strategy for the jitter, or for a C compiler for that matter.  You can see the kind of helper functions the jitter can use in the SSCLI20 source code, clr/src/vm/jithelpers.cpp source code file.  The helper functions for long and ulong arithmetic are at the top of the file.
The second snippet does a 32-bit divide, requiring few enough machine code instructions to be generated in-line.  Converting the divide to a shift is a simple optimization.


text:
Q: How to put these metrics into a formula to describe their dependency on each other? I'm not a mathematician - far from that, but in a current task I think about, I come to idea, that the solution can be found only on mathematics way.
I have five metrics, and I want to get a formula, which describes, how these metrics are relying to each other.
There are two sets of metrics.
The first metrics set describes keyword. It contains

*

*keyword,

*its monthly search volume (how many users search it on Google),

*competition (which is from 0 to 1 and describes whether there are many websites, who want trigger ads with this keyword) and

*suggested bid (which displays, divided by a million, the CPC, cost-per-click - the click price, which is paid by advertiser to Google, if somebody clicks on te ad triggered by this keyword).

Here is the first metrics set:
+-----------+-----------------------+-------------+---------------+
| Keyword   | Monthly Search Volume | Competition | Suggested Bid |
+-----------+-----------------------+-------------+---------------+
| keyword 1 | 110000                | 0.840621281 | 6826196       |
+-----------+-----------------------+-------------+---------------+
| keyword 2 | 12100                 | 0.773800314 | 6156644       |
+-----------+-----------------------+-------------+---------------+
| keyword 3 | 5400                  | 0.94185553  | 8001839       |
+-----------+-----------------------+-------------+---------------+
| keyword 4 | 1900                  | 0.790711928 | 3700900       |
+-----------+-----------------------+-------------+---------------+

The second metrics set describes a pair keyword-domain and contains

*

*keyword,

*domain,

*ranking place (where Google shows the domain's url for this keyword).

To the ranking place from this metrics set belongs additional metric - CTR.
CTR is click-through-rate, which is probability in per cent of the fact user clicks on the url in search results. Click-through-rate applies like a bonus only to the first 20 ranking places.
Here are keywords ranking places and urls.
+-----------+---------------+------------------------+
| Keyword   | Ranking Place | URL                    |
+-----------+---------------+------------------------+
| keyword 1 | 1             | https://example.com/p1 |
+-----------+---------------+------------------------+
| keyword 2 | 8             | https://example.com/p2 |
+-----------+---------------+------------------------+
| keyword 3 | 19            | https://example.com/p3 |
+-----------+---------------+------------------------+
| keyword 4 | 29            | https://example.com/p4 |
+-----------+---------------+------------------------+

And here are CTRs for all 20 ranking places.
+---------------+--------------------+
| Ranking Place | Click Through rate |
+---------------+--------------------+
| 1             | 45.99              |
+---------------+--------------------+
| 2             | 21.12              |
+---------------+--------------------+
| 3             | 13.51              |
+---------------+--------------------+
| 4             | 8.36               |
+---------------+--------------------+
| 5             | 5.71               |
+---------------+--------------------+
| 6             | 3.96               |
+---------------+--------------------+
| 7             | 2.96               |
+---------------+--------------------+
| 8             | 2.10               |
+---------------+--------------------+
| 9             | 1.66               |
+---------------+--------------------+
| 10            | 1.29               |
+---------------+--------------------+
| 11            | 1.17               |
+---------------+--------------------+
| 12            | 1.14               |
+---------------+--------------------+
| 13            | 1.41               |
+---------------+--------------------+
| 14            | 1.46               |
+---------------+--------------------+
| 15            | 1.54               |
+---------------+--------------------+
| 16            | 1.56               |
+---------------+--------------------+
| 17            | 1.33               |
+---------------+--------------------+
| 18            | 1.15               |
+---------------+--------------------+
| 19            | 0.90               |
+---------------+--------------------+
| 20            | 1.02               |
+---------------+--------------------+

What I want: I want to calculate a parameter as reliance of all metrics on each other. I would name it visibility of certain keyword.
Example: the visibility of certain keyword would be like

I'm very unsure in my math and would be happy about any advice!


text:
Q: Can I skip eva's assertion on signed overflow? Sample code:
void main(){
    unsigned int x;
    x = 1U << 31;  // OK
    x = 1 << 31; // Sign overflowed
    return;
}

frama-c-gui -eva main.c:
void main(void)
{
    unsigned int x;
    x = 1U << 31;
    /*@ assert Eva: signed_overflow: 1 << 31 ≤ 2147483647; */
    x = (unsigned int)(1 << 31);
    return;
}

Get red alarm because of signed overflow on line 4. I have existing code with ton of hardware registers defined with mask bits and shifting bits like this. It's unreasonable to modify the code add "U" for all the mask bits. Is there a option in eval plugin to treat these constants as unsigned integer?

A: There are some options in the kernel to control which kinds of alarms should be emitted (see frama-c -kernel-h or the manual, especially its section 6.3, for more information).
In your particular case, you are probably interested in -no-warn-signed-overflow, that will disable alarms related to overflows on signed arithmetic. Eva will then assume 2-complement arithmetic, and emit a warning about that if the situation occurs, but only once for the whole analysis.


text:
Q: Bookmarklet doesnt working on Mozilla but does in chrome i wrote this bookmarklet
test

and it is working in Chrome, but not in Mozilla Firefox
i even tried
test

but it doesn't work too
what am i doing wrong?

A: These are the steps I recommend for making bookmarklets:
1. Put everything in an immediately invoked function
You can use (function(){YOUR CODE}()); or (function(){YOUR CODE})();
2. Minify your code
You can use an online JavaScript uglifier
3. URL-encode it
You can use an online URL-encoder
In your case it could be something like this:
(function(){m=document.getElementById('xxx');m.value=17}());

encoded as:
(function()%7Bm%3Ddocument.getElementById('xxx')%3Bm.value%3D17%7D())%3B

See DEMO.

A: It is not working because FF expects to follow the link to somewhere. This piece of code works
test

But consider making your code unobtrusive. This may help you


text:
Q: MSSQL join with itself I have two tables:
id
1
2
3
4

t1 AND t2
id | related_id
1  | 2
1  | 3

Where t2 is relationship table between t1 records. What is the best way to get desired output?
t1.id | t1_copy.id
1     | NULL -- want to get this NULL row
1     | 2
1     | 3

Simple JOIN would almost work, however it doesn't give me the first NULL row.
SELECT t1.id, t1_copy.id FROM t1
LEFT JOIN t2 ON t1.id = t2.id
LEFT JOIN t1 t1_copy ON t1_copy.id = t2.related_id
WHERE t1.id = 1

P.S: Yes, I do realize that desired output is wacky.

A: Seems like a simple UNION should do the trick
SELECT
   id,
   null as copy_id
FROM
   t1
WHERE
  exists (select * from t2 where t1.id = t2.id)
UNION ALL
SELECT
   t1.id,
   t2.related_id
FROM
   t1
   INNER JOIN t2
   ON t1.id = t2.id

SQL Fiddle

A: SELECT DISTINCT t1.id, t1_copy.id FROM t1
LEFT OUTER JOIN t2 ON t1.id = t2.id
WHERE t1.id = 1


text:
Q: What are the pre-requisites/standards of integrating a chatbot application inside an angularjs web application? I ran into things on searching the internet :
https://www.ibm.com/watson/services/conversation/
https://conversation-demo.mybluemix.net/ (Demo)
I was really interested in below one:
http://angularjs.chat/tutorials/angularjs-basic-chat-module/
but it needs
You need PubNub API Keys. This gives you the Doherty Threshold speed chat communication on a data stream network.

Can we build a chatbot application which i can configure and handle as API and responds to the configured messages?
Like,
(user) Hi
(bot)> Hello

(user)ID : 12345
(bot)> Name: Gopal Kumar
  ID : 12345
  Address: Bengaluru
  Link : https://stackoverflow.com/gok

Or it is we need to take this chats via key generation. Please suggest

A: You can check Recast.Ai they have some good examples how to build and host chatbots using their API also I think it's free to use without much rate limitations.


text:
Q: Identify source of picture (probably "Doom" related) I cleaned up my hard drive and found this picture.

The file is dated 1997, so the source must be older (obviously). It is probably related to the computer game Doom by id-Software. Somehow, that was the first thing that came to my mind after i saw the image for the first time after 16 years ;)
The monster looks similar to the Doom Cyberdemon, thats all i managed to figure out.

I don't have much hope that someone comes up with something, but i thought its at least worth a try. It may even be fan-made, but somehow the monster looks too "good" for that.
EDIT:
After looking at the picture again, I noticed something familiar about the background. Look at the picture below. Those are textures from the Doom game. Doesn't the third one look like the background? While this does not explain where the marine/monster comes from, it supports the fact that the picture really is Doom related and that it probably has been edited. Or maybe I am seeing things that aren't there ;)

A: From the Itrunsdoom forum, we've got a little extra detail. The pictures were originally taken (by Art Data) to demonstrate what the FMV cut-scenes for the 3DO version of the game would look like.
When the game was cancelled, the images were cannibalised for publicity shots but never formally released.
You can see some high quality shots here;

And this twitter confirms that although these were shot as stills, no video was actually made

A: When I was a kid I had a video game magazine with this picture in it. The magazine was advertising the 3DO if anyone even remembers that. It was a video game system that didn't make it. Well they used the picture to advertise Doom being on the platform. I'd say there's a chance it might have been made just for the ad, or perhaps was intended for a potential commercial for the 3DO.

A: I ran a Google image search on this picture, and ended up on the homepage of one Matthias "Matt" Weber, a German Doom fan, last updated so long ago that he feels the need to supply his CompuServe email address, and is proud of the specs of his gaming machine, a Pentium-133 with 16MB of RAM and a 14k4 modem (AWESOME!)
Our man Matt here has this image of yours on his page, and he hesitantly attributes it to the Doom movie:

That's it for computers and Doom and such. Now we come to other, less important things. For instance, cinema:
I expected more from Independence Day. But let's see what this next film has to offer.

Right. This is the famous boss from DooM, who just mauled a marine. Supposedly this picture comes from the "DooM film."  Anyway, after Street Fighter and Mortal Kombat, it's about time for it, so I hope the film to one of the "best games ever" will also come to cinemas.

This is strange, because the Doom movie only came out in 2005 (IMDB), quite a few years after our Matt's homepage 1996 timestamp.
So, my final conclusion is that this image comes from some low-budget horror movie, and only has a coincidental resemblences to Doom's Cyberdemons. This resemblence, however, was enough for some Doom fan to put it up on his page, and perhaps it rolled onwards from there to you.