text:
Q: Fix JSON that does not have quotes around element names I have this broken JSON string
    {
    sources: [{
        file: "/images/image1.png",
        label: "Cat"
    }, {
        file: "/images/image2.png",
        label: "Cat2"
    }, {
        file: "/images/image3.png",
        label: "Cat3"
    }],
    skin: "",
    size: "1330",
    width: 728,
    height: 410,
    preload: "auto",
    startparam: "start",
    other: [],
    config: {
        color: '#FFFFFF',
        fontSize: 15,
        fontFamily: "Verdana",
        backgroundOpacity: 0
    },
    "sharing": {
        code: "265235EF",
        link: "LINK HERE"
    }
}

But as you can see the element names dont have quotes around them, meaning that when I try get infomation from it, it wont work.
Is there a way for me to fix it to turn it into this (adding quotes)
{
   "sources": [
      {
         "file": "/images/image1.png",
         "label": "Cat"
      },
      {
         "file": "/images/image2.png",
         "label": "Cat2"
      },
      {
         "file": "/images/image3.png",
         "label": "Cat3"
      }
   ],
   "skin": "",
   "size": "1330",
   "width": 728,
   "height": 410,
   "preload": "auto",
   "startparam": "start",
   "other": [],
   "config": {
      "color": "#FFFFFF",
      "fontSize": 15,
      "fontFamily": "Verdana",
      "backgroundOpacity": 0
   },
   "sharing": {
      "code": "265235EF",
      "link": "LINK HERE"
   }
}

A: use JSON.stringify() for example:
var obj = {
    sources: [{
        file: "/images/image1.png",
        label: "Cat"
    }, {
        file: "/images/image2.png",
        label: "Cat2"
    }, {
        file: "/images/image3.png",
        label: "Cat3"
    }],
    skin: "",
    size: "1330",
    width: 728,
    height: 410,
    preload: "auto",
    startparam: "start",
    other: [],
    config: {
        color: '#FFFFFF',
        fontSize: 15,
        fontFamily: "Verdana",
        backgroundOpacity: 0
    },
        "sharing": {
        code: "265235EF",
        link: "LINK HERE"
    }
}

var json = JSON.stringify( obj );
console.log( json )

A: use JSON.stringify() like this:

var j =    {
    sources: [{
        file: "/images/image1.png",
        label: "Cat"
    }, {
        file: "/images/image2.png",
        label: "Cat2"
    }, {
        file: "/images/image3.png",
        label: "Cat3"
    }],
    skin: "",
    size: "1330",
    width: 728,
    height: 410,
    preload: "auto",
    startparam: "start",
    other: [],
    config: {
        color: '#FFFFFF',
        fontSize: 15,
        fontFamily: "Verdana",
        backgroundOpacity: 0
    },
    "sharing": {
        code: "265235EF",
        link: "LINK HERE"
    }
};

document.write(JSON.stringify(j));


