text:
Q: Do these three questions mean the same thing? And do you need a preposition when asking about places? To where did you go yesterday?

Where did you go to yesterday?

Where did you go yesterday?

I see people omit the 'to' a lot. However, I also asked a related question yesterday
Who did you give the keys to?

To whom did you give the keys?

Here, the 'to' seems necessary. Why can you omit the 'to' when talking about places?

A: Where has a double sense, both as an interrogative and as a relative. It may stand for either

*

*a preposition phrase (PP) denoting a location or destination—approximately equivalent to at or in or to what/which place

Where are you? = At what/which place are you?
  Where are you going? = To what/which place are you going?

But its pro-PP character is already less than obvious when it's used as a relative with a nominal antecedent.

The place where I am going ... = The place to which I am going ...

Moreover, there are instances where it is needed to designate an origin rather than a location or destination, and to avoid ambiguity where has to be coupled with a distinct preposition such as from.

I see where you're going, but I can't make out where you're coming from.

The first of these permits and the second requires that where should stand for

*a nominal designating a place, which can act as the object of a preposition. The most formal style deprecates this pronominal use when a location or goal is designated. But this use is very common outside that style:

Come on, come on, lemme show you where it's at. —Dave Clark Five
  Doesn't have a point of view, Knows not where he's going to —Beatles

And there's no evident reason in grammar for prohibiting where as object of some prepositions and not others. I myself follow the formal use (I actively avoid situations in which where must be employed with a preposition), and P.E.Dant speaks for his namesakes when he says that where ... to and where ... at are redundant; but those are stylistic judgments, not  grammatical ones.
ADDED, with thanks to ruakh for raising the matter:
Note, however, that even in the most colloquial registers we avoid using locative prepositions like at and in immediately before where—*Let me show you at where it is— only when they are 'stranded' on the right side of the verb. Goal prepositions (to, by, until) and trajectory and origin prepositions (via, through, from) are borderline: they are apt to sound contrived in formal registers and pedantic in colloquial registers. My advice is that you avoid using where in situations where these constructions would be needed and instead use a frank noun: Which road did you take? or What countries are you going to?

A: Of your first three examples, only the second is correct:

Where did you go yesterday?

The preposition to is not omitted in this usage; rather, it is redundant and incorrect usage in the other two (although you will frequently hear "Where did you go to?" in colloquial American speech.) It is redundant because it is unnecessary: the meaning is clear without it.
In your other two examples, to is necessary because the meaning is not clear without it:

Who(m) did you give the keys?


text:
Q: How can I change the overlay color for each image? I'm using FancyBox 2 and I would like to customize the overlay color; I would like this color to match the parent div that is clicked.
For example:

Fancybox Code
$(".fancybox").fancybox( {
    padding:0,
    helpers : {
        overlay : {
            css : { 'background-color' :  **PARENT'S COLOR** }
        }
    }
});

How do I automatically set the correct color in the code above?

A: The easiest way is to get the parent's color on the fly using the beforeShow callback and apply it directly to the .fancybox-overlay selector like :

$(".fancybox").fancybox({
    beforeShow: function() {
        var parentColor = $(this.element).parent().css('backgroundColor');
        $(".fancybox-overlay").css({
            "backgroundColor": parentColor,
            "backgroundImage": 'none' // optional if you prefer a solid color
        });
    }
});

See DEMO

redpajama_set_name: RedPajamaStackExchange


text:
Q: JSESSIONID Cookie with Expiration Date in Tomcat What's the best way to set an expiration date for the JSESSIONID cookie sent by Tomcat for a servlet session?
By default, the expiration date of the cookie seems to be 'session', which means that the session disappears in the client as soon as the browser restarts. But I would like to keep it open for 12h, even after a browser restart (and would then configure the session timeout in the server accordingly).
Is there any way to set an expiration date within Tomcat, e.g. using some configuration option or extension module? Or is there a reliable way to set an expiration date for JSESSIONID using a Servlet filter?

A: As of Servlet 3.0, this can simply be specified in the web.xml:
<session-config>
    <session-timeout>720</session-timeout> <!-- 720 minutes = 12 hours -->
    <cookie-config>
        <max-age>43200</max-age> <!-- 43200 seconds = 12 hours -->
    </cookie-config>
</session-config>

Note that session-timeout is measured in minutes but max-age is measured in seconds.

A: I don't think it's possible to do what you want, without changing the Tomcat code.
Note however that it might have a nasty side effect : if a user starts a session and stays active for twelve hours, its session timeout will be updated accordingly (the timeout will be updated at each request), but its cookie won't, and the user will thus lose its session after 12 hours, even if he's been active all this time.


text:
Q: I want to change audio source onClick I want to change audio source onClick button. I am trying this but I can't take a result.
enter image description here

data() {
    return {
      audioSrc: ''
    }
  },
  methods: {
    setActiveAudio(item) {
      this.$refs.audioElm.src = item;
      this.$refs.audioElm.currentTime = 0;
      this.$refs.audioElm.crossOrigin = 'anonymus';
      this.$refs.audioElm.play();
    },
  },

 Click Sound
<audio ref="audioElm" :src="audioSrc"></audio>

A: You have to use a timer to make sure the DOM has been updated before you interact with the element like
    data() {
    return {
      audioSrc: ''
    }
  },
  methods: {
    setActiveAudio(item) {
      this.audioSrc = item;

      var element = this.$refs.audioElm;
      setTimeout(function()
      {
        element.currentTime = 0;
        element.crossOrigin = 'anonymus';
        element.play();
      }, 0);
    },
  }

Working example on https://jsfiddle.net/AndersBillLinden/6x8hzrga/


text:
Q: Error running Jest in nx monorepo: SyntaxError: Unexpected token 'export' Background
I have a monorepo project built using Nx. This repo contains several reusable libraries for my backend projects. The packages is collected from several projects to create a reusable library.
I use Jest to create and run the unit test used in my monorepo.
Problem
When I run jest, on some test it will throw an error about failure to import .js files with export in them.
Strange thing is those modules have a commonjs version and I can mock those packages without problem in my other project WITHOUT monorepo structure. But when I use the same code in monorepo project (I want to make the code reusable), jest wrongly imports ESM version of the packages instead of the CJS version.
Use case:

*

*I have a blob storage library which uses ali-oss internally.

*ali-oss distributed the CJS and ESM in same package and I can mock it without problem in my other project (without monorepo)

*When I copied the same library into my new monorepo, Jest will complain about export token inside one of ali-oss source in node_modules
Why Jest behave differently in monorepo vs normal repo? How to solve this weird jest module resolution?
Files
tsconfig.json:
{
  "compilerOptions": {
    "module": "commonjs",
    "forceConsistentCasingInFileNames": true,
    "strict": false,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true
  },
  "files": [],
  "include": ["jest.config.ts", "**/*.test.ts", "**/*.spec.ts", "**/*.d.ts"]
}

jest.config.ts:
const nxPreset = require("@nrwl/jest/preset").default;

export default {
  ...nxPreset,
  clearMocks: true,
  coverageReporters: ["lcov", "text", "text-summary", "json-summary"],
  displayName: "kafka",
  globals: {
    "ts-jest": {
      tsconfig: "<rootDir>/tsconfig.spec.json",
    },
  },
  testEnvironment: "node",
  transform: {
    "^.+\\.[tj]s$": "ts-jest"
  },
  moduleFileExtensions: ["ts", "js"],
  coverageDirectory: "../../coverage/packages/kafka",
};

Unit test:
import Bull from "bull";

import * as dlq from "../src/dlq";
import { ModuleContext} from "./context";

jest.mock("bull");

describe(ModuleContext.Root, () => {
  describe(ModuleContext.Runner, () => {
    it("success", () => {
      expect(true).toBe(true);
    })
    describe(dlq.initialize.name, () => {
      it("should return success", () => {
        const createSpy = jest
          .spyOn(Bull.prototype, "process")
          .mockResolvedValue(null);

        dlq.initialize();
        expect(createSpy).toBeCalled();
      });
    });
  });
});

Jest output:
 FAIL   kafka  packages/kafka/test/dlq.spec.ts
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /home/fahmi/logee/logee-ct/logeect-libraries-monorepo/node_modules/.pnpm/msgpackr@1.6.2/node_modules/msgpackr/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { Packr, Encoder, addExtension, pack, encode, NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT, REUSE_BUFFER_MODE } from './pack.js'
                                                                                ^^^^^^

    SyntaxError: Unexpected token 'export'

      at Runtime.createScriptFromCode (../../node_modules/.pnpm/jest-runtime@28.1.3/node_modules/jest-runtime/build/index.js:1796:14)
      at Object.<anonymous> (../../node_modules/.pnpm/bull@4.8.5/node_modules/bull/lib/scripts.js:8:18)

A: Following Nx migration steps described here I could successfully bypass that error.
npx nx migrate latest
npx nx migrate --run-migrations

You can see in the updated files that Nx automatically updates your jest config with the following transform field:
  transform: {
    '^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': '@nrwl/react/plugins/jest', // My config from before
    '^.+\\.[tj]sx?$': ['babel-jest', { presets: ['@nrwl/react/babel'] }], // Added by Nx under the migration
  },

Hope this helps.


text:
Q: C++ member function pointer I need to get the pointer to an object's function. For the sake of not having to rewrite the rest of my program, I can't make the function static. I know that this is not impossible, in a sense, or maybe completely, but I've read that there's obscure ways to get it done.
If possible, what is the simplest way to do it?
If not possible, what are some of the alternatives? The library I'm using requires a pointer to a function.


text:
Q: How can I count occurrences with groupBy? I want to collect the items in a stream into a map which groups equal objects together, and maps to the number of occurrences.
List<String> list = Arrays.asList("Hello", "Hello", "World");
Map<String, Long> wordToFrequency = // what goes here?

So in this case, I would like the map to consist of these entries:
Hello -> 2
World -> 1

How can I do that?

A: Here is the simple solution by StreamEx:
StreamEx.of(list).groupingBy(Function.identity(), MoreCollectors.countingInt());

This has the advantage of reducing the Java stream boilerplate code: collect(Collectors.

A: I think you're just looking for the overload which takes another Collector to specify what to do with each group... and then Collectors.counting() to do the counting:
import java.util.*;
import java.util.stream.*;

class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        list.add("Hello");
        list.add("Hello");
        list.add("World");

        Map<String, Long> counted = list.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(counted);
    }
}