text:
Q: helpers {{#if }} doesn't render with expressjs and express3-handlebars I have a problem with helpers {{#if}} in my nodejs app using expressjs and express3-handlebars:
app.js :
app.get('/view', function (req, res) {
    res.render('view', {
      valeur: true
    });
});

html :
{{#if valeur}}
   ok
{{else}}
   not ok
{{/if}}

'ok' isn't render while valeur is equal to true
('not ok' is always render)
thanks

A: Your code looks correct to me, based on reading the example usage documentation from here.
You code is very similar to the following snippet
app.get('/', function (req, res, next) {
    res.render('home', {
        showTitle: true,

        // Override `foo` helper only for this rendering.
        helpers: {
            foo: function () { return 'foo.'; }
        }
    });
});

And the template snippet

  {{#if showTitle}}

Home

  {{/if}}

I would recommend debugging your app by showing your variable in the rendered template. For instance:
'view` template:
The Valeur is {{valeur}}

{{#if valeur}}
   ok
{{else}}
   not ok
{{/if}}

In my personal experience, you will find that the value of the variable (in your case valeur) will not be as expected, and may be null or even false. I am expecting that you may have simplified your app and that there is a side-effect from some other piece of code that is changing that value.
Hope you have figured it out!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you add a counter to a list comprehension? I'm trying to re-write the following in a list comprehension, but I'm struggling to add the counter in:
create_list = []
    counter = 0
    for x in my_list:
        create_list.append(f(x+counter))
        counter += 1

I've tried:
create_list = [f(x+counter) for x in my_list] but obviously this doesn't increase the counter.

A: You could use enumerate():
new_list = [f(val+index) for (index, val) in enumerate(my_list)]

A: Okay, this is definitely not the best way to handle it (I hate having to import stuff!), but it's pretty cool and works:
counter = -1

def g(x): # function with side-effect! returns back the value.
    global counter
    counter = counter + 1
    return counter

create_list = [f(x)+g(x)) for x in my_list] #btw you might want to type cast? I don't really know your data sets nor functionality of f, so I'm not sure

There are a lot of other ways too such as making a second list based off the len(my_list) and then using zip to sort of "parallel" compute, or using two list comprehensions, etc.


text:
Q: sharing a link opened in safari in ios to my application? I need help about this problem.
I have a functionality in my application to share links with other users, what I need to do is:

*

*Open any link in safari browser

*Directly some action on safari browser to share that link in my application.

Is this possible in iOS to share a link from browser to the app directly.
Need help about this.
Regards.

A: Starting from iOS 8 Using Share App Extension can achieve this task
I managed to do it by creating a Share extension app (File->New->Target->Application Extension)

Then from Targets->Info I specified support for web URLs

Then i spent time searching for a way to use original app files in the app extension and this post helped me a lot Sharing code between original iOS App and App Extension
If you are using cocoapods this can help you too https://stackoverflow.com/a/31989172/3033056 but be aware that not all pods are allowed to be used in app extensions
This is a link for a tutorial http://www.appcoda.com/ios8-share-extension-swift/

A: This is indeed possible using URL Schemes
http://mobile.tutsplus.com/tutorials/iphone/ios-sdk-working-with-url-schemes/

*

*See sender example

*See receiver example

A: iOS custom url scheme:
Example for html:

Run the appiPhone/iPad

CFBundleURLSchemes - An array of strings containing the URL scheme names—for example, http, mailto, tel, and sms.
BundleURLName - A string containing the abstract name of the URL scheme. To ensure uniqueness, it is recommended that you specify a reverse-DNS style of identifier, for example, com.acme.myscheme.
The string you specify is also used as a key in your app's InfoPlist.strings file. The value of the key is the human-readable scheme name.
via Apple's documentation:
Implementing Custom URL Schemes
If your app can receive specially formatted URLs, you should register the corresponding URL schemes with the system. A customURL scheme is a mechanism through which third-party apps can communicate with each other. Apps often use custom URLschemes to vend services to other apps. For example, the Maps app supports URLs for displaying specific map locations.
Registering Custom URL Schemes
To register a URL type for your app, include the CFBundleURLTypes key in your app's Info.plist file. The CFBundleURLTypes key contains an array of dictionaries, each of which defines a URL scheme the app supports.
In your AppDelegate:
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {

    NSString *query = [url query];

//    NSLog(@"query->%@",query);//param=1
//    NSLog(@"host->%@",host);//BundleURLName
//    NSLog(@"resourceSpecifier->%@",resourceSpecifier);//BundleURLName?param=1

    if(![[url scheme] isEqualToString:@"BundleURLSchemes"])
        return NO;
    else{
        NSArray* paramsData =[query componentsSeparatedByString:@"="];

        NSLog(@"param->%@", paramsData[1]);
    }

     return YES;

}

A: You can easily pass data to your app from safari by query inside app URL.
i.e. Your application URL is scheme://host/path?Query where query is data that you can customize and parse. This URL is passed to application:handleOpenURL. See more about it here http://www.idev101.com/code/Objective-C/custom_url_schemes.html


text:
Q: Scheme-theoretic image and delta-invariants Let $(X,o)$ be an affine, isolated, normal, Gorenstein singularity. Let $f$ and $g$ be two morphisms from $\mbox{Spec}(\mathbb{C}[[t]])$ to $X$ (also known as formal arcs) such that the closed point maps to the singular point $o$ and the generic point maps to a smooth point of $X$. Denote by $C_f$ and $C_g$ the closure of the scheme-theoretic image of $f$ and $g$, respectively. Is the delta invariant of $C_f$ the same as that of $C_g$?

A: Without any stronger hypothesis connecting $f$ and $g$ you should not expect that to happen.
The simplest instance is when $(X,o)$ is alrealdy non singular, say dimension 2: $(\mathbb{C}^2,o)$. In this case the morphisms correspond to $\mathbb{C}$-algebra homomorphisms $\mathbb{C}\{x,y\}\rightarrow \mathbb{C}[[t]]$, and these can be interpreted as parametrizations of branches of plane curve singularities.
Take $f$ given by $x\mapsto t$, $y\mapsto t^k$ parametrizing a smooth branch ($\delta_f=0$) and $g$ given by $x\mapsto t^2$, $y\mapsto t^3$ a cusp ($\delta_g=1$).
So in general the answer is no,


text:
Q: PHP trimensional array I was wondering if someone could help me with this looping array in PHP as I am still learning the language.
I need to loop into the 3-dimensional (3D) array below in order to:

*

*Check the [room_type_id] values and if its true to a specific value, I would return [check_in_times] array value for this same parent array.

For example:
if [room_type_ids] = 261
  I would need to return [check_in_times] = 1

if [room_type_ids] = 36
  I would need to return [check_in_times] = 2

My array is:
$myarray = Array (
  [0] => Array (
    [check_in_times] => Array (
      [0] => 1
    )
    [room_type_ids] => Array (
      [0] => 261
      [1] => 281
      [2] => 283
      [3] => 292
      [4] => 296
      [5] => 365
      [6] => 381
      [7] => 387
      [8] => 389
      [9] => 730
    )
    [season_ids] => Array (
      [0] => 0
    )
  )
  [1] => Array (
    [check_in_times] => Array (
      [0] => 2
    )
    [room_type_ids] => Array (
      [0] => 36
      [1] => 38
      [2] => 300
      [3] => 318
      [4] => 336
      [5] => 889
      [6] => 897
      [7] => 728
      [8] => 745
      [9] => 747
    )
    [season_ids] => Array (
      [0] => 0
    )
  )
)

Thank you!

A: Something like:
$room = 261;
$checks = 0;

foreach ($myarray as $subset)
{
    if (in_array($room, $subset['room_type_ids']))
    {
        $checks = $subset['check_in_times'][0];
        break;
    }
}


text:
Q: Nuxt JS store loading lots of data I need to display a lot of items on a page, 1,000 + JSON objects, however, I don't need them all on the page initially, only say 50 or so and then display more as the user scrolls. The data is loaded and stored in the store, and fetched on the page. If I use slice this seems to solve the issue, but how could I get this to show more as I'm scrolling?
<template>

      {{ item }}

</template>

A: You can use a virtual scroller, like this one :
https://github.com/Akryum/vue-virtual-scroller
basically it will act like an infinite scroller and load only the number of element you want.


text:
Q: Eigenfunctions of the Dirichlet Laplacian in balls I am trying to find out about the Dirichlet eigenvalues and eigenfunctions of the Laplacian on $B(0, 1) \subset \mathbb{R}^n$.
As pointed out in this MSE post, one needs to use polar coordinates, whence the basis eigenfunctions are given as a product of solutions of Bessel functions and spherical harmonics. @Neal further points out that such considerations hold even for balls on spaces of constant curvature (see Chavel, Eigenvalues in Riemannian Geometry, Chapter 2, Section 5).
I have one question in this matter: none of the sources say what the values of the basis eigenfunctions are at the center of the ball. Clearly, the eigenfunctions should be smooth, but then it seems that they should be zero at the center of the ball. Is that correct?

A: Radial eigenfunctions are not zero at the centre of the ball, while nonradial eigenfunctions are zero there.
Indeed, recall that the radial part of any basis eigenfunction is
$$
r^\frac{2-n}{2} J_{l-\frac{2-n}{2}}(\sqrt{\lambda} r),
$$
where $\lambda$ is a corresponding eignevalue.
The parameter $l \in \{0,1,\dots\}$ corresponds to spherical harmonics, i.e., $l$ is a degree of a homogeneous harmonic polynomial.
So, if $l=0$, then the eigefunction is radial, while if $l \geq 1$, then the eigenfunction is nonradial.
It is known that $J_{\nu}(x) = c x^\nu + o(x^\nu)$, where $c>0$, see, e.g., here.
Therefore, we see that if $l=0$, then
$$
r^\frac{2-n}{2} J_{-\frac{2-n}{2}}(\sqrt{\lambda} r) = c > 0 \quad \text{at } r=0,
$$
while if $l \geq 1$, then
$$
r^\frac{2-n}{2} J_{l-\frac{2-n}{2}}(\sqrt{\lambda} r) = r^\frac{2-n}{2}\left(c r^{l-\frac{2-n}{2}} + o(r^{l-\frac{2-n}{2}}) \right)  = c r^l +o(r^l) =  0 \quad \text{at } r=0.
$$


text:
Q: Docker: setctty operation not permitted Failed to find any information about the "setctty" operation.
Sometimes when starting a new container I get this error:
Error response from daemon:
    Cannot start container dc3e40bc49b6305edca42537d3d7af8b20e6e119d1ea74b473bb5c069f461641:
    setctty operation not permitted

Here is the docker info:
# docker --debug info
Containers: 2
Images: 501
Storage Driver: devicemapper
 Pool Name: docker-8:3-10224046-pool
 Pool Blocksize: 65.54 kB
 Data file: /var/lib/docker/devicemapper/devicemapper/data
 Metadata file: /var/lib/docker/devicemapper/devicemapper/metadata
 Data Space Used: 73.16 GB
 Data Space Total: 429.5 GB
 Metadata Space Used: 66.57 MB
 Metadata Space Total: 10.74 GB
 Library Version: 1.02.89-RHEL6 (2014-09-01)
Execution Driver: native-0.2
Kernel Version: 2.6.32-431.29.2.el6.x86_64
Operating System: <unknown>
Debug mode (server): false
Debug mode (client): true
Fds: 19
Goroutines: 17
EventsListeners: 0

How to fix this issue or where can I find the info about the "setctty"?


text:
Q: Are congruence subgroups of the modular group finitely presented? Are the congruence subgroups of the modular group $\Gamma\equiv\mathrm{PSL}\left(2,\mathbb{Z}\right)$ (e.g. $\Gamma\left(n\right)$, $\Gamma_{0}\left(n\right)$, $\Gamma_{1}\left(n\right)$ etc.) finitely presented? If so, is there a proof of this? Assuming they are finitely presented, are the presentations of e.g. the principal congruence subgroups $\Gamma\left(n\right)$ (for small $n$) documented anywhere? I know they could be computed using the Reidemeister-Schreier process, but it would be nice to have some independent confirmation of the presentations.
Many thanks!

A: A subgroup of finite index in a finitely presented group is finitely presented (see Exercise 6.1.6 in Robinson: A course in the theory of groups), so all congruence subgroups of the modular group are finitely presented. I cannot answer your second question.

A: Well, the congruence subgroups are finite index, the group $PSL(2,\mathbb{Z})$ is finitely presented, so they are too. The magic words are: "Reidemeister-Schreier" and Magnus-Karras-Solitar.

A: Not only these subgroups are finitely presented, they are all finite free products of cyclic groups; most of them (for sufficiently large $n$) are actually free of finite rank (once congruence subgroup contains no elements of order 2 and 3). For instance, you can easily check that $\Gamma(n)$ is torsion-free for all $n\ge 2$ by looking at traces for $n\ge 3$ (since $1\ne 2$ mod $n\ge 2$ and $2\ne 0$ mod $n\ge 3$) and by looking at matrix coefficients for $n=2$. Rank is easily computable if you know index of the congruence subgroup in the modular group. The magic formula is multiplicativity of the Euler characteristic: For the modular group $\Gamma$, $\chi=-1+\frac{1}{2} + \frac{1}{3}=-\frac{1}{6}$. If $\Gamma'\subset \Gamma$ is a subgroup of index $i$ then $\chi(\Gamma')=i \chi(\Gamma)$. If $\Gamma$ is free of rank $r$ then $\chi(\Gamma)= 1-r$. For instance, to find index $i$ for $\Gamma(n)$, compute the order of the quotient group $SL(2, Z_n)/\pm I$. There is a closed formula for the order of this group (in terms of prime factors of $n$) which will tell you what the index is:
If $n$ is the product of powers of primes
$\prod_i p_i^{k_i}$ then
$$
|PSL(2,Z_n)|= \frac{n^3}{2} ~~~\prod_i (1- p_i^{-2}).
$$


text:
Q: fatal error: sys/cdefs.h: No such file or directory| It has been weeks that I am trying to use Code::Blocks IDE on Ubuntu 14.04 LTS to program Atmega16, however I am hindered by the following error while compiling/building the program in C::B
/usr/include/features.h|374|fatal error: sys/cdefs.h: No such file or directory|

I have read this thread
and based on that I have tried to purge libc6-dev and ran into trouble by removing the dependencies. From previous experience I knew that there is a huge probability to get into broken pipe error. I tackled it by installing the lost dependencies.
Now still I have the same error.

A: On my machine, where I've probably screwed around too much with 32 and 64 bit architecture files, I resolved this issue by installing g++-multilib.

A: Typing the command:
sudo apt-get --reinstall install libc6 libc6-dev

solved the problem.

A: I know this is an Ubuntu-centric branch of  but this page is the first one that came up when I searched this error on Google (even when I put -Ubuntu in the search), so I'm going to share my answer for Arch linux here:
In Arch, I got a /lib/cpp fail sanity check because the package glibc was corrupt and missing all the /usr/include/sys headers. I resolved this error by recompling glibc.

A: Looks like sys/cdefs.h is defined under /usr/include/x86_64-linux-gnu/sys, but /usr/include/x86_64-linux-gnu is NOT a default INCLUDE_PATH.

A: If you are on an amd64 installation, you can try to install the package libc6-dev-i386. This helped me solve the same issue you encountered while trying to compile smm from i8kutils.

A: apt install gcc-multilib will also install the library you need libc6-dev-i386 along with packages you might need in future.

A: I got this while trying to compile openssl-1.0.2a while chrooted to a wheezy 32-bit partition while running a 64-bit kernel. the "./config" script was too smart, and decided to configure for amd64. I solved it by MACHINE=i386 ./config --prefix=$HOME, and then make worked without error.

A: I got this by accidently adding the -m32 option (gcc told me to add for -maes but it was wrong).


text:
Q: How to implement a current controlled voltage source, or a comparator that trips once a certain current is reached? I have current flowing through a CCVS, once 10A is reached, the CCVS puts out 10V, which takes a comparator's output high. The current that goes through the CCVS continuous to the load. Is there a way to implement this without an ideal CCVS?

A: Measure the voltage drop across a small (very small) resistor in series with the load using an instrumentation amplifier, and feed the output of the inamp into your comparator.

simulate this circuit – Schematic created using CircuitLab


text:
Q: where can I have the specific OBD DTC fault code description e.g P1xxx means XXXXXX I am working on OBD project now, I wanna have list of data for DTC fault code. we can easily find the general fault code info e.g P0xxx and P2XXX. We can pay for the license. anyone know where I can buy the database?

A: You can find a good list of them here: https://www.outilsobdfacile.com/data-trouble-code-obd2.php
If you are working on a specific car manufacturer you can usually find all the manufacturer level error messages hidden somewhere in a file of their diagnostic software.

A: As long as you don't expect to find definitions for vendor-specific fault codes (which only the respective vendors own), the first place should be the SAE International, which is the actual organization committee that has defined those codes.
E.g., you might want to buy SAE J2012 or J2012DA, respectively.


text:
Q: Import arbitrary python source file. (Python 3.3+) How can I import an arbitrary python source file (whose filename could contain any characters, and does not always ends with .py) in Python 3.3+?
I used imp.load_module as follows:
>>> import imp
>>> path = '/tmp/a-b.txt'
>>> with open(path, 'U') as f:
...     mod = imp.load_module('a_b', f, path, ('.py', 'U', imp.PY_SOURCE))
...
>>> mod
<module 'a_b' from '/tmp/a-b.txt'>

It still works in Python 3.3, but according to imp.load_module documentation, it is deprecated:

Deprecated since version 3.3: Unneeded as loaders should be used to
  load modules and find_module() is deprecated.

and imp module documentation recommends to use importlib:

Note New programs should use importlib rather than this module.

What is the proper way to load an arbitrary python source file in Python 3.3+ without using the deprecated imp.load_module function?

A: importlib helper function
Here is a convenient, ready-to-use helper to replace imp, with an example. The technique is the same as that of https://stackoverflow.com/a/19011259/895245 , this is just providing a more convenient function.
main.py
#!/usr/bin/env python3

import os
import importlib

def import_path(path):
    module_name = os.path.basename(path).replace('-', '_')
    spec = importlib.util.spec_from_loader(
        module_name,
        importlib.machinery.SourceFileLoader(module_name, path)
    )
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    sys.modules[module_name] = module
    return module

notmain = import_path('not-main')
print(notmain)
print(notmain.x)

not-main
x = 1

Run:
python3 main.py

Output:
<module 'not_main' from 'not-main'>
1

I replace - with _ because my importable Python executables without extension have hyphens as in my-cmd. This is not mandatory, but produces better module names like my_cmd.
This pattern is also mentioned in the docs at: https://docs.python.org/3.7/library/importlib.html#importing-a-source-file-directly
I ended up moving to it because after updating to Python 3.7, import imp prints:
DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses

and I don't know how to turn that off, this was asked at:

*

*The imp module is deprecated

*How to ignore deprecation warnings in Python
Tested in Python 3.7.3.

A: Updated for Python >= 3.8:
Short version:
>>> # https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
>>> import importlib.util, sys
>>> spec = importlib.util.spec_from_file_location(modname, fname)
>>> module = importlib.util.module_from_spec(spec)
>>> sys.modules[modname] = module
>>> spec.loader.exec_module(module)

Full version:
>>> import importlib.util
>>> import sys
>>> from pathlib import Path
>>> from typing import TYPE_CHECKING
>>>
>>>
>>> if TYPE_CHECKING:
...     import types
...
...
>>> def import_source_file(fname: str | Path, modname: str) -> "types.ModuleType":
...     """
...     Import a Python source file and return the loaded module.

...     Args:
...         fname: The full path to the source file.  It may container characters like `.`
...             or `-`.
...         modname: The name for the loaded module.  It may contain `.` and even characters
...             that would normally not be allowed (e.g., `-`).
...     Return:
...         The imported module

...     Raises:
...         ImportError: If the file cannot be imported (e.g, if it's not a `.py` file or if
...             it does not exist).
...         Exception: Any exception that is raised while executing the module (e.g.,
...             :exc:`SyntaxError).  These are errors made by the author of the module!
...     """
...     # https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
...     spec = importlib.util.spec_from_file_location(modname, fname)
...     if spec is None:
...         raise ImportError(f"Could not load spec for module '{modname}' at: {fname}")
...     module = importlib.util.module_from_spec(spec)
...     sys.modules[modname] = module
...     try:
...         spec.loader.exec_module(module)
...     except FileNotFoundError as e:
...         raise ImportError(f"{e.strerror}: {fname}") from e
...     return module
...
>>> import_source_file(Path("/tmp/my_mod.py"), "my_mod")
<module 'my_mod' from '/tmp/my_mod.py'>

Original answer for Python 3.5 and 3.6
Shorter version of @falsetru 's solution:
>>> import importlib.util
>>> spec = importlib.util.spec_from_file_location('a_b', '/tmp/a-b.py')
>>> mod = importlib.util.module_from_spec(spec)
>>> spec.loader.exec_module(mod)
>>> mod
<module 'a_b' from '/tmp/a-b.txt'>

I tested it with Python 3.5 and 3.6.
According to the comments, it does not work with arbitrary file extensions.

A: Similar to @falsetru but for Python 3.5+ and accounting for what the importlib doc states on using importlib.util.module_from_spec over types.ModuleType:

This function [importlib.util.module_from_spec] is preferred over using types.ModuleType to create a new
  module as spec is used to set as many import-controlled attributes on
  the module as possible.

We are able to import any file with importlib alone by modifying the importlib.machinery.SOURCE_SUFFIXES list.
import importlib

importlib.machinery.SOURCE_SUFFIXES.append('') # empty string to allow any file
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# if desired: importlib.machinery.SOURCE_SUFFIXES.pop()

A: Found a solution from importlib test code.
Using importlib.machinery.SourceFileLoader:
>>> import importlib.machinery
>>> loader = importlib.machinery.SourceFileLoader('a_b', '/tmp/a-b.txt')
>>> mod = loader.load_module()
>>> mod
<module 'a_b' from '/tmp/a-b.txt'>

NOTE: only works in Python 3.3+.
UPDATE Loader.load_module is deprecated since Python 3.4. Use Loader.exec_module instead:
>>> import types
>>> import importlib.machinery
>>> loader = importlib.machinery.SourceFileLoader('a_b', '/tmp/a-b.txt')
>>> mod = types.ModuleType(loader.name)
>>> loader.exec_module(mod)
>>> mod
<module 'a_b'>

>>> import importlib.machinery
>>> import importlib.util
>>> loader = importlib.machinery.SourceFileLoader('a_b', '/tmp/a-b.txt')
>>> spec = importlib.util.spec_from_loader(loader.name, loader)
>>> mod = importlib.util.module_from_spec(spec)
>>> loader.exec_module(mod)
>>> mod
<module 'a_b' from '/tmp/a-b.txt'>

A: after many failure solutions this one works for me
def _import(func,*args):
    import os
    from importlib import util
    module_name = "my_module"
    BASE_DIR = "wanted module directory path"
    path =  os.path.join(BASE_DIR,module_name)
    spec = util.spec_from_file_location(func, path)
    mod = util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return getattr(mod,func)(*args)

and to call it just write the function name and it's parameters _import("function",*args)


text:
Q: How to create a common after_create callback for all models? Consider I have the models User, Account and Products. I want a common after_create callback for all these models say log_creation.
How do I do that?

A: You can have a GenericModule and include this in any model you wish
module GenericModule
  extend ActiveSupport::Concern

  included do
    after_create :log_creation
  end

  def log_creation
    # perform logging
  end
end

And in the model
class User < ActiveRecord::Base
  include GenericModule

  # ...other model code...
end

You can have this for all your models in which you need this behavior.

A: From the Ruby on Rails Guides on ActiveRecord Callbacks:
Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them.
Here's an example where we create a class with an after_destroy callback for a PictureFile model:
class PictureFileCallbacks
  def after_destroy(picture_file)
    if File.exists?(picture_file.filepath)
      File.delete(picture_file.filepath)
    end
  end
end

When declared inside a class, as above, the callback methods will receive the model object as a parameter. We can now use the callback class in the model:
class PictureFile < ActiveRecord::Base
  after_destroy PictureFileCallbacks.new
end


text:
Q: Why does my password keep getting reset? This is the second time this message has been displayed. I have changed my password and then 24 hours later, Mojang resets my password again. Here is the text:

Due to recent suspicious activity in your account we suspect that your Mojang account email and password may have been compromised. To prevent unauthorized use of your account we've reset your account password. If you use that same password on other sites we strongly recommend that you change your password on those sites as well.

A: Messages like that are usually relating  to other people trying to or actually accessing your account. I would change your password to a much stronger password, and if you are sharing your account with someone else, don't since that is a serious security issue and may be what is causing your problem.

A: You need to change the password of your connected e-mail account as well. Anyone with access to that account can regain access to your Mojang account. Also you should no longer give access to your Mojang account, if you did so in the past.
Of course you should change all passwords of the accounts connected to that e-mail account and all passwords that were equal to your stolen one.


text:
Q: docker-compose redis password via environment variable I'm trying to pass my redis password using docker-compose via environment variable but it gives me errors.
Here is part of mine docker-compose.yml with redis image:
  redis:
    image: redis
    container_name: redis
    # command: redis-server --requirepass mypassword <--- this works as expected
    # command: redis-server --requirepass ${REDIS_PASSWORD} <-- while this does not
    command: redis-server --requirepass $${REDIS_PASSWORD} <-- and this does not work either
    volumes:
      - redis:/var/lib/redis/data
      - ./redis.conf:/usr/local/etc/redis/redis.conf
    ports:
      - "6379"
    env_file:
      - .env.prod

My .env.prod:
REDIS_PASSWORD=mypassword

It gives me an error:
consumer: Cannot connect to redis://:**@redis:6379/0: WRONGPASS invalid username-password pair or user is disabled..

But if I specify password directly in docker-compose.yml without env variable, then it works.

A: env_file allows to set environment variables in the container - while you need them in the environment of docker-compose in order to perform variable substitution for ${REDIS_PASSWORD}.
To achieve your goal remove the env_file from your yml and, either:

*

*rename your .env.prod file to just .env, so that docker-compose would automatically pick it; or,

*specify it while calling docker-compose, by way of the --env-file parameter:

docker-compose --env-file .env.prod up

A: This works for me.
Similar like Cezary Drożak answer, but less code.
docker-compose.yml
  redis:
    image: redis:alpine
    restart: always
    command: /bin/sh -c "redis-server --requirepass $$REDIS_HOST_PASSWORD"
    env_file:
      - redis.env

redis.env
REDIS_HOST_PASSWORD=mypassword

Source

A: This should work:
    redis:
        image: redis
        command: >
          --requirepass ${REDIS_PASSWORD}

A: None of the answers worked for me. Here is what I ended up doing, adjusted to
the code snippet provided by OP:
redis:
  image: redis
  container_name: redis
  command:
    - /bin/sh
    - -c
    # - Double dollars, so that the variable is not expanded by Docker Compose
    # - Surround by quotes, so that the shell does not split the password
    # - The ${variable:?message} syntax causes shell to exit with a non-zero
    #   code and print a message, when the variable is not set or empty
    - redis-server --requirepass "$${REDIS_PASSWORD:?REDIS_PASSWORD variable is not set}"
  volumes:
    - redis:/var/lib/redis/data
    - ./redis.conf:/usr/local/etc/redis/redis.conf
  ports:
    - "6379"
  env_file:
    - .env.prod

I changed the command field, so that the command is run through the shell —
this way, /bin/sh can expand the REDIS_PASSWORD variable or exit with an
error message, if the variable could not be find.
As for why the code snippet in question does not work:

*

*command: redis-server --requirepass ${REDIS_PASSWORD}
In this case, the ${REDIS_PASSWORD} would be expanded by Docker Compose.
Docker Compose first tries to find an environment variable called
REDIS_PASSWORD. Then, Docker Compose looks for file .env (yes, even if
the env_file field was provided). Because the variable is defined in file
.env.prod, Compose cannot find it.

*command: redis-server --requirepass $${REDIS_PASSWORD}
Here, ${REDIS_PASSWORD} is passed unexpanded to the redis-server command.
This is because Docker runs the redis-server command directly, not
through the shell. When one enters that command in a terminal emulator, the
shell, usually Bash, expands the variable before running the command.
Sources

*

*Shell Parameter Expansion — the ${variable:?message} syntax

*Environment variables in Compose — how Compose expands variables

A: *

*redis-stack

version: '3.8'

services:

  redis:
    container_name: redis-stack
    image: 'redis/redis-stack:latest'
    restart: unless-stopped
    #command: ["redis-server", "/etc/redis/redis.conf"]
    environment:
      REDIS_ARGS: "--requirepass root"
    volumes:
      - ./redis-data:/data
      #- ./conf/users.acl:/etc/redis/users.acl:z
      #- ./conf/redis.conf:/etc/redis/redis.conf:z
    ports:
      - "6379:6379"#redis-server
      - "8001:8001" #RedisInsight

A: You need to set the Env vars and pass them like this:

  cache:
    image: redis:6.2-alpine
    restart: always
    environment:
      REDIS_PWD: '${REDIS_PWD}'
    ports:
      - '6379:6379'
    command: redis-server --save 20 1 --loglevel warning --requirepass $REDIS_PWD
    volumes:
      - cache:/data

Than set it in your .env file:
REDIS_PWD=ChangeMeLater!


text:
Q: Javascript interpreters in multiple threads Situation: i have C# code and Nil.JS javascript interpreter inside it. Instances of js engine may be working in different threads. I need to create a variable in one thread and read it from another.
I know something like this works for Lua (you can delete information about table's parent for example, and it will be visible in another thread), but i don't have any idea how to make for javascript. Are there any ways of doing it?


text:
Q: Metaspace Memory Leak We recently migrated our application from Java 7 to Java 8. from the day of cut over, we started seeing Out of Memory Metaspace issues. We tried increasing the metaspace space size, but it didn't help. Jvisual VM(and Jconsole) shows that 60 -70 K class files are getting loaded into memory every day and nothing getting unloaded. we tried using all kinds of GC algorithms and nothing helped. What else can possibly go wrong in never Java version ?

A: After some research, we found the solution to our problem. Adding below JVM argument fixed the issue.
-Dcom.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize=true

Below are article has good info on the issue.
https://issues.apache.org/jira/browse/CXF-2939
Hope this helps.


text:
Q: (Unity3D) Saving/Loading Player Inventory Whenever saving or loading via the Player script, the inventory always comes up blank on both sides, and I can't figure out where the problem is. The inventory uses the same system that is used in the Intermediate Inventory Tutorial by Unity, which works fine, but the inventory is always blank when loading.
Player
public void Save(){
    Debug.Log ("Saving data (player / inventory)");

    SaveLoadManager.SavePlayer (this); //works fine
    SaveLoadInventory.SaveInventory (inv); //where the issue is
}
public void Load(){
    Debug.Log ("Loading data (player / inventory)");

    float[] loadedStats = SaveLoadManager.LoadPlayer (); //works fine
    Item[] loadedItems = SaveLoadInventory.LoadInventory (); //comes up empty

    inv.items = loadedItems; //try to set the referenced Inventory script array of items equal to the loaded items

    //loadedStats[...] are set to player values and all works good
}

Inventory
public class Inventory : MonoBehaviour {

public Image[] itemImages = new Image[numItemSlots];
public Text[] itemAmountsText = new Text[numItemSlots];
public int[] itemAmounts = new int[numItemSlots];
public Item[] items = new Item[numItemSlots];

public const int numItemSlots = 40;

public void AddItem(Item itemToAdd){
    for (int i = 0; i < items.Length; i++) {
        if(items [i] == itemToAdd){
            if (itemAmounts [i] <= 99) {
                itemAmounts [i]++;
            } else {
                items [i] = itemToAdd;
                itemImages [i].sprite = itemToAdd.itemImage;
                itemImages [i].enabled = true;
            }
            itemAmountsText [i].text = itemAmounts [i] + "";
            return;
        } else if (items [i] == null) {
            itemAmounts [i]++;
            itemAmountsText [i].text = itemAmounts [i] + "";
            items [i] = itemToAdd;
            itemImages [i].sprite = itemToAdd.itemImage;
            itemImages [i].enabled = true;
            return;
        }
    }
}

public void RemoveItem(Item itemToRemove){
    for (int i = 0; i < items.Length; i++) {
        if (items [i] == itemToRemove) {
            items [i] = null;
            itemImages [i].sprite = null;
            itemImages [i].enabled = false;
            return;
        }
    }
}

public void ClearAllItems(){
    for (int i = 0; i < items.Length; i++) {
        items [i] = null;
        itemImages [i].sprite = null;
        itemImages [i].enabled = false;
        return;
    }
}

[Serializable]
public class InventoryData {
    public Image[] itemImages = new Image[numItemSlots];
    public Text[] itemAmountsText = new Text[numItemSlots];
    public int[] itemAmounts = new int[numItemSlots];
    public Item[] items;

    public InventoryData(Inventory inv){
        items = new Item[numItemSlots];

        for (int i = 0; i < items.Length; i++) {
            inv.items[i] = items[i];
            inv.itemAmounts[i] = itemAmounts[i];
            inv.itemAmountsText[i] = itemAmountsText[i];
            inv.itemImages[i] = itemImages[i];
            }
        }
    }
}

SaveLoadInventory
public static class SaveLoadInventory {

    public static void SaveInventory(Inventory inv){

    BinaryFormatter bf = new BinaryFormatter();
    var createdir = Directory.CreateDirectory(Application.persistentDataPath + "/saves");
    String dir = Application.persistentDataPath + "/saves";
    Inventory.InventoryData data = new Inventory.InventoryData (inv);

    DirectoryInfo dir_i = new DirectoryInfo(dir);
    FileInfo[] info = dir_i.GetFiles("*.inv");
    foreach (FileInfo f in info) {
        Debug.Log (f);
    }

    FileStream stream = new FileStream (dir + "/player" + (info.Length + 1) + ".inv", FileMode.Create);

    bf.Serialize (stream, data);
    stream.Close ();

}

    public static Item[] LoadInventory(){
    String dir = Application.persistentDataPath + "/saves";

    DirectoryInfo dir_i = new DirectoryInfo(dir);
    FileInfo[] info = dir_i.GetFiles("*.inv");
    foreach (FileInfo f in info) {
        Debug.Log (f);
    }

    if (info.Length >= 1) {

        BinaryFormatter bf = new BinaryFormatter ();
        var createdir = Directory.CreateDirectory(Application.persistentDataPath + "/saves");
        FileStream stream = new FileStream (dir + "/player" + (info.Length) + ".inv", FileMode.Open);
        Inventory.InventoryData data = bf.Deserialize (stream) as Inventory.InventoryData;

        stream.Close ();
        return data.items;
    } else {
        return null;
    }
}

I honestly would try some combination of Debugging for this and figure it out myself but it all seems too complicated to wrap my head around and have been worried it wouldn't ever work. If you have any help or suggestions that would be greatly appreciated.

A:
but the inventory is always blank when loading.

The first problem is the type of variables you want to serialize in your InventoryData class. You can't seriaize the Image and Text components directly because they are UnityEngine.Object type. For the Image component, save the path of the Sprite the Image  component is using. For the Text component, save the value of the .text property that holds the text itself.
If you want to serialize more than one property for the Image or Text component, it is better to create a new serialize-able class/wrapper that will hold important data you want to serialize for the Image component and another one for the Text component.
For example, let's say you want to serialize information about a Text component such as the font size, actual text and the color, here is an example  simple wrapper:
[Serializable]
public class TextWrapper
{
    public int fontSize;
    public string text;
    public Color color;

    public TextWrapper(Text text)
    {

        //Get Text Info
        fontSize = text.fontSize;
        this.text = text.text;
        color = text.color;
    }
}

The Text component to serialize:
public Text myText;

You can create new instance of TextWrapper from the Text component to serialize:
TextWrapper textWrapper = new TextWrapper(myText);

Now, you can serialize it with the BinaryFormatter in your question. You can put the TextWrapper variable in your InventoryData  class and that should serialize too.
Note that TextWrapper must be put in its own .cs file otherwise BinaryFormatter may file to serialize/deserialize it. If you still have problems using ..just use Json. See this post of more information.


text:
Q: cannot set iframe url programmatically I have a setIframe function to set the iframe url dynamically, but when reading back the url with getIframe url is blank why ?
index.html:
    <iframe id="MyIframe" src="frame.html">
    </iframe>

    <script>
    function setIframe(iframeId, url){
        document.getElementById(iframeId).src = url;
      }

      function getIframe(iframeId){
        return document.getElementById(iframeId).src;
      }

      var url = "frame.html" + location.search;
      alert(url);
      setIframe('myIframe',url);
      alert(getIframe("myIframe"));
    </script>

frame.html

          alert(location.search);

A: attr is not a vanilla JS function (although it is a function in jQuery.)
You'll need to use the vanilla equivalents: getAttribute and setAttribute.
function setIframe(iframeId, url){
  document.getElementById(iframeId).setAttribute('src', url);
}

function getIframe(iframeId){
  return document.getElementById(iframeId).getAttribute('src');
}

A: You're using myIframe in JavaScript but your iframe id is actually MyIframe, so I'm not sure how you set it up but maybe you're confused with the defined src from the element. And use .src instead of .attr()

function setIframe(iframeId, url){
    document.getElementById(iframeId).src = url;
  }

  function getIframe(iframeId){
    return document.getElementById(iframeId).src;
  }

  var url = "http://gizmodo.com/";
  setIframe('MyIframe',url);
  alert(getIframe("MyIframe"));
<iframe id="MyIframe" src="http://gizmodo.com/">
</iframe>


text:
Q: How much async/await is OK? In our project we are using async/await for almost 3 purposes (for all of their methods):

*

*Data access layer: where fetching/updating databases (using Dapper).

*Cache (Redis): read/write.

*ASP.Net MVC 5 controllers.

The question is how much async/await is ok. Is it ok to use them even when reading or writing small amount of data? How about cache and controllers?
Remarks: the project is a little special and it may have about 50,000 requests per second for few hours of a day.

A: According to an article I've read:

Async/await is great for avoiding blocking while potentially
  time-consuming work is performed in a .NET application, but there are
  overheads associated with running an async method
The cost of this is comparatively negligible when the asynchronous
  work takes a long time, but it's worth keeping in mind.

Based on what you asked, even when reading or writing small amount of data?. It doesnt seem to be a good idea as there are over.
Here is the article: The overhead of async/await in NET 4.5
And in the article he used a profiler to check the optimization of async/await.
QUOTE:

Despite this async method being relatively simple, ANTS Performance
  Profiler shows that it's caused over 900 framework methods to be run
  in order to initialize it and the work it does the first time that
  it's run.

The question here maybe if you're gonna accept these minimal overheads, and take into consideration that these overheads do pile up into something possibly problematic.

A:
The question is how much async/await is ok. Is it ok to use them even
  when reading or writing small amount of data? How about cache and
  controllers?

You should use async/await for I/O bound operations, it doesn't matter if it's a small amount of data. More important is to avoid potentially long running I/O bound operations mainly disk and network calls. Asp.net has limited size of thread pool and these operations may block it. Using asynchronous calls helps your application to scale better and allows to handle more concurrent requests.
For more info: http://msdn.microsoft.com/en-us/magazine/dn802603.aspx


text:
Q: LRU cache implementation in Javascript Java has LinkedHashMap which gets you 99% there to an LRU cache.
Is there a Javascript implementation of an LRU cache, preferably from a reputable source, that is:

*

*understandable

*efficient (amortized O(1) get/put/delete)

? I've been searching on the web but couldn't find one; I thought I found one on Ajax Design Patterns but it glosses over the sendToTail() method and has O(n) performance (presumably, since the queue and associative array are split up).
I suppose I could write my own, but I've learned the hard way that reinventing the wheel for core algorithms can be hazardous to one's health :/

A: This:
https://github.com/monsur/jscache
seems to fit you case although setItem (i.e. put) is O(N) in the worst case, that happens if the cache is filled up on insertion. In this case the cache is searched to purge expired items or least recently used items. getItem is O(1) and the expiry is handled on the getItem operation (i.e. if the item being fetched is expired, removes it and returns null).
The code is compact enough to be easily understood.
P.S. It might be useful to add to the constructor the option to specify the fillFactor, which is fixed to 0.75 (meaning that when the cache is purged it's size is reduced at least to 3/4th of the maximum size)

A: This is worth a mention:
https://github.com/rsms/js-lru
The core set of functions are O(1) and the code is heavily commented (with ASCII art too!)

A: Map should be O(1) in most implementations average case. Since Map keeps insertion order, adding a bit of code around it will get you a LRU and for most uses this should be plenty fast.
I needed a simple LRU cache for a small number of expensive operations (1 second). I felt better about copy-pasting some small code rather than introducing something external, but since I didn't find it I wrote it:
class LRU {
    constructor(max = 10) {
        this.max = max;
        this.cache = new Map();
    }

    get(key) {
        let item = this.cache.get(key);
        if (item) {
            // refresh key
            this.cache.delete(key);
            this.cache.set(key, item);
        }
        return item;
    }

    set(key, val) {
        // refresh key
        if (this.cache.has(key)) this.cache.delete(key);
        // evict oldest
        else if (this.cache.size == this.max) this.cache.delete(this.first());
        this.cache.set(key, val);
    }

    first() {
        return this.cache.keys().next().value;
    }
}

Usage:
> let cache = new LRU(3)
> [1, 2, 3, 4, 5].forEach(v => cache.set(v, 'v:'+v))
> cache.get(2)
undefined
> cache.get(3)
"v:3"
> cache.set(6, 6)
> cache.get(4)
undefined
> cache.get(3)
"v:3"

A: The monsur.com implementation is O(n) on insertion only because it has items which actually expire on real world time. It is not a simple LRU. If you only care about maintaining the most recently used items without regard to real world time, this can be done in O(1). A queue, implemented as a doubly linked list, is O(1) for insertion or deletion from the end, and this is all you should need for a cache. As for lookup, a hash map, which javascript makes pathetically easy, should be good for nearly O(1) lookup (assuming the javascript engine uses a good hashmap, that's implementation dependent of course). So you have a linked list of items with a hash map pointing to the items. Manipulate the ends of the linked list as needed to put new items and requested items on one end and remove old items from the other end.

A: This library runtime-memcache implements lru and a few other caching schemes in javascript.
It uses modified Doubly Linked List to achieve O(1) for get, set and remove. You can check out the implementation which is pretty simple.

A: It's not an LRU cache, but I've got my own linked map implementation. As it uses a JS objects as store, it'll have similar performance characteristics (the wrapper objects and hash function impart a performance penalty).
Currently, documentation is basically non-existant, but there's a related SO answer.
The each() method will pass the current key, the current value and a boolean indicating if there are more elements as arguments to the callback function.
Alternatively, looping can be done manually via
for(var i = map.size; i--; map.next()) {
    var currentKey = map.key();
    var currentValue = map.value();
}

A: I am aware that this is an old question but adding a link for future refrence.
Check out https://github.com/monmohan/dsjslib . This has a LRU Cache implementation in addition to some other data structures. Such caches (and this one too) maintain doubly linked list of cache entries in LRU order i.e. entries move to the head as they are accessed and are removed from tail when they are reclaimed (say by expiry or because size limit was reached). Its O(1) since it only involves constant number of pointer manipulations.

A: I improve @odinho's answer to fit this leetcode question
change if (item) to if (item != undefined) to fit value === 0 case
following is my code:
class LRUCache {
  constructor(max = 10) {
    this.max = max
    this.cache = new Map()
  }

  get(key) {
    let item = this.cache.get(key)
    if (item !== undefined) {
      // refresh key
      this.cache.delete(key)
      this.cache.set(key, item)
    }
    return item === undefined ? -1 : item
  }

  put(key, val) {
    // refresh key
    if (this.cache.has(key)) this.cache.delete(key)
    // evict oldest
    else if (this.cache.size == this.max) this.cache.delete(this.first())
    this.cache.set(key, val)
  }

  first() {
    return this.cache.keys().next().value
  }
}

A: External package/library is not required, we can write our own code to implement LRU in javascript, Please refer https://dev.to/udayvunnam/implementing-lru-cache-in-javascript-3c8g site for details.

A: Since we need read, write, update and delete operations in O(1), we use two data structures.

*

*An Object(or Map)in JavaScript provides retrieval in O(1).

*A Doubly LinkedList(Custom data structure we create) makes below functionalities in O(1)

*

*change position of the most used element to the top

*delete least used element from cache on reaching cache limit.

The custom implementation of Doubly LinkedList and Least Recently Used cache with clear explanation is given below.
https://medium.com/dsinjs/implementing-lru-cache-in-javascript-94ba6755cda9


text:
Q: Junit testing for exception Hello I have a code similar to this and I need to write junit test for it, but I keep getting nullpointeException, can any body write the test for this?
 public class myState{
     @Inject
       private StateData stateData;
   public String getAbbreviation(){
       try{
           state selectedState= StateData.getSelectedState().getState();
           formatedAbbrebiation=selectedState.getStline()+""+selectedState.getRegion();

    }
     catch(Exception e){
         formatedAbbrebiation="abbrebiation not available"
    }
     return formatedAbbrebiation;
    }

This is what I have tried :
StateData stateData=Mockito.mock(StateData.class);
Mockito.when(stateData.getSelectedState().getState()).thenReturn(selectedState)
Mockito.when(selectedState.getStLine())).thenThrow(new Exception());


text:
Q: ReferenceError: listen is not defined in NodeJS I have installed NodeJS on Ubuntu (14.04) and i am trying to get my first code working:
var http = require("http");

http.createServer(function(request,response){
    response.writeHead(200, {"Content-Type": "text/html"});
    response.write("");
    response.write("<title>Node.JS</title>");
    respons.write("Hello web");
    respons.write("");
    response.end();
}),
listen(9999);

I get this error:
/home/privateuser/nodejsweb/helloweb.js:11
listen(9999);
^
ReferenceError: listen is not defined

at Object.<anonymous> (/home/privateuser/nodejsweb/helloweb.js:11:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:929:3

During install of NodeJS i got an error during install of optional "something":
Optional: install build tools
To compile and install native addons from npm you may also need to install build tools:
    apt-get install -y build-essential
got error:=> E: Kon het vergrendelingsbestand '/var/lib/dpkg/lock' niet openen - open (13: Toegang geweigerd)
E: Kan de beheersmap (/var/lib/dpkg/) niet vergrendelen. Heeft u beheerdersrechten?
when i used this command with sudo it tells me the last version is already installed?
Then i have tried:
auto-apt run node helloweb.js
Entering auto-apt mode: node helloweb.js
Exit the command to leave auto-apt mode.
But still gives the reference error for listen?
Please help, this is my second day with Ubuntu and my first NodeJS example and i am already stuck now:(
Thanks in advance for any help!

A: var http = require("http");

http.createServer(function(request,response){
    response.writeHead(200, {"Content-Type": "text/html"});
    response.write("");
    response.write("<title>Node.JS</title>");
    respons.write("Hello web");
    respons.write("");
    response.end();
}).listen(9999);

listen is a function that needs to be called on what is returned by createServer


text:
Q: Force Google Chrome to ask before update Google chrome updates to new version without asking for permission to do so. How to tame Google Chrome to be polite and ask before it plays with my Windows 7 machine?

A: You cannot make Google Chrome ask you before update, not anymore. All you can do is to disable automatic updates completely and then update manually. Looks like silent update is the feature since 2008.


text:
Q: Index value 0 to 8 could be out of prefix range 1 to 8 - VHDL In my code I'm defining this vector:
Data: in std_logic_vector(1 to 8);

So I have an input 0:7 and I solve a counter problem when it reaches 0. But my Synthesizer gives me this warning:

Index value 0 to 8 could be out of prefix range 1 to 8

It can create errors? Or it just warns that if I use index 0, it can create errors?

A: It looks like you are indexing your vector with a value that has 9 values  in its range (such as signal index : integer range 0 to 8), but your vector only has 8 values (so you need signal index : integer range 1 to 8). If you post the code where you use in, and the declarations for any signals/values involved in indexing, we can provide more details.


text:
Q: use Apache Alias instead of RewriteRule to serve HTML page A simple Alias in Apache configuration not working -
Alias /url/path/some-deleted-page.html /url/path-modified/new-avatar-of-some-deleted-page.html

It gives "page not found".
However RewriteRule works as expected but it sends redirect status to browser. I want browser/user not to be aware of the redirect. Hence, I want to use Alias instead of RewriteRule. I want to confirm if mod_alias can be used to map individual URL.
I use ProxyPassMatch also which executes all html pages as PHP script. Also adding ProxyPass makes no diffrence.
ProxyPass /url/path/some-deleted-page.html !

Please help so that I can map individual URL (a bunch of them) with Alias instead of RewriteRule.

A: The purpose of mod_alias is to map requested URLs with a directory on the system running your httpd instance.  It does not return anything to the browser (i.e. no redirection code, nothing).  It is all done internally.  Hence your client does not even know it is there.

Request: http://www.example.com/someurl/index.html

Configuration
[...]
DocumentRoot "/opt/apache/htdocs"
Alias "/someurl/" "/opt/other_path/someurl_files/"
[...]

In this scenario, users asking for any URL besides /someurl/ would receive files from /opt/apache/htdocs.
If a user asks for /someurl/, files from /opt/other_path/someurl_files/ will be used.
Still missing in this example is a <Directory> definition for securing the Alias directory.
You should read: https://httpd.apache.org/docs/2.4/mod/mod_alias.html

Alias will cover the case where you need to point a certain URL to a particular directory on the file system.
If you need to modify the filename (i.e. the client asks for file A, and you send back page B), you should use RewriteRule.  And to hide the fact you changed the filename, use the [P] flag.
This directive allows you to use regex, yet still use a proxy mechanism.  So your client does know what went on, as the address in his address bar does not change.


text:
Q: Laravel 4 : Detect and update intended url How do I detect the intended URL and edit it, if the intended URL has a specific value like:
if($intended_url == 'http://.../logout')
{
    //forget or update it
    $intended_url = '/home';
}

A: Laravel sets a url.intended session variable for intended URLs.
You could do this:
Route::get('/logout', function (){

      if (Session::get('url.intended')) == 'http://example.com/logout')
      {
           Session::put('url.intended', 'http://example.com/home');
      }
});

A: Use...
if (location.href =="http://google.com"){
alert('its google');
} else{
alert('location is ' + location.href);
};

window.location is the object to get this value.
You can assign by using
location.href = "http://hotmail.com";


text:
Q: In kartik/gridview of yii2 export link is not display its shows the #? I have written following code for export data as csv or other format using kartik/gridview plugin in yii2. When i click on export button its display # sign on each type of export so hot fix this issue.
index.php
    <?php
    use yii\helpers\Html;
    use yii\grid\GridView;
    use yii\widgets\Pjax;
    use app\models\AdminUserMaster;
    use yii\helpers\Url;
    use app\models\SubAdminRoles;
    use kartik\export\ExportMenu;
/* This code for design coloumns */
                        $gridColumns = [
                            ['class' => 'yii\grid\SerialColumn'],
                            'full_name',
                            'email',
                            ['class' => 'yii\grid\ActionColumn'],
                        ];

/* This code create export menu */
    echo ExportMenu::widget([
        'dataProvider' => $dataProvider,
        'columns' => $gridColumns,
         'target' => ExportMenu::TARGET_BLANK,
        'fontAwesome' => true,
        'dropdownOptions' => [
            'label' => 'Export All',
            'class' => 'btn btn-default'
        ]]);

/* This code create a gridview with column and data with action and number column */
    echo \kartik\grid\GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
         'responsive' => true,
            'hover' => true,
            'bordered' => false,
            'floatHeader' => true,
                    'pjax' => true,
        'columns' => $gridColumns,]);

    ?>
/* This code will configured the gridview module */

web.php file
    'modules' => [
                    'gridview' => [
                    'class' => '\kartik\grid\Module',
                    //'downloadAction' => 'export',
                    'downloadAction' => 'gridview/export/download',
                    ]

    So please help me how to fix this issue.

A: you need to create export options for csv like this.
GridView::widget([
        'id' => 'kv-grid-vehicle',
        'dataProvider'=>$dataProvider,
        'filterModel'=>$searchModel,
        'columns'=>$gridColumns,
        'resizableColumns'=>true,
        'containerOptions'=>['style'=>'overflow: auto'], // only set when $responsive = false
        'headerRowOptions'=>['class'=>'kartik-sheet-style'],
        'filterRowOptions'=>['class'=>'kartik-sheet-style'],
        'pjax'=>true, // pjax is set to always true for this demo
        'export'=>[
            'fontAwesome'=>true
        ],
        // parameters from the demo form
        'bordered'=>true,
        'striped'=>false,
        'condensed'=>true,
        'responsive'=>false,
        'hover'=>true,
        'showPageSummary'=>false,
        'panel'=>[
            'type'=>GridView::TYPE_PRIMARY,
        ],
        'persistResize'=>false,
        'exportConfig'=>$defaultExportConfig,
    ]);
    ?>

and $defaultExportConfig like this
$defaultExportConfig = [
    GridView::CSV => [
        'label' => Yii::t('kvgrid', 'CSV'),
        'icon' => $isFa ? 'file-code-o' : 'floppy-open',
        'iconOptions' => ['class' => 'text-primary'],
        'showHeader' => true,
        'showPageSummary' => true,
        'showFooter' => true,
        'showCaption' => true,
        'filename' => Yii::t('kvgrid', 'grid-export'),
        'alertMsg' => Yii::t('kvgrid', 'The CSV export file will be generated for download.'),
        'options' => ['title' => Yii::t('kvgrid', 'Comma Separated Values')],
        'mime' => 'application/csv',
        'config' => [
            'colDelimiter' => ",",
            'rowDelimiter' => "\r\n",
        ]
    ],
]

may this help you.


text:
Q: simultanous read and write (stdin, stdout) in C I'm trying to write a chat client and server and the client should be able to print the messeges from the server while also writing something on the console.
So I created a pthread that should read the user input and the main thread prints the messeges from the server. But when I type something and while typing a messege is received, the text I was typing is pushed up on the console. How can i fix that?
for example:
I'm typing "abcdef" and then when I get a messege from the server (but didn't finish typing yet) it will look like this:
abcdef[Chatuser1]:Hello

A: Use synchronization technique like semaphore or mutex to synchronize input and output in your multi threaded program

A: I would really recommend doing something like this in a GUI with two seperate edit box elements and not in a console.
If you still want to do it in a console, you will need to do direct console buffer modification.
Every time a new output message arrives, the current input message has to be backed up so you can savely write to the console then do some custom scrolling and add the input message back again. Thread syncronisation is needed to prevent mixing of input and output in the buffer.
I think you also would not get around custom key handling, because otherwise you have no access to partialy typed input.


text:
Q: How to resize image pixel size programmatically i am creating app using facebook. if i am trying to upload photo to facebook means i got following message any give idea for solve that
"The provided user_generated photo for an OG action must be at least 480px in both dimensions"

A: I use a function like follow to get an image with any size.
Original image should big than you wanted.(ps:You can try an image little)
+ (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)wantSize
{
    UIImage * targetImage;
    if (nil == image) {
        targetImage = nil;
    }else{
        CGSize size = image.size;
        CGRect rect;
        if (wantSize.width/wantSize.height > size.width/size.height) {
            rect.size.width = wantSize.height*size.width/size.height;
            rect.size.height = wantSize.height;
            rect.origin.x = (wantSize.width - rect.size.width)/2;
            rect.origin.y = 0;
        } else{
            rect.size.width = wantSize.width;
            rect.size.height = wantSize.width*size.height/size.width;
            rect.origin.x = 0;
            rect.origin.y = (wantSize.height - rect.size.height)/2;
        }
        UIGraphicsBeginImageContext(wantSize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        UIRectFill(CGRectMake(0, 0, wantSize.width, wantSize.height));//clear background
        [image drawInRect:rect];
        targetImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return targetImage;
}

A: You must provide a bigger image, with at least 480px width and height.

A: Your image is apparently smaller than 480px wide or tall. The problem is either that the original image is too small, or you're retrieving it incorrectly. You could, theoretically resize the image to make it bigger, but that will result in pixelation that is probably undesirable.
You should show us how you're retrieving the image. For example, when I want to pick a photo from my library, I'll use the code adapted from Picking an Item from the Photo Library from the Camera Programming Topics for iOS:
UIImagePickerController *mediaUI = [[UIImagePickerController alloc] init];
mediaUI.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;

// To instead show the controls to allow user to trim image, set this to YES;
// If no cropping available, set this to NO.

mediaUI.allowsEditing = YES;

mediaUI.delegate = delegate;

And then, you obviously have to implement the didFinishPickingMediaWithInfo:
#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage, *editedImage, *imageToUse;

    // Handle a still image picked from a photo album
    if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo) {

        editedImage = (UIImage *) [info objectForKey:UIImagePickerControllerEditedImage];
        originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];

        if (editedImage) {
            imageToUse = editedImage;
        } else {
            imageToUse = originalImage;
        }

        NSLog(@"image size = %@", NSStringFromCGSize(imageToUse.size));

        if (imageToUse.size.width < 480 || imageToUse.size.height < 480)
        {
                [[[UIAlertView alloc] initWithTitle:nil
                                            message:@"Please select image that is at least 480 x 480"
                                           delegate:nil
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil] show];
        }
        else
        {
            // do something with imageToUse
        }
    }

    [picker dismissViewControllerAnimated: YES completion:nil];
}


text:
Q: Create non-queued remote COM object specifying server at run time in VB6 I have a COM+ dll installed in a COM application on 2 remote servers. I have exported a non-queued proxy from one of the servers and installed it on a client machine.
I want to be able to specify which remote server the COM object is instantiated on at runtime - the proxy installation contains the Remote Server Name of the machine I exported the proxy from, so simply creating the proxy on the client will always call the machine I exported it from, since it's part of the proxy properties.
The proxy is not queued, so I can't use the method of calling GetObject with a PathName like queue:ComputerName=Server01/new:ComClass.Class.
For non-queued proxies that will always call the remote server they were exported from I just use CreateObject(objectName) and it will use the Remote Server Name from the proxy properties.
After some searching I found a solution (in my self-answer below) but is there a simpler way of doing it within VB6 without having to use the ole32.dll functions?
Edit: After testing the solution proposed by @Bob77 in the comments, called CreateObject with the server name parameter has no effect. Only using the CreateRemoteObject method outlined actually calls the COM component on the specified server.
This may be because the client call is from an IIS process and the user identity of the remote server's COM+ application is different.

A: This can be done using the CoCreateInstanceEx function from the ole32.dll library.
First declare the required functions from ole32.dll and the corresponding data structures:
Private Type SERVER_STRUCTURE
   reserved1   As Long
   pServer     As Long
   AuthInfo    As Long
   reserved2   As Long
End Type

Private Type MULTI_QI
   pIID        As Long
   pInterface  As Object
   hResult     As Long
End Type

Private Declare Function CLSIDFromProgID Lib "ole32.dll" _
                 (progid As Any, clsid As Any) As Long

Private Declare Function OleInitialize Lib "ole32.dll" _
                 (ByVal Nullptr As Long) As Long

Private Declare Function CoCreateInstanceEx Lib "ole32.dll" _
                 (clsid As Any, ByVal pUnkOuter As Long, _
                  ByVal Context As Long, server As SERVER_STRUCTURE, _
                  ByVal nElems As Long, mqi As MULTI_QI) As Long

I then use this function that takes in the object name and server name and returns an instance of the object, which would be a proxy to the required server:
Private Function CreateRemoteObject(ByVal ObjectName As String, _
                   ByVal ByVal serverName As String) As Object

    Dim clsid(256) As Byte
    Dim progid() As Byte
    Dim server() As Byte
    Dim queryInterface As MULTI_QI
    Dim serverStructure As SERVER_STRUCTURE
    Dim refiid(16) As Byte
    Dim longReturnCode As Long
    Dim errorString As String

    errorString = ""

    GetInterfaceIDforIDispatch refiid()     ' set an interface ID for IDispatch
    queryInterface.pIID = VarPtr(refiid(0)) ' point to the interface ID
    progid = ObjectName & Chr$(0)           ' specify the object to be launched
    server = serverName & Chr$(0)           ' specify the server
    OleInitialize 0                         ' initialise OLE
    longReturnCode = CLSIDFromProgID(progid(0), clsid(0))   ' get the CLSID for the object

    If longReturnCode <> 0 Then
        errorString = "Unable to obtain CLSID from progid " & ObjectName
        App.LogEvent errorString, vbLogEventTypeError
        Exit Function
    End If

    ' point to server name and invoke a remote instance of the desired object
    serverStructure.pServer = VarPtr(server(0))
    longReturnCode = CoCreateInstanceEx(clsid(0), 0, 16, serverStructure, 1, queryInterface)

    If longReturnCode <> 0 Then
        errorString = "CoCreateInstanceEx failed with error code " & Hex$(longReturnCode)
        App.LogEvent errorString, vbLogEventTypeError
        Exit Function
    End If

    ' Pass back object ref
    Set CreateRemoteObject = queryInterface.pInterface
End Function

Private Sub GetInterfaceIDforIDispatch(p() As Byte)
    ' fills in the well-known IID for IDispatch into the byte array p.

    p(1) = 4
    p(2) = 2
    p(8) = &HC0
    p(15) = &H46
End Sub


text:
Q: Find Formula for Curvature and Max and Min Values If $C$ is a smooth curve in 3-space parametrized by arc length, then then curvature $k(t)$ is defined as $$k(t)=\frac{||r'(t)\times r''(t)||}{||r'(t)||^3}$$ Let $C$ be the curve parametrized by $x=\cos t, y=\sin t, z=\cos t, 0\le t\le 2\pi$.
How do I find the formula for $k(t)$, the curvature. And, how do I find the max and min values of the radius of curvature for $C$?

A: Your expression $$\kappa(t) = \frac{\|{\bf r}'(t)\times{\bf r}''(t)\|}{\|{\bf r}'(t)\|^3}$$ is actually good for curves with any parametrization, not only for unit speed curves (i.e., curves that are parametrized by arc-length). When I read the question earlier, in a bit of a hurry, I thought that you were asking about a deduction of said formula - as I mentioned in the comments, John Oprea's Differential Geometry and Its Applications is a good reference. That being said, you have: $$\begin{align} {\bf r}(t) &= (\cos t, \sin t, \cos t) \\ {\bf r}'(t) &= (-\sin t, \cos t, -\sin t) \\ {\bf r}''(t) &= (-\cos t, -\sin t, -\cos t) = -{\bf r}(t)\end{align}$$
Don't be afraid, plug everything in the expression for $\kappa(t)$ above. You don't have to think much, it is mechanical. Now, remember that if $\kappa(t)$ is the curvature, then $R(t) = 1/\kappa(t)$ is the radius of curvature. Once you find $\kappa(t)$, you automatically get $R(t)$.
And for finding max/min for $R(t)$, note that although we've been dealing with vectors so far, $R$ is a function that receives a real number $t$ and spits a real number $R(t)$. So you'll use what you have learned in single variable calculus - meaning: solve $R'(t_0) = 0$, then see the sign of $R''(t_0)$ (max.:  $<0$, min.: $>0$, saddle point:$=0$).
Just take it slowly and you can do it.


text:
Q: UIImagePickerControllerOriginalImage is not working in ios 11.2.1 In what cases will I be sad? if I have set allowEditing as false.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        // I am happy :)
    } else {
        // I am sad :(
    }
    dismiss(animated: true, completion: nil)
}

(I got a crash in iOS 11.2.1 iPhone SE(as per Crashlytics), so confused if there are legit conditions where this can fail or it is just an iOS bug.)

A: I've read it in a Apple Developer Forum thread that, if the image size is larger (Above 2048 X 2048) on iOS 11 UIImagePickerControllerOriginalImage returns nil. As a work-around the post suggests to use Photos framework to get the picked image. The solution offered in that post is as follows:
Objective C:
__block UIImage *image = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
if (@available(iOS 11.0, *))
{
    PHAsset * asset = (PHAsset*)[info objectForKey:UIImagePickerControllerPHAsset];
    PHImageManager *manager = [PHImageManager defaultManager];
    PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
    requestOptions.resizeMode = PHImageRequestOptionsResizeModeExact;
    requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    requestOptions.synchronous = true;
    [manager requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeDefault options:requestOptions resultHandler:^void(UIImage *img, NSDictionary *info) {
       if(img != nil)
       {
          image = img;
       }
    }];
}

Reference : iOS 11 does not return the original image for large images with UIImagePickerControllerOriginalImage
Swift:
var image = info[UIImagePickerControllerOriginalImage]
if #available(iOS 11.0, *)
{
    let asset                    = info[UIImagePickerControllerPHAsset] as! PHAsset
    let manager                  = PHImageManager.default()
    let requestOptions           = PHImageRequestOptions()
    requestOptions.resizeMode    = PHImageRequestOptionsResizeMode.exact
    requestOptions.deliveryMode  = PHImageRequestOptionsDeliveryMode.highQualityFormat
    requestOptions.isSynchronous = true
    manager.requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: PHImageContentMode.default, options: requestOptions, resultHandler: { (img, info) in
        if img != nil
        {
            image = img
        }
    })
}

A: the method signature has changed like so:
  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    guard let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else {
        fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
    }

    // Set photoImageView to display the selected image.
    photoImageView.image = selectedImage

    // Dismiss the picker.
    dismiss(animated: true, completion: nil)
}

Note the second argument:
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]

It is not an array of strings like in the previous method signature.

A: changed in IOS 12
  image.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage

A: I ended up using this:
import Photos

extension UIImage {
    static func from(info: [String : Any]) -> UIImage? {
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
            return image
        }

        var imageToBeReturned: UIImage?
        if let url = info[UIImagePickerControllerReferenceURL] as? URL,
            let asset = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil).firstObject {
            let manager = PHImageManager.default()
            let option = PHImageRequestOptions()
            option.isSynchronous = true
            manager.requestImage(for: asset, targetSize: CGSize(width: 1000, height: 1000), contentMode: .aspectFit, options: option, resultHandler: {(image: UIImage?, info: [AnyHashable : Any]?) in
                imageToBeReturned = image
            })
        }
        return imageToBeReturned
    }
}

In this way-
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let selectedImage = UIImage.from(info: info) {
        // I am happy :)
    } else {
        // I am sad :(
    }
    dismiss(animated: true, completion: nil)
}

This is working for me, please do suggest any improvements :)


text:
Q: What does 'do a 180' mean in Halo 3? I was reading this tip on my Halo 3 guide. It said to find a certain skull on the Covenant. I had to climb up this pathway at the 2 tower, turn left, then do a "180". How am I suppose to do a 180?

A: "Do a 180" means to turn around.  Specifically, turn 180 degrees, which is a half-circle.  A 360 is therefore turning completely around to face the same way as you started.
This is not Halo-specific, it's a common English term which is frequently used in so-called "extreme sports."


text:
Q: In R, which() is returning integer(0) for the search of a word within a book I'm sorry if this has been covered but I can't find a comparable question that's helpful here or anywhere else that isn't much too complicated for my beginner self. I just started learning R and am trying a practice problem that is literally identical to the one I was working on from the textbook, just with Jane Austen instead of Melville. Right now I'm trying to establish the beginning and end of the text so I can get rid of the metadata and be left with just the text. Here is my code:
# import the file
text.v <- scan("data/plainText/austen.txt", what="character", sep="\n")
# find the first and last sentences
start.v <- which(text.v == "CHAPTER 1. The family of Dashwood")
end.v <- which(text.v == "live twenty years longer.")

When I run it and then enter start.v or end.v into the console, I get integer(0).
However, the comparable code with the Melville returns the proper values.
#load text file
text.v <- scan("data/plainText/melville.txt", what="character", sep="\n")
text.v #view whole book
text.v[1] #view first line of book, as separated by \n
#create "bookmarks" to show the beginning and end of text
start.v <- which(text.v == "CHAPTER 1. Loomings.")
end.v <- which(text.v == "orphan.")