Result:
{Hello=2, World=1}

(There's also the possibility of using groupingByConcurrent for more efficiency. Something to bear in mind for your real code, if it would be safe in your context.)

A: Here is example for list of Objects
Map<String, Long> requirementCountMap = requirements.stream().collect(Collectors.groupingBy(Requirement::getRequirementType, Collectors.counting()));

A: If you're open to using a third-party library, you can use the Collectors2 class in Eclipse Collections to convert the List to a Bag using a Stream. A Bag is a data structure that is built for counting.
Bag<String> counted =
        list.stream().collect(Collectors2.countBy(each -> each));

Assert.assertEquals(1, counted.occurrencesOf("World"));
Assert.assertEquals(2, counted.occurrencesOf("Hello"));

System.out.println(counted.toStringOfItemToCount());

Output:
{World=1, Hello=2}

In this particular case, you can simply collect the List directly into a Bag.
Bag<String> counted =
        list.stream().collect(Collectors2.toBag());

You can also create the Bag without using a Stream by adapting the List with the Eclipse Collections protocols.
Bag<String> counted = Lists.adapt(list).countBy(each -> each);

or in this particular case:
Bag<String> counted = Lists.adapt(list).toBag();

You could also just create the Bag directly.
Bag<String> counted = Bags.mutable.with("Hello", "Hello", "World");

A Bag<String> is like a Map<String, Integer> in that it internally keeps track of keys and their counts.  But, if you ask a Map for a key it doesn't contain, it will return null.  If you ask a Bag for a key it doesn't contain using occurrencesOf, it will return 0.
Note: I am a committer for Eclipse Collections.

A: Here are slightly different options to accomplish the task at hand.
using toMap:
list.stream()
    .collect(Collectors.toMap(Function.identity(), e -> 1, Math::addExact));

using Map::merge:
Map<String, Integer> accumulator = new HashMap<>();
list.forEach(s -> accumulator.merge(s, 1, Math::addExact));

A: List<String> list = new ArrayList<>();

list.add("Hello");
list.add("Hello");
list.add("World");

Map<String, List<String>> collect = list.stream()
                                        .collect(Collectors.groupingBy(o -> o));
collect.entrySet()
       .forEach(e -> System.out.println(e.getKey() + " - " + e.getValue().size()));


text:
Q: JAXB marshal to string works differently on different computers I have this test java app:
@XmlRootElement
public class Car {

    @XmlElement(namespace="http://www.example.com/CAR_NAME")
    private String name;

    @XmlElement(namespace="http://www.example.com/CAR_PRICE")
    private int price;

    @XmlElement(namespace="http://www.example.com/CAR_BUS")
    private Bus bus;

    //constructors, getters and setters

 @XmlRootElement
 public class Bus {

    @XmlElement(namespace="http://www.example.com/BUS_NAME")
    private String name;

    @XmlElement(namespace="http://www.example.com/BUS_PRICE")
    private int price;

    //constructors, getters and setters

@XmlRootElement
public class Request {

    @XmlAnyElement
    private Element element;

    //constructors, getters and setters

And I try convert string xml to Element  set this element to Request  and convert request to string.
public class Main {
    public static void main(String[] args) throws JAXBException, ParserConfigurationException, IOException, SAXException {

        String hz = "<car xmlns:ns6=\"http://www.example.com/CAR_BUS\" xmlns:ns5=\"http://www.example.com/CAR_NAME\" xmlns:ns2=\"http://www.example.com/CAR_PRICE\" xmlns:ns4=\"http://www.example.com/BUS_PRICE\" xmlns:ns3=\"http://www.example.com/BUS_NAME\">\n" +
                "    <ns5:name>CarName1</ns5:name>\n" +
                "    <ns2:price>999</ns2:price>\n" +
                "    <ns6:bus>\n" +
                "        <ns3:name>BusName1</ns3:name>\n" +
                "        <ns4:price>666</ns4:price>\n" +
                "    </ns6:bus>\n" +
                "</car>";

        JAXBContext jaxbContext = JAXBContext.newInstance(Car.class, Bus.class, Request.class);
        Marshaller marshaller = jaxbContext.createMarshaller();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Element documentElement = builder.parse(new InputSource(new StringReader(hz))).getDocumentElement();

        Document document = documentElement.getOwnerDocument();
        DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
        LSSerializer serializer = domImplLS.createLSSerializer();
        String s = serializer.writeToString(documentElement);

        System.out.println(s);

        System.out.println("------------------------------");

        Request request = new Request(documentElement);

        StringWriter sw = new StringWriter();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(request, sw);
        String s1 = sw.toString();
        System.out.println(s1);

    }
}

When I start this application on my machine I get next  output:
<?xml version="1.0" encoding="UTF-16"?>
<car xmlns:ns2="http://www.example.com/CAR_PRICE" xmlns:ns3="http://www.example.com/BUS_NAME" xmlns:ns4="http://www.example.com/BUS_PRICE" xmlns:ns5="http://www.example.com/CAR_NAME" xmlns:ns6="http://www.example.com/CAR_BUS">
    <ns5:name>CarName1</ns5:name>
    <ns2:price>999</ns2:price>
    <ns6:bus>
        <ns3:name>BusName1</ns3:name>
        <ns4:price>666</ns4:price>
    </ns6:bus>
</car>
------------------------------
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<request xmlns:ns6="http://www.example.com/CAR_BUS" xmlns:ns5="http://www.example.com/CAR_NAME" xmlns:ns2="http://www.example.com/CAR_PRICE" xmlns:ns4="http://www.example.com/BUS_PRICE" xmlns:ns3="http://www.example.com/BUS_NAME">
    <car>

        <ns5:name>CarName1</ns5:name>

        <ns2:price>999</ns2:price>

        <ns6:bus>

            <ns3:name>BusName1</ns3:name>

            <ns4:price>666</ns4:price>
    </ns6:bus>
</car>
</request>

But When I start this application on test computer I habe next output:
<?xml version="1.0" encoding="UTF-16"?>
<car xmlns:ns2="http://www.example.com/CAR_PRICE" xmlns:ns3="http://www.example.
com/BUS_NAME" xmlns:ns4="http://www.example.com/BUS_PRICE" xmlns:ns5="http://www.example.com/CAR_NAME" xmlns:ns6="http://www.example.com/CAR_BUS">
    <ns5:name>CarName1</ns5:name>
    <ns2:price>999</ns2:price>
    <ns6:bus>
        <ns3:name>BusName1</ns3:name>
        <ns4:price>666</ns4:price>
    </ns6:bus>
</car>
------------------------------
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<request xmlns:ns6="http://www.example.com/CAR_BUS" xmlns:ns5="http://www.example.com/CAR_NAME" xmlns:ns2="http://www.example.com/CAR_PRICE" xmlns:ns4="http://www.example.com/BUS_PRICE" xmlns:ns3="http://www.example.com/BUS_NAME">
    <car>

        <name>CarName1</name>

        <price>999</price>

        <bus>

            <name>BusName1</name>

            <price>666</price>
    </bus>
</car>
</request>

On the test machine missing tags ns5, ns6, ns2
I do not understand how this can be. The same version of Java, the same application but different output. Because of this, I have problems in the production server. How to fix it or where to find the cause?


text:
Q: How to find the minimal function of this functional using Euler Method for extremals? The original functional was $\ J[x]= \int_{0}^{1} x \cdot f(x) \cdot f'(x) dx $ with $\ h(x) =x $. Solved for the Gateau derivative: $\ \partial J[f,h]= \int_{0}^{1} x \cdot f(x) \cdot h'(x) dx  + \int_{0}^{1} x \cdot f'(x) \cdot h(x) dx$. To use the Euler method, $\ L = x \cdot f \cdot x +  x \cdot f' \cdot x$ such that $\ L_{f} = x^2, L_{f'} = x^2, \frac{d}{dx}L_{f'}=2x $. However, I must have made a mistake that I can't see with that because it yields $\ x^2-2x =0 $ which doesn't tell me anything about what $\ f $ must be.

A: The functional is
$$J[f]=\int_0^1 L(x,f(x),f'(x))\,dx=\int_0^1 xf(x)f'(x)\,dx$$
The Euler-Lagrange equation for this functional, with $L=xff'$ is given by
$$\begin{align}
\frac{\partial }{\partial f}L(x,f,f')-\frac{d}{dx}\frac{\partial}{\partial f'}L(x,f,f')&=\frac{\partial }{\partial f}(xff')-\frac{d}{dx}\frac{\partial}{\partial f'}(xff')\\\\
&=xf'-\frac{d}{dx}(xf)\\\\
&=-f
\end{align}$$
Therefore, the functional has a stationary point for $f(x)\equiv 0$.
At $f=0$, $J[f]=0$, which is not necessarily an extreme value.  That is to say, there exist $f_1(x)$ and $f_2(x)$ for which $L[f_1]>0$ and $L[f_2]<0$ (e.g., $f_1(x)=x$ and $f_2(x)=1-x$).


text:
Q: GirdSearchCV Multiclass-Multioutput Here is my pipeline:
pipeline = Pipeline([('features', FeatureUnion([

            ('text_pipeline', Pipeline([
                ('count_vectorizer', CountVectorizer(tokenizer=tokenize)),
                ('tfidf_transformer', TfidfTransformer())
            ])),

            ('starting_verb_transformer', StartingVerbExtractor())
        ])),

        ('classifier',MultiOutputClassifier(RandomForestClassifier(class_weight='balanced')))
    ])

Here is my cv function:
parameters = {'classifier__estimator__n_estimators': [10],
               }
cv = GridSearchCV(estimator=pipeline, param_grid=parameters, cv=2, scoring = "average_precision", verbose=True)
cv.fit(X_train, y_train)

The error is:
ValueError: multiclass-multioutput format is not supported

But the pipeline.fit works well. How can we solve this problem?


text:
Q: How can I find/install a package that appears not to be available I'm trying to install the novell iPrint client on ubuntu 10.10, which comes as an rpm package and so needs to be installed via alien. One of its requirements to work properly seems to be a package called libglitz-glx1. This package seems to be available for several distributions but not in the main repository for Ubuntu 10.10.
The package does seem to be available for the 32 bit version of ubuntu but I'm running 64 bit. Is it possible to download and use the 32 bit version and rebuild it for 64 bit or is it not that simple...
Simply put: how can I install libglitz-glx1.

A: The Glitz OpenGL 2D graphics library is no longer included in Ubuntu > 10.10. However you can still download and install the am64 Debian package for libglitz-glx1 built for 10.04 from Launchpad. In the URL given you will also find the dependencies that need to be met:
Before installing libglitz-glx1 you obviously need to install libglitz1 that can also be downloaded here.
You need to find out yourself if these libraries are safe to run, as they are not tested for  conflicts with other packages from Maverick.

A: Try the amd64 version of lucid http://packages.ubuntu.com/lucid/libglitz-glx1
For what i have seen the package will be compatible since it needs a certain version or higher which you should have already.


text:
Q: Unable to load config info from /usr/local/ssl/openssl.cnf on Windows While using OpenSSL on Windows:
openssl genrsa -out privatekey.pem 1024 -->
Created successfully
openssl req -new -x509 -key privatekey.pem -out publickey.cer -days 365
---->

Showing error message as

unable to load config info from /usr/local/ssl/openssl.cnf

A: You should specify the absolute path to the config, something like this:
openssl req -x509 -config "C:\OpenSSL-Win64\bin\openssl.cnf" ...

A: In Windows 7 I didn't have to restart, simply run command prompt in administrator mode.

A: In my case, I need to set the path of openssl.cnf file manually on the command using config option. So the command
openssl req -x509 -config "C:\Users\sk\Downloads\openssl-0.9.8k_X64\openssl.cnf" -newkey rsa:4096 -keyout key.pem -out cert.pem -nodes -days 900

A: In Windows 10, no need to restart nor run in Administrator's mode but instead set openssl config like so:
set OPENSSL_CONF=C:\Program Files (x86)\GnuWin32\share\openssl.cnf

Of course, if you are using GnuWin32

A: If you're using Win32 OpenSSL v1.1.0g, setting up this environment variable:
set OPENSSL_CONF=C:\OpenSSL-Win32\bin\cnf\openssl.cnf

Before running this command with "server.key", successfully creating "server.csr":
openssl req -new -key server.key -out server.csr

A: On the basic question of why openssl is not found:
Short answer:Some installation packages for openssl have a default openssl.cnf pre-included.  Other packages do not.
In the latter case you will include one from the link shown below;
You can enter additional user-specifics --DN name,etc-- as needed.
From https://www.openssl.org/docs/manmaster/man5/config.html,I quote directly:
"OPENSSL LIBRARY CONFIGURATION
Applications can automatically configure certain aspects of OpenSSL using the master OpenSSL configuration file, or optionally an alternative configuration file. The openssl utility includes this functionality: any sub command uses the master OpenSSL configuration file unless an option is used in the sub command to use an alternative configuration file.
To enable library configuration the default section needs to contain an appropriate line which points to the main configuration section. The default name is openssl_conf which is used by the openssl utility. Other applications may use an alternative name such as myapplication_conf. All library configuration lines appear in the default section at the start of the configuration file.
The configuration section should consist of a set of name value pairs which contain specific module configuration information. The name represents the name of the configuration module. The meaning of the value is module specific: it may, for example, represent a further configuration section containing configuration module specific information. E.g.:"
So it appears one must self configure openssl.cnf according to your
Distinguished Name (DN), along with other entries specific to your use.
Here is the template file from which you can generate openssl.cnf
with your specific entries.
One Application actually has a demo installation that includes a demo .cnf file.
Additionally, if you need to programmatically access .cnf files, you can
include appropriate headers --openssl/conf.h-- and parse your .cnf files
using
CONF_modules_load_file(const char *filename, const char *appname,
                            unsigned long flags);

Here are docs for "CONF_modules_load_file";

A: The only thing that worked for me in this situation was the self-created openssl.cnf file.
Here are the basics needed for this exercise (edit as needed):
#
# OpenSSL configuration file.
#

# Establish working directory.

dir                         = .

[ ca ]
default_ca                  = CA_default

[ CA_default ]
serial                      = $dir/serial
database                    = $dir/certindex.txt
new_certs_dir               = $dir/certs
certificate                 = $dir/cacert.pem
private_key                 = $dir/private/cakey.pem
default_days                = 365
default_md                  = md5
preserve                    = no
email_in_dn                 = no
nameopt                     = default_ca
certopt                     = default_ca
policy                      = policy_match

[ policy_match ]
countryName                 = match
stateOrProvinceName         = match
organizationName            = match
organizationalUnitName      = optional
commonName                  = supplied
emailAddress                = optional

[ req ]
default_bits                = 1024          # Size of keys
default_keyfile             = key.pem       # name of generated keys
default_md                  = md5               # message digest algorithm
string_mask                 = nombstr       # permitted characters
distinguished_name          = req_distinguished_name
req_extensions              = v3_req

[ req_distinguished_name ]
# Variable name             Prompt string
#-------------------------    ----------------------------------
0.organizationName          = Organization Name (company)
organizationalUnitName      = Organizational Unit Name (department, division)
emailAddress                = Email Address
emailAddress_max            = 40
localityName                = Locality Name (city, district)
stateOrProvinceName         = State or Province Name (full name)
countryName                 = Country Name (2 letter code)
countryName_min             = 2
countryName_max             = 2
commonName                  = Common Name (hostname, IP, or your name)
commonName_max              = 64

# Default values for the above, for consistency and less typing.
# Variable name             Value
#------------------------     ------------------------------
0.organizationName_default  = My Company
localityName_default        = My Town
stateOrProvinceName_default = State or Providence
countryName_default         = US

[ v3_ca ]
basicConstraints            = CA:TRUE
subjectKeyIdentifier        = hash
authorityKeyIdentifier      = keyid:always,issuer:always

[ v3_req ]
basicConstraints            = CA:FALSE
subjectKeyIdentifier        = hash

I hope that helps.

A: In windows , [Similar scenario]
I was facing the same problem But It was during requesting for Certificate Signing Request.
I did the below , It Worked for me.
Once OpenSSL installed, Ran command prompt as administrator after the system reboot.[for the best I did both.. run as admin and system reboot]
did,
1.[Error Case]
C:\OpenSSL-Win64\bin>openssl req -new -key server.key -out server.csr

WARNING: can't open config file: C:\OpenSSL-Win64\bin\openssl.cnf
AND
Unable to load config info from C:\OpenSSL-Win64\bin\openssl.cnf
2.[Worked with Warning]
C:\OpenSSL-Win64\bin> openssl req -new -key server.key -out server.csr -config C:\OpenSSL-Win64\bin\openssl.cfg

[Warning message]: WARNING: can't open config file: C:\OpenSSL-Win64\bin\openssl.cnf

But prompted me for the Pass Phrase for server.key
It worked for me.
I referred,This link for my assistance.
Thank you.

A: After installing OpenSSL I was required to create a new environment variable:

*

*Name: OPENSSL_CONF

*Value: C:\Program Files\OpenSSL\openssl.cnf
In powershell:
$env:OPENSSL_CONF = "${env:ProgramFiles}\OpenSSL\openssl.cnf"

This value differs from previous installation versions (as seen in a previous edit of this post).  Also, don't forget to add the openssl binary folder ${env:ProgramFiles}\OpenSSL to your Path.

A: After installing OpenSSL, you need to restart your computer and use Run As Administrator. Then its works.

A: For me on Windows 8, I simply found openssl.cnf file and copied it on the C drive. then:
openssl req -new -key server.key -out server.csr -config C:\openssl.cnf

Worked perfectly.

A: With the GnuWin32 tools I found the openssl.cnf under C:\gnuwin32\share
set OPENSSL_CONF=C:\gnuwin32\share\openssl.cnf

A: On Windows Powershell:
$env:OPENSSL_CONF = "${env:ProgramFiles}\OpenSSL-Win64\bin\openssl.cfg"

A: For me put variable before calling did the trick:
OPENSSL_CONF=/usr/ssl/openssl.cnf openssl req -new -x509 -key privatekey.pem -out publickey.cer -days 365

A: I had similar problem on Windows 7:
WARNING: can't open config file: C:\OpenSSL-Win32\bin\openssl.cfg
Unable to load config info from C:\OpenSSL-Win32\bin\openssl.cfg

The reason was removed OpenSSL-Win32 directory without using deinstallator, so not all components was properly removed from system.
I had to remove environment variable OPENSSL_CONF manually.
Some openssl binaries, e.g. installed with git, does not need OPENSSL_CONF environment variable, but if this environment variable exists it must lead to valid file.


text:
Q: Eclipse - set custom color theme and now when highlighted things turn black So i got a custom color theme in eclipse, decided i didn't like it and went back to the default.  Now you know when you click on a variable in eclipse it highlights all the other mentions of it.  It does it in black.  So i successfully removed the other features just not that.  Can anyone help me out?

A: This option is can be modified under the Annotations section of the Preferences dialog (as shown below).


text:
Q: unable to share internet from windows 8.1 and my phone kitkat 4.4.4 unable to share internet from pc to phone
before upgrading from red mi 1s version to kitkat I use to connect through usb media

A: You can make a wifi hotspot by running the following in command line as Administrator:
netsh wlan set hostednetwork mode=allow ssid=enterssid key=enterpassword

When you want to start the hotspot, run:
netsh wlan start hostednetwork

To stop the hotspot:
netsh wlan stop hostednetwork

You can also make separate batch files to start/stop your network using notepad, type:
To start:
@echo off
netsh wlan start hostednetwork
pause

To stop:
@echo off
netsh wlan stop hostednetwork
pause

Save those as .bat files on your desktop and right click run as admin.
Then to share your internet, go to Network and Sharing Center -> Change adapter settings
Right click -> Properties on the connection you want to share internet from, then in sharing tab check the box for "Allow other network users to connect through this computer's Internet connection"

A: Stock Kit Kat 4.4.4 does not support that option. Only way to share is to turn Windows machine into hotspot.


text:
Q: Causing unknown signal 6 You are given a set of bars of gold and your goal is to take as much gold as possible into your bag. There is just one copy of each bar and for each bar you can either take it or not (hence you cannot take a fraction of a bar).
Problem Description Task. Given n gold bars, find the maximum weight of gold that fits into a bag of capacity W. Input Format. The first line of the input contains the capacity W of a knapsack and the number n of bars of gold. The next line contains n integers w0,w1,...,wn−1 defining the weights of the bars of gold. Constraints. 1 ≤ W ≤ 104; 1 ≤ n ≤ 300; 0 ≤ w0,...,wn−1 ≤ 105. Output Format. Output the maximum weight of gold that fits into a knapsack of capacity W.
 here is my code.
#include <bits/stdc++.h>
using namespace std;
int optimal(vector<int>&w,int W,int n){
vector<vector<int> > val(n+2,vector<int>(W+2));

  for(int j=0;j<=n;j++)
  {
for(int i=0;i<=W;i++)
  { if(i==0 || j==0){ val[j][i]=0;continue;}
    if(w[j]<=i)
    {
        val[j][i]=max(val[j-1][i],(w[j]+val[j-1][i-w[j]]));
        //cout<<val[j][i]<<endl;
    }
    else {val[j][i]=val[j-1][i];

  }}
  }
  int q1=val[n][W];
  return q1;
}
int main() {
  int n, W;
  std::cin >> W >> n;
  vector<int> w;
  w.push_back(0);
  for (int i = 1; i <= n; i++) {
    std::cin >> w[i];
  }
 sort(w.begin(),w.end());
cout<<optimal(w,W,n);
}

I cant figure out the solution of this problem.Would be really grateful for any help in this matter .TIA.


text:
Q: Jquery Dialog Redirection Issue I am using Jquery dialog box(jquery-ui-1.8.11.custom.min.js). The source for this dialog box is an aspx(src.aspx) page containing a html textbox.  When I press "Enter" in the html textbox, it redirects the page to the dialog page source page i.e. src.aspx (the complete content of the dialog box is displayed in the browser not as dialog box content but as an aspx page). So, tell me a way to stop/block this redirection.
Thanks in advance..

A: do you have a submit button on your aspx page? if so then that is your issue and it happens by default with your form.
See: http://geekswithblogs.net/ranganh/archive/2006/04/12/74951.aspx
or use javascript to prevent the submit on enter.
http://forums.asp.net/p/1355662/2780799.aspx


text:
Q: NoClassDefFoundError when calling function from RESTful web service I'm trying to create a RESTful web service in java that will allow authentication with a Yubikey.
I'm modifying an existing tutorial that I completed while trying to learn about REST.
I'm trying to call the validation function from within the javax.ws.rs.core.Response function but keep getting an error with a package from the imported yubikey jars.
I imported these jars from build path -> libraries --> Add external Jars
Error as follows when I post my form to the RESTful url:
java.lang.NoClassDefFoundError: com/yubico/client/v2/exceptions/YubicoValidationException
package de.vogella.jersey.todo.resources;

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

import com.yubico.client.v2.exceptions.YubicoValidationException;
import com.yubico.client.v2.exceptions.YubicoValidationFailure;
import de.vogella.jersey.todo.resources.Validate;

@Path("/test")
public class Test {

@POST
public Response testCred(@FormParam("username") String username,
          @FormParam("password") String password,
          @FormParam("otp") String otp) throws YubicoValidationException, YubicoValidationFailure {
    int client_id = 11095;
    boolean status;
    status = Validate.validate(otp, client_id);

    return Response.status(200)
        .entity("validation status: : " + status + ", for client " + otp)
        .build();

    }

}

the validate class is as follows:
package de.vogella.jersey.todo.resources;

import com.yubico.client.v2.YubicoClient;
import com.yubico.client.v2.YubicoResponse;
import com.yubico.client.v2.YubicoResponseStatus;
import com.yubico.client.v2.exceptions.YubicoValidationException;
import com.yubico.client.v2.exceptions.YubicoValidationFailure;

public class Validate {

 public static boolean validate(String otp, int client_id) throws YubicoValidationException, YubicoValidationFailure {
        YubicoClient client = YubicoClient.getClient(client_id);
        YubicoResponse response = client.verify(otp);
        if(response != null && response.getStatus() == YubicoResponseStatus.OK) {
          return true;
        }
        return false;
     }

}


text:
Q: how to decrease height of linearlayout which is an image in android I want to decrease height of an image which is used as linearlayout in android.How can i do that? My code is as below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@android:color/transparent">

<ImageView android:id="@+id/icon"
    android:layout_weight="0.15"
    android:layout_width="0dp"
    android:layout_height="48dp"
    android:layout_gravity="center_vertical"
    android:padding="5dp"
    android:scaleType="fitCenter"/>

<LinearLayout android:id="@+id/details"
    android:layout_weight="0.75"
    android:layout_width="0dp"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:gravity="center_vertical">

    <TextView
        android:id="@+id/primary_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:ellipsize="end"
        android:textSize="20dp"/>
</LinearLayout>

<ImageView
   android:id="@+id/status"
   android:layout_width="50dp"
   android:layout_height="62dp"
   android:layout_gravity="center_vertical"
   android:layout_marginRight="7dp"
   android:layout_weight="0.08" />

Decrease the height of imageview doesnot work.how can i do this?

A: change height in this tag >> android:layout_height="100dp" , use less number for height(80dp) or make it wrap_content
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:background="@android:color/transparent">

A: Decrease layout_height or decrease it manually from Graphical layout. If even it does not work then you have to check whether that image's layout is overlapping with others or not. If yes then decrease that layout's size.


text:
Q: emu8086 - assembler not responding on startup I am taking a course in assembly and computer architecture. It is required that we download software called emu8086 - assembler, I downloaded the required software, but when I launch it, it just won't respond. It stays in the not responding state for a few minutes and then I have to terminate through the task manager.
I am using Windows 8.1 (64 bit), but all the other people on the course (we were all given the exact same computers) were able to run the software.
Just to make sure you know I reinstalled the software several times and it did not help.
I know that the emu8086 cannot run along other VMs at the same time, and I do have VMware installed on my computer, could it be the issue?


text:
Q: Issues with extracting data from a list then using them together in separate data (part of online course) Sorry, I'm not quite sure how to describe my issue.
For an online python course I'm following there's an exercise I can't figure out. (raise NotImplementedError() refers to lines I need to input code).
The line of code station_years = 2019 - station_start_years[selected_station] is what I'm stuck on. I'm aiming for the list "station_start_years" to chose its value based on my selected_station value, which is based on station_names.
num = int(input('select a station: ')) was inserted by me so may be wrong.
Thanks for any help, I've read through the exercises but am lost.
Read-only code cell
station_names = ['Harmaja', 'Kaisaniemi', 'Kaivopuisto', 'Kumpula', 'lighthouse', 'Malmi airfield', 'Suomenlinna aaltopoiju', 'Vuosaari harbour']
Read-only code cell
station_start_years = [1989, 1844, 1904, 2005, 2003, 1937, 2016, 2012]
Below we can define the selected station:
 #raise NotImplementedError()
num = int(input('select a station: '))
selected_station = station_names[num]
Next we find the location of the selected station in the list of station names:
Read-only code cell
station_index = station_names.index(selected_station)
Now we can calculate the years the station has been operational:
YOUR CODE HERE
raise NotImplementedError()

station_years = 2019 - station_start_years[selected_station]
Now, we can print the station name and number of years of operation to the screen.
A sample print statement on screen is 'The Helsinki Harmaja station has been operational for 30 years.' The print statements should work for all listed stations only by modifying the selected_station -variable that is defined earlier in this problem.
YOUR CODE HERE
raise NotImplementedError()
 str(station_years)+ " years.

print(print_statement)

A: You find the index of selected_station in station_names but then you use selected_station (which is the name of the station) to index your station_start_years list. You should be using station_index there:
station_index = station_names.index(selected_station)
station_years = 2019 - station_start_years[station_index]

(BTW, it is no longer year 2019…)


text:
Q: string - array ambiguity in PHP I dimly recall, from my first readings of the PHP docs (more than 10 years ago) that the array-like syntax to access characters in arrays ($string[0]) posed some ambiguity or undefined behaviour.
The O'Reilly PHP Pocket Reference (2nd ed) states:

To solve an ambiguity problem between strings and arrays, a
  new syntax has been introduced to dereference individual characters
  from strings:
$string{2}
This syntax is equivalent to $string[2], and is preferable.

I understand that $string[2] might be confusing, but I'm not sure how it could be ambiguous?
Furthermore: I wonder how the new syntax $string{2} removes the ambiguity/confusion, considering that the curly braces  (apparently) also work for "real" arrays.

A: The only ambiguity is that if you're expecting an array, but actually have a string, $var[0] will give you the first byte of the string instead of the first array element. This may lead to a lot of head scratching and wondering why PHP is only giving you the first character instead of the whole array element. This is even more true for non-numeric indexes like $var['foo'], which actually works if $var is a string (yeah, please don't ask). I.e. it may make debugging slightly more difficult if your program is wrong in the first place.
There's no ambiguity for correct programs, since a variable cannot be a string and an array at the same time.

A: Many problems caused by the ambiguity between string offsets and array offsets have been removed with the changes in 5.4, which is after the publish date of your reference.   http://php.net/manual/en/migration54.incompatible.php
For this reason, I'd reccomend [] for string offsets in new code.

A: Well, I have tested some variables with this code:
<pre><?php

dumpling(array("php"));
dumpling(array());
dumpling(0);
dumpling(1);
dumpling(TRUE);
dumpling(FALSE);
dumpling(NULL);
dumpling("php");

function dumpling($var){
    var_dump($var[0]);
    var_dump($var{0});
}

?>

and there didn't seem to be any difference between those two.
The output was :
string(3) "php"
string(3) "php"
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
string(1) "p"
string(1) "p"


text:
Q: Prints "none" when I run it /PYTHON Running this code where I am asking the user if they want the code in reverse order.
Everything runs smoothly, however when the program runs the section Do you want reverse order (y/n), it prints None on the next line for some reason?
Can anybody explain why/how I get this to stop?
def farmList():
    print("Please enter six farming animals: ")
    terms = []
    for counter in range(6):
        term = input("Please enter a farm animal")
        terms.append(term)

    reverseOrder = input("Do you want reverse order (y/n)")
    if reverseOrder == "y":
        print(terms[::-1])
    else:
        print(terms)

    whichTerm = int(input("Choose a number between 1-6, and the program will print that animal: "))

    print(terms[whichTerm-1])

A: If you are calling farmList() properly, then changing input to raw_input should work for python 2.7.
For Python 2.7, raw_input() takes exactly what the user typed and passes it back as a string.
Else for Python 3, your code should work just fine.

A: Your code works fine, at least in Python3 (see this thread for more information : What's the difference between raw_input() and input() in python3.x)
Note that you only show a reversed list, you don't reverse terms, though :
Please enter six farming animals:
Please enter a farm animala
Please enter a farm animalb
Please enter a farm animalc
Please enter a farm animald
Please enter a farm animale
Please enter a farm animalf
Do you want reverse order (y/n)y
['f', 'e', 'd', 'c', 'b', 'a']
Choose a number between 1-6, and the program will print that animal: 1
a

To reverse the list you could write :
if reverseOrder == "y":
    terms = terms[::-1]

So your code would become :
def farmList():
    print("Please enter six farming animals: ")
    terms = []
    for counter in range(6):
        term = input("Please enter a farm animal")
        terms.append(term)

    reverseOrder = input("Do you want reverse order (y/n)")
    if reverseOrder == "y":
        terms = terms[::-1]

    whichTerm = int(input("Choose a number between 1-6, and the program will print that animal: "))

    print(terms[whichTerm-1])

farmList()

For Python2.7, replace every occurence of input() to raw_input().


text:
Q: Python - How to convert a string from binary to integer list? I got a string like:
s = "\0x01\0x02\0x01\0x11"

And I want to get the average number of that string. I tried this:
sum = 0
for d in s:
    sum += int(d)

But it said "invalid literal for int() with base 10:'\x08'" :-(

A: I recommend the struct module.
>>> import struct
>>> s = '\x01\x02\x01\x11'
>>> struct.unpack('=4B', s)
(1, 2, 1, 17)

A: You can use the python int() function, the first argument is the string, the second is the base of the number.
You need to check the base, because what you posted looks like hexadecimal numbers (0x0 usually denotes a HEX number, additionally 02 is not a valid binary number).
For binary (base two):
num = int("0x11", 2); # num will be 3

For hexadecimal (base 16):
num = int("0x0A", 16); # num will be 10

To convert your string ("\0x01\0x02\0x01\0x11"):
numbers = [int(s, base) for s in "\\0x01\\0x02\\0x01\\0x11".split("\\") if len(s)]

If run with base = 16, outputs: numbers = [1, 2, 1, 17]
You can then find the average using:
average = sum(numbers)/len(numbers)

A: The ord() will, when given a string of length one, give you the code point of the character in that string. You should just be able to use this instead of int() in your code, which would look something like this:
sum = 0
for d in s:
    sum += ord(d)

A: You can do it like this:
s = "\0x01\0x02\0x01\0x11"
list = s.split('\0x')
list.remove('')

sum = 0
for d in list:
    sum += int(d)

# 15


text:
Q: :compileKotlin fails in Gradle (mixed Java + Kotlin project) I have a mixed Java/Kotlin project with the following structures:
My Gradle script for building it looks like this:
buildscript {
  ext.kotlin_version = '1.0.4'
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
  }
}

apply plugin: "kotlin"
apply plugin: "application"

mainClassName = "com.mycopany.App"

sourceSets {
  deploy
}

repositories {
  mavenCentral()
}

dependencies {
  compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
  testCompile  'junit:junit:4.11'
  testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
}

test.testClassesDir = project.tasks.compileTestKotlin.destinationDir

task wrapper(type: Wrapper) {
  gradleVersion="2.7"
}

App.kt is a simple program:
package com.mycompany.App

class App {
    fun run() {
        System.out.println("Hello, Kotlin world!")
    }
}

fun main(args : Array<String>) {
    val app = App()
    app.run()
}

When I try to build it using gradle build, I get the following error messages:
16:13:16.768 [DEBUG] [org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter] Finished executing task ':copyMainKotlinClasses'
16:13:16.768 [LIFECYCLE] [class org.gradle.TaskExecutionLogger] :copyMainKotlinClasses FAILED
16:13:16.769 [INFO] [org.gradle.execution.taskgraph.AbstractTaskPlanExecutor] :copyMainKotlinClasses (Thread[main,5,main]) completed. Took 0.042 secs.
16:13:16.770 [DEBUG] [org.gradle.execution.taskgraph.AbstractTaskPlanExecutor] Task worker [Thread[main,5,main]] finished, busy: 0.28 secs, idle: 0.005 secs
16:13:16.827 [LIFECYCLE] [org.gradle.BuildResultLogger]
16:13:16.828 [LIFECYCLE] [org.gradle.BuildResultLogger] BUILD FAILED
16:13:16.829 [LIFECYCLE] [org.gradle.BuildResultLogger]
I get the same error, when I try to build it in Eclipse (also with Gradle).
If I run the same script with the --stacktrace option, I get this:
Caused by: java.lang.NullPointerException
        at org.gradle.util.GFileUtils.mkdirs(GFileUtils.java:265)
        at org.gradle.api.internal.project.taskfactory.OutputFilePropertyAnnotat
ionHandler$2$1.execute(OutputFilePropertyAnnotationHandler.java:73)
        at org.gradle.api.internal.project.taskfactory.OutputFilePropertyAnnotat
ionHandler$2$1.execute(OutputFilePropertyAnnotationHandler.java:68)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(Abstra
ctTask.java:621)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(Abstra
ctTask.java:604)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.ex
ecuteAction(ExecuteActionsTaskExecuter.java:80)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.ex
ecuteActions(ExecuteActionsTaskExecuter.java:61)
        ... 57 more
How can I fix this?


text:
Q: How do I horizontally and vertically center an image on the page, except for when it's too big to fit? I'm trying to implement a basic image viewer using HTML and CSS, where the image remains centered in the page, except for when it's too big to fit. In that case, the user should be able to scroll to see the rest of the image with no margins. If only one dimension is too big to fit, the other dimension remains centered. There is nothing else on the page other than the image.
However, the size of the image needs to be specified by a scaling factor so that I can enlarge or shrink it relative to its original size. This means I can't use an explicit width/height in pixels or size it relative to the size of the page. I've tried adjusting its transform css property, i.e. transform: scale(2.5) but that generally causes the top of the image to be cut off. I've also tried doing this by making the image's display property by set to inline-block and its height property set to auto so that I can set its width to the percentage I want it to be scaled by, but I can't figure out how to keep it centered on page as described in the above paragraph.
How can I accomplish this? So far I've tried around a dozen different ways of centering an element on the page, and none of them result in this exact behavior I'm shooting for. For example, I've used flexboxes to keep the image centered horizontally and vertically, but as soon as it grows too tall to fit, (again) the top of the image gets cut off.

A: You can use flexbox and center with margin to obtain this:

body {
 min-height:100vh;
 margin:0;
 display:flex;
}
body > img {
 margin:auto;
}

And in case you don't want scroll apply max-height/max-width:

body {
 height:100vh;
 margin:0;
 display:flex;
}
body > img {
 margin:auto;
 max-width:100%;
 max-height:100%;
}

A: there are several ways to achieve horizontal and vertical alignment. However, they are usually done separately and in different ways. You can have a look at W3Schools, they do a few tutorials on each:
W3Schools Alignment Tutorial
Also if you are willing to use bootstrap (makes everything much easier, especially centering) you can have a look at the following link:
BootStrap Grid System Tutorial
Below is a quick method on for centering. Credit goes to: This Post with some minor improvements from myself.

.outer {
  display: table;
  position: absolute;
  height: 100%;
  width: 100%;
}

.middle {
  display: table-cell;
  vertical-align: middle;
}

.inner {
  margin-left: auto;
  margin-right: auto;
  width: 400px;
  text-align:center;
  /*whatever width you want*/
}

The Content

Once upon a midnight dreary...


text:
Q: Array search algorithms for largest group of elements based on value I need a search algorithm that can find the largest rectangle of mostly 1's in a matrix of 0s and 1s; specifically, I need it to return the (x,y) coordinate pairs of the top-left and bottom-right of these rectangles.
For example, consider the following matrix:
[1,1,0,0,0,
 1,0,0,0,0,
 0,0,0,0,0,
 0,0,0,1,1,
 0,0,0,1,1]

If I set the threshold to 75% (average value of the rectangle is 0.75), two rectangles (squares, specifically) would be found at the top left and bottom right of the matrix. And the tuple outputs would top left (x,y), bottom right (x,y) for each point.
{rectangle_1: ((0,0),(1,1)),
rectangle_2: ((3,3),(4,4))}

Are there any array/matrix search algorithms that I should consider as a starting point for this task?
If it's of any importance, I'll be using python. So if such an algorithm has a python implementation, that would be greatly appreciated.

A: My take on the problem - I converted the matrix to dictionary with keys as positions (x, y) and values equal to 0 or 1 (surely, this is not the fastest approach - you are surely better with NumPy):
from itertools import count

lst = [
 1,1,0,0,0,
 1,0,0,0,0,
 0,0,0,0,0,
 0,0,0,1,1,
 0,0,0,1,1]

def get_values(d, i1, j1, i2, j2):
    c = 0
    s = 0
    for i in range(i1, i2+1):
        for j in range(j1, j2+1):
            s += d[(i, j)]
            c += 1
    return s / c

def find_squares(lst, m, n, t):
    lst = iter(lst)
    d = {(j, i): next(lst) for i in range(m) for j in range(n)}

    seen_squares = []

    for i1 in range(m):
        for j1 in range(n):
            ii2 = count(i1+1)
            ij2 = count(j1+1)

            i2 = next(ii2)
            j2 = next(ij2)
            current_square = None
            while i2 < m and j2 < n:
                if get_values(d, i1, j1, i2, j2) >= t:
                    current_square = i1, j1, i2, j2
                else:
                    break

                i2 = next(ii2)
                j2 = next(ij2)

            if current_square:
                for x1, y1, x2, y2 in seen_squares:
                    if i1 >= x1 and i2 - 1  <= x2 and j1 >= y1 and j2 - 1 <= y2:
                        break
                else:
                    seen_squares.append(current_square)
                    yield current_square

for i1, j1, i2, j2 in find_squares(lst, 5, 5, 0.75):
    print(i1, j1, i2, j2)

Prints:
0 0 1 1
3 3 4 4

For matrix:
lst = [
 1,1,0,0,0,
 1,0,0,0,0,
 0,0,0,1,1,
 0,0,0,1,1,
 0,0,0,1,1]

The output is:
0 0 1 1
3 2 4 3
3 3 4 4


text:
Q: Simple HTTP request with C++ Before you flag this for redundancy, do know that I have tried a lot of the methods posted around the web (stack overflow included) already and they each couldn't satisfy my needs. Also do note I am quite new to the programming world so excuse me for my misuse of technical terms.
Right now I am writing a C++ program that computes some data from the user's computer (IP address for example), then I send the IP address to a server that's already set up. I do this through an URL. So for example, if the server is at http://stack1234abcdz.com, and the user's IP address is 100.100.100.100 , then I would request
http://stack1234abcdz.com/?ip="100.100.100.100

I have tried libcurl and it works to some extent, but after compiling, I require 5 .dll in the same directory as the .exe in order to run it, which I cannot have due to some portability of my problem.
I have also tried some other traditional socket methods, but they require loads of libraries and SDKs, which are hard to configure and they often overwhelm a newbie like me. What I need to do is very simple (I don't even need the server to send anything back except for maybe success or failure codes), therefore I don't think I should be needing so much to do so little.
I am using Visual Studio 2006 on Windows 7 (64 bit) machine, doing C++. I cannot use newer versions because most of the other code that was given to me is in VS2006 and they do not transfer/convert well to newer versions.
I guess what I'm asking now is what I should do next. Is there a way to make the executable with libcurl to NOT use 5 .dll? I saw somewhere that I have to do some static linking stuff, but they weren't being very specific.
Or are there simpler ways to solve my problem that I overlooked? WinInet? CAtlHttpClientT? Casablanca? I'd prefer not to install and configure complex libraries that I have yet to grasp my mind around, especially not for the size of my problem...
I would appreciate any help/opinion/feedback on this matter, thanks!

A: After lots of trials and errors I solved my own problem.
I used OpenURL() function in the CInternetSession class.
Did a simple open in around 25 lines of code. Ran into some problems while including   afxinet.h, stdafx.h, httpClient.h. That order worked for me, but might be different for other programs.


text:
Q: Disqus API - unable to use 'query' param in 'posts/list' I have created an Application that has the default access set to "Read, Write and Manage forums" however when I hit the API using GET forum=our-forum&query=querystring I'm then returned an error:
Uncaught DisqusAPIError: Must have moderator permission on forum our-forum to use 'query' param

How else do you set moderator permission for an application?

A: For those that are looking for the answer to this - pass the access token along with the request:
GET forum=our-forum&query=querystring&access_token=your-access-token


text:
Q: How to change ionic alert element I'm new in ionic, I try to change alert element scss but it doesn't work.
list.html
<ion-select [(ngModel)]="dept_title" style="color: white; display:none" #sel >
  <ion-option  *ngFor="let data of dept_data" value="{{data.deptid}}">
    {{data.deptid}}
  </ion-option>
</ion-select>

list.ts
selectOpen(sel){
  sel.open();
}

list.scss
page-list {
  ion-option {
    background-color: gray;
  }
}

A: You can't apply css to ion-Option. Instead you have to apply css to interface type you have taken, Here by default they gives <ion-option interface="alert"> </ion-option>.
So you have to apply CSS by  AlertController CSS commands you can follow step given below .
I will prefer ionic official CSS Commands.
1) Go to AlertController doc page of oficial web site of ionic . https://ionicframework.com/docs/api/components/alert/AlertController/
2) At the bottom of the page you can find an option for CSS as 'Material Design'
3) Pick CSS command from there according to your need. and apply it.

*

*In your case you can apply :
$alert-md-background-color : #808080
You can apply it globally by putting it in 'src\theme\variable.scc' file
OR
You can apply it on your particular page by putting it in your "list.scss" page.
Hope it will help you . Thanks


text:
Q: Variable from a property file used in email trigger script in JENKINS I have two jobs: Job_a and Job_b. I want to use a variable in Job_a to decide whether an email should be sent in JOb_b.
The simplified jobs:
In Job_a:
Step 1: Execute Windows batch command:
echo GO=Y > testme.txt

this will create testme.txt with GO=Y in the workspace.
Step 2: Trigger/call builds on other projects:
projects to build: Job_b
Parameters from property files: testme.txt
In Job_b:
Step 1:
echo Go = %GO%

Post-build Actions
Editable Email Notification
triggers:  Script - After Build
trigger script:
build.envVars["GO"]  == 'Y'

Now, run Job_a, no email triggered, while step 1 in Job_b, does print Go = Y
to prove the trigger script itself is correct, I add a String Parameter in Job_a:
Name: GO1
Default Value: Y

and change the trigger script in Job_b to:
build.envVars["GO1"]  == 'Y'

run Job_a, thus JOb_b as well, and email was sent as expected.
it seems that only parameters defined in the upstream job can be used in the email trigger script, parameters in the property file are not available.
I know I could inject the parameter from the property file in the fly with EnvInject Plugin, and/or with System Groovy script, I can add new parameters, but my build environment is tight controlled, there is no System groovy, no new additional plugin can be installed.
My jenkins version is 1.622

A: To share with everyone. I have found what went wrong.
The property file has one line: GO=Y
The parameter 'GO' in the property file created in Job_a IS indeed passed to Job_b.
The groovy test build.envVars["GO"]  == 'Y' does not return 'true', thus no email will be sent.
I print the length of the parameters:
println build.envVars["GO"].length()

println 'Y'.length()

which prints
2
1

Apparently, there is a new line carriage appended when we create the contents of the property file with
echo GO=Y > testme.txt

I have to trim off the new line carriage, so change the trigger script for the editable mail, Script - After build to
build.envVars["GO"].trim() == 'Y'

it works as expected.


text:
Q: JQuery SlideUp, Delay and SlideDown with every AJAX call I want to slide up the header delay and slide it back down. I have the function bind to the form submission but it the slide up and slide happens only the first time. The code is as below.
$(document).ready(function() {
  console.log("ready!");

$('form').on('submit', function() {

        setInterval(function() {
            $('header').slideUp(500, function() {
                 $('header').delay(10000).slideDown(500);
                });
            });

        var url = $('input[name="Value"]').val();
        console.log(url)
        $.ajax({
                type:'POST',
                url:'/first_page',
                data: {'val': url },
                cache:false,
                success: function(results){
                        console.log(results);

                        $("#heading").html("Word Cloud")
                        $("#key1").html("The primary topic of this page is" + " " +results.pt)
                        $("#key2").html(" with the relevancy score of" + " " + results.ptr)
                        $("#key3").html("The secondary topic of this page is" + " " + results.st)
                        $("#key4").html(" with the relevancy score of" + " " + results.str)
            },error:function(error){
                   console.log(error)
                 }
});
});

Can anyone please suggest me why this is happening only once when I refresh the page? Thank you.

A: Since this is asynchronous you'll want to put the slideDown() method in the callback:

$('form').on('submit', function() {
    $('header').slideUp(500);

  var url = $('input[name="Value"]').val();
  console.log(url)
  $.ajax({
    type: 'POST',
    url: '/first_page',
    data: {
      'val': url
    },
    cache: false,
    success: function(results) {
      console.log(results);

      $("#heading").html("Word Cloud")
      $("#key1").html("The primary topic of this page is" + " " + results.pt);
      $("#key2").html(" with the relevancy score of" + " " + results.ptr);
      $("#key3").html("The secondary topic of this page is" + " " + results.st);
      $("#key4").html(" with the relevancy score of" + " " + results.str);
      $('header').delay(10000).slideDown(500);
    },
    error: function(error) {
      console.log(error)
    }
  });

  return false;
});

A: It is because it is an asynchronous method. And you will need to bind it with an event. Only then you would see it happening.


text:
Q: Send info from last INSERT on Database to a php file I have a jQuery function on a panel as part of an ERP, making an INSERT via a PHP file. The INSERT is correctly made, as the database always receives info properly, but I am unable to send that last inserted record back in order to show it on screen on real time.
jQuery function (seems to be working properly)
function showSuggestions (datos) {
$('tbody *').empty();
var resultados= datos;
$('tbody').on('keydown').html(resultados);}

Content on the PHP file making the insert (INSERT works properly):
        $nombreTurno = $_POST['tu_name'];

        $insertar = mysql_query("INSERT INTO turn_conf (tu_id,tu_name,tu_status) VALUES ('','$nombreTurno','1')");
        $lastInsert=mysql_insert_id();
        $select =mysql_query("SELECT * FROM turn_conf WHERE tu_id='$lastInsert'");

        $data="";
                    $name=$select['tu_name'];
                    $turn_id=$select['tu_id'];
                    $data= '

                        '.$name.'

';      echo $data;

What is coming back to the panel is the HTML piece, but with no values on '.$name.' and '.$turn_id.' so the row is added, but empty. There's no console error, and I've checked that $lastInsert contains the correct info: this INSERT's id that has just been done.
EDIT_ I've also tryed by $turn_id=$lastInsert; with no result.

A: i think you've missed this
$result= mysql_fetch_array($select);
print $result['tu_name'];
print $result['tu_id'];


text:
Q: Forwarding to another spring controller that receive parameter from POST action I have a request mapping for a controller let's say it's A, it receives post action and uses its post values as parameter, sometimes the parameters will be very long so that's the reason why it's POST not GET apart from the best practices and security;
RequestMapping(value = "/reports/performance/indicator/{indicatorType}", method = RequestMethod.POST)
    public String generatePerformanceReportsIndicator(ModelMap map,HttpServletResponse response, @PathVariable("indicatorType") Long indicatorType,
                                                      @RequestParam(value = "siteIds", required = false) List<Long> siteIds,
                                                      @RequestParam(value = "timeframeIds", required = false) List<String> timeframeIds,
                                                      @RequestParam(value = "showTarget", required = false) String showTarget,Locale locale) {

And then it turned out that in another spring controller I need to forward the request to the first one.
The problem is how I can add post parameters to the request before forwarding it to the first request mapping? is that healthy to say for example?
new FirstController().generatePerformanceReportsIndicator(....);

Given that:

*

*I don't want the first request mapping to use get instead of post of the mentioned reasons.

*I don't want to write redundant code by creating another method that extract the parameters as attribute from the model map.

A: You should not manually call other controllers! What you can do is redirect to them with RedirectAttributes like:
@RequestMapping(value = "/doctor/doEditPatientDetails", method = RequestMethod.POST)
public String editPatientDetails(Model model, @ModelAttribute(value = "user") @Valid User user,
        BindingResult result, RedirectAttributes attr, Principal principal) {
    if (null != principal) {
        if (result.hasErrors()) {
            attr.addFlashAttribute("org.springframework.validation.BindingResult.user", result);
            attr.addFlashAttribute("user", user);
            attr.addAttribute("id", user.getId());
            return "redirect:/doctor/editPatient/{id}";
        }
    }
    ....
    return "redirect:/doctor/patients";
}

@RequestMapping(value = "/doctor/editPatient/{id}", method = RequestMethod.GET)
public String showEditPatient(Model model, @ModelAttribute("id") String id, Principal principal) {
    if (null != principal) {
        //here you can access the model and do what everything you want with the params.
        if (!model.containsAttribute("user")) {
            model.addAttribute("user", user);
        }
    ....
    }

    return "/doctor/editPatient";
}

Note that, to redirect to a link like "redirect:/doctor/editPatient/{id}" you have to add the id in RedirectAttributes. Also not that there are many ways you can achive the same functionality like HttpServletRequest


text:
Q: Problem with ls inside bash script Basically I am trying to recursively  list sub directories until I hit a directory where there are no more directories to be found.
The problem here, is that when I pass the argument into the function, as it is given, the ls command doesn't work. Without the $var in quotations, ls treats the space separated string as multiple arguments.
Why is this happening and how can I avoid it?
#! /bin/bash
function subdir_check(){
    local var="$*"
    ls -F -b "$var" | grep '/' | sed 's/\///g'
}
directory="$1"
if [[ $(subdir_check $directory) != "" ]]
then
    pick=$(subdir_check $directory | rofi -dmenu -p 'Select Subdirectory')
    directory="${directory}/${pick}"
    while [[ $(subdir_check $directory) != "" ]]
    do
        pick=$(subdir_check $directory | rofi -dmenu -p 'Select Subdirectory')
        directory="${directory}/${pick}"
    done
fi
echo $directory

A: There are two issues here. The first is quoting. You should get into the habit of always quoting your variables. For more on this please see:

*

*Why does my shell script choke on whitespace or other special characters?

*Security implications of forgetting to quote a variable in bash/POSIX shells
However, that's not what's actually breaking your script here. The next problem comes from the fact that you're trying to parse ls. For why that's a bad idea, please see:

*

*https://mywiki.wooledge.org/ParsingLs

*Why *not* parse `ls` (and what to do instead)?
Specifically, the problem here is your use of -b which causes a directory named dir one to be displayed as dir\ one. If you pick that from your menu picker, then you will run subdir_check with dir\ one as an argument. Because that's quoted (var is quoted in the function), you are attempting to run ls on the literal dir\ one, the escaped space is not read as being escaped since you're quoting. However, if you don't quote it, it will be read as two separate arguments. So the whole thing is a bit of a mess.
Here's a working version of your script using your basic approach with minor tweaks:
#! /bin/bash
function subdir_check(){
  ## globs that don't match anything should expand to the empty string
  ## instead of expanding to the glob itself as happens by default
  shopt -s nullglob
  ## save all sub directories in the 'dirs' array
  local dirs=("$@"/*/);
  ## Print each dir on its own line and remove the trailing '/'.
  printf '%s\n' "${dirs[@]}" | sed 's|/$||'
}
## Remove the trailing '/' from the input.
directory=$(sed 's|/$||'<<<"$1")
## Quote all the things!
if [[ $(subdir_check "$directory") != "" ]]
then
    ## You don't need a second variable. Just one: directory. This will now
    ## include the path.
    directory=$(subdir_check "$directory" | rofi -dmenu -p 'Select Subdirectory')
    while [[ $(subdir_check "$directory") != "" ]]
    do
        directory=$(subdir_check "$directory" | rofi -dmenu -p 'Select Subdirectory')
    done
fi
echo "$directory"


text:
Q: Force system with nVidia Optimus to use the real GPU for my application? I want my application to always run using the real gpu on nVidia Optimus laptops.
From "Enabling High Performance Graphics Rendering on Optimus Systems", (http://developer.download.nvidia.com/devzone/devcenter/gamegraphics/files/OptimusRenderingPolicies.pdf):

Global Variable NvOptimusEnablement (new in Driver  Release 302)
  Starting with the Release 302 drivers, application developers can
  direct the Optimus  driver at runtime to use the High Performance
  Graphics to render any application–even  those applications for which
  there is no existing application profile. They can do this by
  exporting a global variable named NvOptimusEnablement. The Optimus
  driver looks for  the existence and value of the export. Only the LSB
  of the DWORD matters at this time. A  value of 0x00000001 indicates
  that rendering should be performed using High  Performance Graphics. A
  value of 0x00000000 indicates that this method should be  ignored.
  Example Usage:

extern "C" {   _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; }

The problem is that I want to do this using Delphi. From what I've read Delphi does not support export of variables even though some hacks exists. I did try a few of them but couldn't make it work.
In the same nvidia document I read that forcing the proper GPU can be accomplished via linking statically to one of a handful listed dlls. But I don't want to link to dlls I'm not using. (Why the opengl.dll is not one of them is beyond me.) A simple exported variable seems much cleaner.

A:
From what I've read Delphi does not support export of variables.

That statement is incorrect. Here's the simplest example that shows how to export a global variable from a Delphi DLL:
library GlobalVarExport;

uses
  Windows;

var
  NvOptimusEnablement: DWORD;

exports
  NvOptimusEnablement;

begin
  NvOptimusEnablement := 1;
end.

I think your problem is that you wrote it like this:
library GlobalVarExport;

uses
  Windows;

var
  NvOptimusEnablement: DWORD=1;

exports
  NvOptimusEnablement;

begin
end.

And that fails to compile with this error:

E2276 Identifier 'NvOptimusEnablement' cannot be exported

I don't understand why the compiler doesn't like the second version. It's probably a bug. But the workaround in the first version is just fine.

A: I'm not a Delphi expert, but AFAIK it is possible to link to static libraries implemented in C from Delphi. So I'd simply create a small stub library, just providing this export, which is statically linked into your Delphi program. This adds the very export you need.


text:
Q: Trying to create a look-up table but one array has an apostrophe in front I'm trying to create a look-up table between two arrays which I've created from a text file.
One is letters, LET = '[AS, DF, EG, ET, AS]'
The other is numbers, NUM = [1,3,1,0,6]
I want to be able to retrieve the number corresponding with the pair of letters.
How can I do this?
I think my problem has something to do with the fact that the LET array is a string as indicated by the " ' ".  Is there any way I can change this and then tuple the two lists?

A: '[AS, DF, EG, ET, AS]' is a string. You need to fix your code so it is a list of strings as imm suggests.
Now you can use zip() with the two lists to make a dictionary
>>> LET = ['AS','DF','EG','ET','AS']
>>> NUM = [1,3,1,0,6]
>>> dict(zip(LET, NUM))
{'DF': 3, 'ET': 0, 'AS': 6, 'EG': 1}

note that there is only one of the values for 'AS' in the dictionary since you can't have duplicate keys


text:
Q: Android Fragment - Detect if view is active/visible Refresh code
   public void viewRefresh(){
        getProgressBar(R.id.spinnerBar).setAlpha(1);  // CRASH HERE. FATAL EXCEPTION: main
java.lang.NullPointerException

On Resume Code
  public void onResume(){
        super.onResume();
        viewRefresh();

   API.getInstance().bidOnAuction(auctionID, bid, new JsonHttpResponseHandler(){

                    @Override  // this code is calls refresh after 3 or so seconds.
                    public void onSuccess(JSONObject results) {
                        // BID Successfully
                        Log.i("BID ", "SUCCESS");
                        viewRefresh();

I have an android app API 19. I have some async code that cools a redraw.
What I have found that if I load the fragment, then before the callback has occurred, I pop the fragment. The view is gone but the code keeps executing. And therefore. I cannot get access to my Progressbar.
How do detect if my fragment view is still active? (without complex fragment tagging logic?)

A: The Fragment class has methods for that checking, such as isAdded(), isDetached(), etc.
Fragment.isAdded() probably will work for you.


text:
Q: ag-grid upgrade to v23.x : issue with typing files I have been using ag-grid 6x version for a while for an angularJS app. Now, I'm trying to upgrade ag-grid to latest version 23.x . I used bower to install new the version and I'm trying to use the definition files but few 'd.ts' files are not compiling.  I need some help to successfully finish this upgrade.
Here is the error:
 bower_components/ag-grid-community/dist/lib/filter/provided/providedFilter.d.ts(50,5): error TS2416: Property 'setModel' in type 'ProvidedFilter' is not assignable to the same property in base type 'IFilterComp'.
      Type '(model: ProvidedFilterModel) => Promise<void>' is not assignable to type '(model: any) => void | Promise<void>'.
        Type 'Promise<void>' is not assignable to type 'void | Promise<void>'.
          Type 'Promise<void>' is missing the following properties from type 'Promise<void>': listOfWaiters, firstOneOnly, map
    bower_components/ag-grid-community/dist/lib/filter/provided/simpleFilter.d.ts(83,15): error TS2416: Property 'setModelIntoUi' in type 'SimpleFilter<M>' is not assignable to the same property in base type 'ProvidedFilter'.
      Type '(model: ISimpleFilterModel | ICombinedSimpleModel<M>) => Promise<void>' is not assignable to type '(model: ProvidedFilterModel) => Promise<void>'.
        Property 'waiters' is missing in type 'ag.grid.Promise<void>' but required in type 'import("D:/svn/Trunk/MAP/WebDev/bower_components/ag-grid-community/dist/lib/utils/promise").Promise<void>'.
    bower_components/ag-grid-community/dist/lib/filter/provided/simpleFilter.d.ts(91,15): error TS2416: Property 'resetUiToDefaults' in type 'SimpleFilter<M>' is not assignable to the same property in base type 'ProvidedFilter'.
      Type '(silent?: boolean) => ag.grid.Promise<void>' is not assignable to type '(silent?: boolean) => import("D:/svn/Trunk/MAP/WebDev/bower_components/ag-grid-community/dist/lib/utils/promise").Promise<void>'.
        Type 'ag.grid.Promise<void>' is not assignable to type 'import("D:/svn/Trunk/MAP/WebDev/bower_components/ag-grid-community/dist/lib/utils/promise").Promise<void>'.
    bower_components/ag-grid-community/dist/lib/headerRendering/headerRootComp.d.ts(34,28): error TS2583: Cannot find name 'Map'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.

Typescript version: 3.9.2
ag-grid-community: 23.2.1
Angular 1.5.6 (i think angular version is not the problem here)


text:
Q: Custom UICollectionViewCell not loading from cache I have a custom UICollectionViewCell defined as follows:
class MomentsCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!}

And my delegate method looks as such:
    override func collectionView(_ collectionView: UICollectionView,
                             cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
                                                  for: indexPath) as! MomentsCell
    let imageURL = imageURLS[indexPath.row]
    self.updateImageForCell(cell: cell,
                            inCollectionView: collectionView,
                            withImageURL: imageURL,
                            atIndexPath: indexPath)
    return cell

The method "updateImageForCell" looks as follows:
    func updateImageForCell(cell: MomentsCell,
                        inCollectionView collectionView: UICollectionView,
                        withImageURL: String,
                        atIndexPath indexPath: IndexPath) {
    /*if let url = URL(string: withImageURL) {
        cell.imageView.setImageWith(url, placeholderImage: UIImage(named: "placeholder"))
    }*/
     cell.imageView.image = UIImage(named: "placeholder")
     ImageManager.shared.downloadImageFromURL(withImageURL) {
        (success, image) -> Void in
        if success && image != nil {
            // checks that the view did not move before setting the image to the cell!
            if collectionView.cellForItem(at: indexPath) == cell {
                cell.imageView.image = image
            }
        }
     }
}

The ImageManager is a singleton that contains a cache of a set number of images. If the image URL is in the cache, it returns the cached image. If not, it initiates a URLSession to download the image from Firebase.
The images do show up when the view is first loaded, which indicates to me that everything is working more or less correctly at this point. However, when I scroll, random images are loaded, some end up not being loaded, and eventually all of the cells become blank and do not load no matter what, even though everything is saved in the cache.
It's a doozy, but here is my ImageManager class:
class ImageManager: NSObject {
static var shared: ImageManager { return _singletonInstance }
var imageCache = [String : UIImage]()

// checks the local variable for url string to see if the UIImage was already downloaded
func cachedImageForURL(_ url: String) -> UIImage? {
    return imageCache[url]
}

// saves a downloaded UIImage with corresponding URL String
func cacheImage(_ image: UIImage, forURL url: String) {
    // First check to see how many images are already saved in the cache
    // If there are more images than the max, we have to clear old images
    if imageCache.count > kMaxCacheImageSize {
        imageCache.remove(at: imageCache.startIndex)
    }
    // Adds the new image to the END of the local image Cache array
    imageCache[url] = image
}

func downloadImageFromURL(_ urlString: String,
                          completion: ((_ success: Bool,_ image: UIImage?) -> Void)?) {

    // First, checks for cachedImage
    if let cachedImage = cachedImageForURL(urlString) {
         completion?(true, cachedImage)
    } else {
        guard let url = URL(string: urlString) else {
            completion?(false,nil)
            return
        }
        print("downloadImageFromURL")

        let task = URLSession.shared.downloadTask(with: url,
            completionHandler: { (url, response, error) in

                print("downloadImageFromURL complete")

                if error != nil {
                    print("Error \(error!.localizedDescription)")
                } else {
                    if let url = URL(string: urlString),
                        let data = try? Data(contentsOf: url) {
                        if let image = UIImage(data: data) {
                            self.cacheImage(image, forURL: url.absoluteString)
                            DispatchQueue.main.async(execute: { completion?(true, image) })
                        }
                    }
                }
        })
        task.resume()
    }
}

func prefetchItem(url urlString: String) {
    guard let url = URL(string: urlString) else {
        return
    }

    let task = URLSession.shared.downloadTask(with: url,
            completionHandler: { (url, response, error) in
                if error != nil {
                    print("Error \(error!.localizedDescription)")
                } else {
                    if let url = URL(string: urlString),
                    let data = try? Data(contentsOf: url) {
                    if let image = UIImage(data: data) {
                    self.cacheImage(image, forURL: url.absoluteString)
                }
            }
        }
        })
        task.resume()
    }

}
Any help would be appreciated. If I missed any important information, please let me know.

A: There are multiple issues at play here, but I believe only #1 is causing your problem of images not showing at all.

*

*The line when you check that the cell is the same before setting the image: collectionView.cellForItem(at: indexPath) == cell. cellForItem is actually returning nil as it is offscreen. It works when it downloads the image since there is time to bring it on screen, but when pulling the image out of the cache your completionHandler is called immediately, so the cell has not been returned back to the collectionView yet!
There are multiple solutions to this, but perhaps the simplest is adding a wasCached flag returned to your completionHandler (see code at the end of this answer).

*You are actually downloading each image twice: First, using URLSession.shared.downloadTask, then again inside the completionHandler when you fetch the data from the download task's url. The URL you are passing to try? Data(contentsOf: url) is the image URL from the server, not the file URL returned inside the completionHandler.

*From Apple's documentation of downloadTask(with:completionHandler:) the URL passed into the completionHandler block you are reading from:

The location of a temporary file where the server's response is stored. You must move this file or open it for reading before your completion handler returns. Otherwise, the file is deleted, and the data is lost.

If you do not need disk caching, then to fix #2 and #3, switch to using dataTask(with:completionHandler:) function instead which provides you with the image data already in memory and you can construct the image from that.
func downloadImageFromURL(
    _ urlString: String,
    completion: ((_ success: Bool,_ image: UIImage?, _ wasCached: Bool) -> Void)?) {

    // First, checks for cachedImage
    if let cachedImage = cachedImageForURL(urlString) {
        print("Found cached image for URL \(urlString)")
        completion?(true, cachedImage, true)
    } else {
        guard let url = URL(string: urlString) else {
            completion?(false,nil, false)
            return
        }
        print("downloadImageFromURL \(urlString)")

        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            print("downloadImageFromURL complete \(urlString)")
            if let error = error {
                print("Error \(urlString) \(error.localizedDescription)")
            } else if let data = data, let image = UIImage(data: data) {
                self.cacheImage(image, forURL: url.absoluteString)
                DispatchQueue.main.async { completion?(true, image, false) }
            }
        }
        task.resume()
    }
}

And its usage:
ImageManager.shared.downloadImageFromURL(withImageURL) { success, image, wasCached in
    if success && image != nil {
        // checks that the view did not move before setting the image to the cell!
        if wasCached || collectionView.cellForItem(at: indexPath) == cell {
            cell.imageView.image = image
        }
    }
}