text:
Q: Change size of chapter/(sub)section headings to specific pt size How do I change the size of my chapter headings to 35 pt, section headings to 24 pt and subsection headings to 14 pt?
I know I can change the sizes using \HUGE, \Huge, etc... but according to the memoir manual, \HUGE is only 20 pt when \normalsize is 9 pt.
\documentclass[9pt,extrafontsizes]{memoir}

\usepackage[sfdefault]{roboto}

\chapterstyle{hangnum}

\newcommand{\vubfont}[1]{\usefont{T1}{qag}{m}{n}#1}
\newcommand{\vubfontbf}[1]{\usefont{T1}{qag}{b}{n}#1}

\renewcommand*{\chapnumfont}{\vubfontbf\HUGE}
\renewcommand*{\chaptitlefont}{\vubfont\HUGE}
\setsecheadstyle{\vubfont\Huge}
\setsubsecheadstyle{\vubfontbf\LARGE}

\begin{document}
\chapter{Avant Garde -- 35pt}
\section{Avant Garde -- 24pt}
Roboto -- 9pt
\subsection{Avant Garde bold -- 14pt}
Roboto -- 9pt
\end{document}

(Also, is this the best way to change the fonts of the headings to Avant Garde?)

A: You can define a new fontsize using
\def\<name>{\fontsize{<fontsize>}{<baselineskip>}\selectfont}

Also, in memoir, when you use the class option 9pt, \huge is 14pt.
This works:
\documentclass[9pt,extrafontsizes]{memoir}

\usepackage[sfdefault]{roboto}

\chapterstyle{hangnum}

\newcommand{\vubfont}[1]{\usefont{T1}{qag}{m}{n}#1}
\newcommand{\vubfontbf}[1]{\usefont{T1}{qag}{b}{n}#1}
\def\chapsize{\fontsize{35}{42}\selectfont}
\def\secsize{\fontsize{24}{30}\selectfont}

\renewcommand*{\chapnumfont}{\vubfontbf\chapsize}
\renewcommand*{\chaptitlefont}{\vubfont\chapsize}
\setsecheadstyle{\vubfont\secsize}
\setsubsecheadstyle{\vubfontbf\huge}

\begin{document}
    \chapter{Avant Garde -- 35pt}
    \section{Avant Garde -- 24pt}
    Roboto -- 9pt
    \subsection{Avant Garde bold -- 14pt}
    Roboto -- 9pt
\end{document}


text:
Q: 404 Apache tomcat in a Java project So this is my project:

Where Registro.java is:
    package Ejer2;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.*;

@SuppressWarnings("deprecation")
@WebServlet(urlPatterns="/Registro")
public class Registro extends HttpServlet implements SingleThreadModel{
    private static final long serialVersionUID = 1L;

    public Registro() {
        super();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        HttpSession session=req.getSession(true);
        Usuario miuser=(Usuario)session.getValue(session.getId());
        if(miuser==null){
            miuser=new Usuario(req.getParameter("user"),req.getParameter("password"));
            session.putValue(session.getId(),miuser);
        }
        res.setContentType("text/html");

        String user=req.getParameter("user");
        //String pass = req.getParameter("pass");

        PrintWriter toClient = res.getWriter();
        toClient.println("");
        toClient.println("<title>REGISTRO REALIZADO</title>");
        toClient.println("Usuario "+user+" registrado con exito");
        toClient.println("");

        toClient.close();
    }

}

And registro.html is:
<!DOCTYPE html>

        <meta charset="ISO-8859-1">
        <title>Registro</title>

        <form action="/Ejer2/Registro" method="POST">
            <input type=hidden name=registro value=resultadoRegistro>

Username: <input type=text name=user>

Password: <input type=password name=pass>

<input type=submit value="Enviar"><input type=reset>
        </form>

When I run registro.html everything goes as expected:

But when I enter an username and a password it doesnt work:
4
It seems as if it doesnt find the Registro.java. I have tried changing the action="/Ejer2/Registro" to many other things like just /Registro orthe full http://... but still doesnt work.
This is my web.xml:

What can be the problem?

A: I guess you are missing servlet mapping in your web.xml. You need to register your servlet in web.xml (open web.xml file and at the bottom change tab to see actual source code not designer) add following code and you should be good to go
<servlet>
    <servlet-name>RegistroServlet</servlet-name>
    <servlet-class>Ejer2.Registro</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>RegistroServlet</servlet-name>
    <url-pattern>/Registro</url-pattern>
</servlet-mapping>

I also suggest you to step back and start with basic java before attemping to write web application. You have several newbie issueses with your code:
1) name of packages should start with lower case !
2) also url mapping should be with lower case like this /registro
in your form action change url to match urlmapping. In your case it's
form action="/Registro" ...
Ejer2 is name of package it has nothing to do with url mapping. Hope it helps to resolve your problem


text:
Q: How to implement custom object like NSArray I want to implement an object named "XXXList" which will return a collection (not NSArray subclass), so that I can use it like an NSArray:
XXXList *list = [XXXList list];

for(id object in list)
{
    ......
}

A: There are several things you can do with NSArrays, I'll list the two of them that I think might be what you're after:
Firstly you can iterate with a for…in loop (NSFastEnumeration), secondly you can use the indexed subscript notation (something like list[2]). Fortunately, both of these are available for other types of objects as well, you just need to implement them.
Implementing NSFastEnumeration isn't so trivial, I'd suggest reading up on Mike Ash's NSBlog post.
Implementing subscript notation on the other hand is quite simple, there are just two methods you need to implement.
There's the getter:
 - (id)objectAtIndexedSubscript: (NSUInteger)index;

and the setter
 - (void)setObject: (id)obj atIndexedSubscript: (NSUInteger)index;

There's an NSBlog post on that, too.

A: You need to implement NSFastEnumeration if you want to use your own classes.


text:
Q: Error while uploading image file jsp mysql This is the back-end code,
<%@ page contentType="text/html;charset=utf-8"%>
<%@ page import="java.util.*"%>
<%@ page import="java.sql.*"%>
<%@ page import="java.io.*"%>

<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.*"%>

<%@ page import="org.apache.commons.fileupload.disk.*"%>

<%! Connection con=null; %>
<%! Statement st= null; %>

<%
String lunchName = null;
String lunchDate = null;
InputStream lunchImage = null;
//out.print("lunch name:::::");
//out.print(request.getParameter("lunch_name"));
//out.print("lunch date:::::");
//out.print(request.getParameter("lunch_date"));
String id = request.getParameter("id");

//Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();

//Configure a repository (to ensure a secure temp location is used)
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);

//Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);

//Parse the request
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
    FileItem item = iter.next();

    if (item.isFormField()) {
            String name = item.getFieldName();
            String value = item.getString();
            if(name.equals("lunch_name"))
                lunchName = value;
            else if(name.equals("lunch_date"))
                lunchDate = value;

    } else {
        lunchImage = item.getInputStream();
        //String fieldName = item.getFieldName();
        //String fileName = item.getName();
        //String contentType = item.getContentType();
        //boolean isInMemory = item.isInMemory();
        //long sizeInBytes = item.getSize();
        //out.print("fieldName : " + fieldName+"
");
        //out.print("fileName : " + fileName+"
");
    }
}
try{
    String message = null;
    Connection con=null;
    String driver = "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/first_app";
    String user = "root";
    String password = "asd462";
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    con = DriverManager.getConnection(url, user, password);
    String sql = "insert into lunch_menu(lunch_image,lunch_name,lunch_date) values(?,?,?)";
    PreparedStatement statement = con.prepareStatement(sql);
    if (lunchImage != null) {
        // fetches input stream of the upload file for the blob column
        statement.setBlob(1, lunchImage);
    }
    statement.setString(2, lunchName);
    statement.setString(3, lunchDate);

    // sends the statement to the database server
    int row = statement.executeUpdate();
    if (row > 0) {
        message = "File uploaded and saved into database";
    }
}catch(SQLException ex){

     ex.printStackTrace();
}finally {
    if (con != null) {
        // closes the database connection
        try {
            con.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

}

%>

i've checked that the data from the front is fine.
but if i run this, i have an error like this.
org.apache.jasper.JasperException: An exception occurred processing JSP page /jsp/writeMenu.jsp at line 73

70:     PreparedStatement statement = con.prepareStatement(sql);
71:     if (lunchImage != null) {
72:         // fetches input stream of the upload file for the blob column
73:         statement.setBlob(1, lunchImage);
74:     }
75:     statement.setString(2, lunchName);
76:     statement.setString(3, lunchDate);

Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:553)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:442)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause

javax.servlet.ServletException: java.lang.AbstractMethodError: com.mysql.jdbc.PreparedStatement.setBlob(ILjava/io/InputStream;)V
    org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:911)
    org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:840)
    org.apache.jsp.jsp.writeMenu_jsp._jspService(writeMenu_jsp.java:174)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause

java.lang.AbstractMethodError: com.mysql.jdbc.PreparedStatement.setBlob(ILjava/io/InputStream;)V
    org.apache.jsp.jsp.writeMenu_jsp._jspService(writeMenu_jsp.java:135)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.12 logs.

i followed the code in here,
http://www.codejava.net/coding/upload-files-to-database-servlet-jsp-mysql
plus,
http://commons.apache.org/proper/commons-fileupload/using.html
what should be the problem?

A: Your stack trace shows an java.lang.AbstractMethodError for com.mysql.jdbc.PreparedStatement.setBlob  That means that your JDBC driver does not implement the setBlob method with an InputStream parameter.  According to Java 6 docs, this is supported only since 1.6 (Java 6).  Check your Java and driver versions; you need a newer version where this method is implemented.


text:
Q: Automate appending additional database connection to env.php I have a customized env.php that has an additional customized database connection appended to it. This file is edited manually and is not in a source code repo because a new installation of Magento will overwrite it.
My objective is to ensure the customized env.php file is in place after every deployment regardless if it's a new Magento install or update.
What is the most secure and efficient approach to appending this extra db connection to env.php during every run of the deployment script (this script is in source code repo)?
I want to be careful not to interfere with the way Magento handles the env.php so the correct Magento commands and timing of the data being appended is key.
Thank you


text:
Q: Remove any row with at least 1 NA with PySpark I have a pyspark dataframe and I would like to remove any row countaining at least one NA.
I know how to do so only for one column (code below).
How to do the same for all columns of the dataframe?
Reproducible example
# Import modules
from pyspark.sql import SparkSession
from pyspark import SparkContext
from pyspark.sql.functions import col
from pyspark.sql import Row

# Defining SparkContext
SparkContext.getOrCreate()

# Defining SparkSession
spark = SparkSession \
    .builder \
    .master("local") \
    .appName("Introduction au DataFrame") \
    .getOrCreate()

# Initiating DataFrame
values = [("1","2","3"),
          ("NA","1", "2"),
          ("4", "NA", "1")]
columns = ['var1',
           'var2',
           'var3']
df = spark.createDataFrame(values, columns)

# Initial dataframe
df.show()
+----+----+----+
|var1|var2|var3|
+----+----+----+
|   1|   2|   3|
|  NA|   1|   2|
|   4|  NA|   1|
+----+----+----+

# Subset rows without NAs (column 'var1')
df.where(~col('var1').contains('NA')).show()
+----+----+----+
|var1|var2|var3|
+----+----+----+
|   1|   2|   3|
|   4|  NA|   1|
+----+----+----+

My expected output
+----+----+----+
|var1|var2|var3|
+----+----+----+
|   1|   2|   3|
+----+----+----+

What I also tried
I have tried the following but it seems that PySpark doesn't recognize NAs as in pandas.
It only recognizes null values.
df.na.drop().show()
df.select([count(when(isnan('var1'), True))]).show()
df.filter(df['var1'].isNotNull()).show()

A: try this one :
df.dropna().show()

you can specify the paramter in dropna method also:
if how = 'any' , then it's your case
or how = 'all' the row will be removed if all columns are null
how by default is 'any'

A: new = (df.na.replace({'NA': None})#Replace string NA with null
       .dropna()#Drop NA
      ).show()


text:
Q: What is the good practice to manage i18n with an API? I've created a small helpers framework and I want it to be multi-languages. So I used the .resx files for translation.
But, I'm afraid the satellites dll's will be a real mess when my framework is used into an application that has its own .resx...
So I'd like to know the best practices to avoid what seems to be a resource hell

A: The best practice is to follow Microsoft guidelines. Therefore *.resx files, or more precisely Satellite Assemblies is exactly what you should be using.
The problem with this approach, however is how you handle dependencies. From what I understand, you don't want to pollute the disk with additional libraries. So, you would like your clients to install just the needed files and nothing else.
The good news is, you can do that and you can still use Satellite Assemblies. All you have to do, is to pack the assembly into your DLL and override Assembly Resolution event, so that it will use internal file rather than searching for it on disk. However, with all the pros are also the cons. When you do that, your clients will have to install one file (rather large one), but they will be forced to choose from languages you provided. They won't be able to cut anything out, nor add additional language in the future.
I hope now you understand why Satellite Assembly approach is the best solution - it gives you the control over Localization process. There is no better way of handling this, sorry.
BTW. The DLL hell was related to the multiple versions of the same library needed by different clients. It won't happen in your case. Of course additional files means additional installer entries, but there is a reason why people created the concept of Merge Modules. I wouldn't worry so much for it, I would just provide framework as a merge module and let people customize it themselves, if they really have to do that.


text:
Q: How do I query in TFS to get work items with specified conditions for ALL OF its childs In TFS query builder, I need a query to get all PBIs that ALL of its child tasks are in done state.
for example :
PBI : User Story 1
    - Task 1 (Done)
    - Task 2 (Done)
    - Task 3 (Done)

PBI : User Story 2
    - Task 1 (Done)
    - Task 2 (Done)
    - Task 3 (In Progress)

In above example, the desired query should only returns User Story 1

A: You should create a "Work Item and Direct Links" query.
In the top query select:

"Work Item Type = Product Backlog Items" & "State In Committed, Done"

In the bottom query select:

"Work Item Type = Task" & "State <> Done"

In the radio buttons on the left select:

"only top level items that do not have the link."

Should suit but there are two assumptions:

*

*All PBI's that have been committed by the team have at least one task

*PBI's that are in New or Approved are not being worked on

A: Type == "Product Backlog Item"
Total number of Child Tasks > 0
Number of Child Tasks WHERE (task.State == "Done") == Total number of Child Tasks