text:
Q: Invalid Write with strcpy I have been programming for a while but I am new to C. I have this linked list implementation in ansi C that I need to test. I have narrowed the problem down to an issue with an invalid write. I ran the code through Valgrind and received the following output:
==18131== Invalid write of size 1
==18131==    at 0x4C2C0CC: __GI_strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64 linux.so)
==18131==    by 0x40089B: main (in /home/btm7984/hw3/TestList)
==18131==  Address 0x51f1388 is 0 bytes after a block of size 8 alloc'd
==18131==    at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18131==    by 0x400880: main (in /home/btm7984/hw3/TestList)
==18131==
==18131== Invalid write of size 1
==18131==    at 0x4C2C0DF: __GI_strcpy (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18131==    by 0x40089B: main (in /home/btm7984/hw3/TestList)
==18131==  Address 0x51f138e is 6 bytes after a block of size 8 alloc'd
==18131==    at 0x4C2B6CD: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18131==    by 0x400880: main (in /home/btm7984/hw3/TestList)
==18131==
--18131-- VALGRIND INTERNAL ERROR: Valgrind received a signal 11 (SIGSEGV) - exiting
--18131-- si_code=1;  Faulting address: 0x6D4FCAA;  sp: 0x402bdae00

All that I can ascertain from this is that I am allocating something wrong. I think it has to be with my strcpy line. I really don't know how to approach this question. What follows is my use of the LinkedLists interface. InitLinkedLists, AddToBackOfList, and DestroyList are all defined in that interface.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "LinkedLists.h"

int main(int argc, char *argv[]) {

  FILE *fp;
  char tmpString[100];
  LinkedLists *ListPtr = malloc(sizeof(LinkedLists));
  ElementStructs *DataPtr;
  LinkedListNodes* curr = malloc(sizeof(LinkedListNodes));
  int counter = 0;
  int Done = 0;

  InitLinkedList(ListPtr);
  fp = fopen(argv[1], "r");
  if (!fp){
    fprintf(stderr,"%s Cannot open file %s\n", argv[0], argv[1]);
    exit(1);
  }
  do{
    fscanf(fp,"%s",tmpString);
    if (!feof(fp)) {
      DataPtr = malloc(sizeof(DataPtr));
      printf("%d   %d : %d\n",counter,(int)strlen(DataPtr->str),(int)strlen(tmpString));
      strcpy(DataPtr->str,tmpString);
      DataPtr->index=counter;
      AddToBackOfLinkedList(ListPtr, DataPtr);
      counter++;
      Done = 1;
    } else {
      Done = 0;
    }
  }while (Done);

In conclusion, I think strcpy is causing an invalid write and I don't know why.
Any help would be greatly appreciated. Thanks in advance.
EDIT: ElementStructs is defined as follows:
typedef struct ElementStructs
   {
   /* Application Specific Definitions */
   int index;
   char str[100];
  } ElementStructs;

A: The problem resides in this statement:
DataPtr = malloc(sizeof(DataPtr));

You allocate only enough memory to hold a pointer and not a full struct.
You should allocate using:
DatapPtr = malloc(sizeof(ElementStructs));

or, as described in the comments (WhozCraig):
DatapPtr = malloc(sizeof(*DataPtr));


text:
Q: NPM doesn't install module dependencies This is my package.json for the module that I'm including in the parent project:
{
  "version": "0.0.1",
  "name": "module-name",
  "dependencies": {
    "express": "3.3.4",
    "grunt": "0.4.1",
    "grunt-contrib-compass": "0.4.0",
    "grunt-contrib-copy": "0.4.1",
    "grunt-contrib-cssmin": "0.4.1",
    "grunt-contrib-jshint": "0.6.3",
    "grunt-contrib-requirejs": "0.4.1",
    "grunt-contrib-uglify": "0.2.2",
    "grunt-contrib-watch": "0.5.1",
    "grunt-express-server": "0.4.1",
    "grunt-karma": "0.4.5",
    "grunt-regex-replace": "0.2.5",
    "request": "2.25.0"
  },
  "scripts": {
    "postinstall": "grunt install"
  }
}

One thing to note is that this module is contained in a private repo and I include it in the parent package.json like: "module-name": "git+ssh://git@myserver:user/module-name.git"

A: I suspect you're facing the issue where your package.json file is not in the same directory as your Gruntfile.js. When you run your grunt xxx commands, you get error an message like:
Local Npm module "xxx" not found. Is it installed?

For now, the solution is:

*

*Create package.json in the same directory as Gruntfile.js

*Define the modules required by your grunt project

*Execute npm install to load them locally

*Now the required grunt command should work.

IMHO, it is sad that we cannot have grunt resolve modules loaded from a parent npm module (i.e. package.json in a parent directory within the same project). The discussion here seems to indicate that it was done to avoid loading "global" modules but I think what we want is loading from "my project" modules instead.

A: I am using windows machine.

*

*I deleted node_modules folder.

*Somehow, package.lock.json file is getting created. I deleted that file.

*Then npm install.

*Clean build.

*Run.

A: Worth to mention to make sure your dependencies should be in the dependencies part of your package.json (as opposed to devDependencies).
My issue was basically the same as OP:

*

*installing a private repo (Let's call it repo1) via "module-name": "git+ssh://git@myserver:user/my-repo-name.git" in other repo(Let's call it repo2),

*in repo2's node_modules, one package dependency from repo1 wasn't there.

*My silly mistake!.. repo1 was listing that dependency in devDependencies instead of dependencies

*Move the dependency in my repo1's package.json from devDependencies  to dependencies

*In my repo2, I removed my node_modules and package-lock.json, did npm install, an voilà!... dependency was there!

A: You might need to install the grunt-cli, try this before doing a npm install:
sudo npm install -g grunt-cli

That fixes the grunt does not exit for me, you'll also need a valid grunt file.
Source: https://stackoverflow.com/a/16456467/241294

A: Just in case anyone is suffering from this predicament and happens to make the same asanine mistake that I did, here is what it was in my case.  After banging my head against the wall for an hour, I realized that I had my json incorrectly nested, and the key "dependencies" was inside of the key "repository".
Needless to say, no errors were evident, and no modules were installed.

A: Another way to work this around is to add this into your module package.json scripts section
"preinstall": "npm install {Packages You depend on}"

what this will does is, it will install all packages needed by the module and you won't get that error.

A: happens with old node version. use latest version of node like this:
$ nvm use 8.0
$ rm -rf node_modules
$ npm install
$ npm i somemodule
edit: also make sure you save.
eg: npm install yourmoduleName --save

A: I was receiving this error when I installed a clean Node dev environment on windows.
To fix this, I went into my new project directory (that I just scaffolded with yo angular) and typed in two commands:
npm install -g grunt --save-dev
That will install the local grunt dependencies to your project. Next:
npm install
That will ensure all your (new) project dependencies are installed.
Tada!

A: It looks like you hit a bug that has existed for quite a while and doesn't have solution yet. There are several open issues for this case in the npm repository:

*

*npm install should recursively check/install dependencies https://github.com/npm/npm/issues/1341 (closed)

*local private module dependencies https://github.com/npm/npm/issues/2442 (closed)

In the first one people list several workarounds that you may try.
An alternative solution may be (a little hackish) to explicitly list the dependencies as first level dependents. This requires you to maintain the list but practically it has to be done very infrequently.

A: if you inherited this code, it could be that the dependencies and versions were locked and you have a ./npm-shrinkwrap.json file.
if your dependency is not listed in that file, it will never get installed with the npm install command.
you will need to manually install the packages and then run npm shrinkwrap to update the shrinkwrap file.

A: Also check that your package name is correctly accepted:
WRONG:
{
    "name": "My Awesome Package"
}

CORRECT:
{
    "name": "my-awesome-package-name"
}

A: I had very similar issue, removing entire node_modules folder and re-installing worked for me. Learned this trick from the IT Crowd show!
rm -rf node_modules
npm install

A: In my case it helped to remove node_modules and package-lock.json.
After that just reinstall everything with npm install.

A: OP may be true for an older version of node. However, I faced the same with node 4.4.1 as well.
It very well may be linked to the node version you are using. Try to upgrade to a latest version. Certain dependencies don't load transitively if they are incompatible with node version.
I found this by running npm update.
After upgrading to latest version (4.4 -> 5.9); this got fixed.

A: I faced the issue when I was trying to create the first Angular application.
ng new angular-tour-of-heroes
cd angular-tour-of-heroes
ng serve --open

So every time I tried to compile the app I get the dependency error. Finally was able to resolve the issue after running
npm install -g @angular/cli@latest

After that ng serve command works without any error when I replicate the above steps for new project.

A: What I've tried and Helped:
rimraf node_modules
npm cache clean --force
npm i

The most important: Close the VS Code and re-open it. Only after I did that all the errors were gone.
Good luck!

A: I had the same problem. But on the same machine one project had good package.json, where all my dependencies are successfully installed. And in another project my package.json dependencies were not installed no matter what i do.
I just copied the package.json and pasted into that another project. And it worked!
The difference i have found was only empty line at the start of file. Dont know or it influences anything, maybe some other problem. But the problem was only the package.json file.

A: I think that I also faced this problem, and the best solution I found was to look at my console and figure out the error that was being thrown. So, I read it carefully and found that the problem was that I didn't specify my repo, description, and valid name in my package.json. I added those pieces of information and everything was okay.

A: I've been hours trying to debug this issue and finally it was that I had the NODE_ENV= env variable set to "production".
From https://riptutorial.com/node-js/example/10101/setting-node-env--production-
"When the NODE_ENV environment variable is set to 'production' all devDependencies in your package.json file will be completely ignored when running npm install."

A: fix
As @Monkpit said : Deleting package-lock.json and re-running npm install solved the issue for me. But don't forget to push the new package-lock.json*.
explanation
Don't download the inherit dependencies would be an awful issue and Nodejs don't have it.
The error is caused by an older package-lock.json caused for the use of libraries not hosted in the official repository : https://www.npmjs.com/  Example:
"dependencies": {
    "express": "4.17.1",
    "xyz": "git+https://github.com/bar/xyz.git"
}

If the package xyz is hosted correctly on www.npmjs.com and is added to package.json, the npm install will download correctly the xyz dependencies. If the package is special or is under development, you could have this problem.
This file package-lock.json is very important. If you delete it (as several answers advice) you could have another severe issues: Deleting `package-lock.json` to Resolve Conflicts quickly
Finally, if you have this kind of errors in which foo dependencies are not downloaded:
{
  "name": "acme",
  "version": "1.0.0",
  "dependencies": {
    "foo": "git+https://github.com/bar/foo.git"
  }
}

*

*validate that in acme/node_modules don't exist the foo dependencies

*Check the package.json of foo if the dependencies are coorectly added

*delete the node_modules of your local project (acme in the example)

*delete package-lock.json

*run npm install

*validate that in acme/node_modules exist the foo dependencies

*push this renewed file package-lock.json to your git repository

A: There might be a version conflict. I had the same issue, on npm 8.
At first, I tried to manually install the missing dependency using npm instasll <module> but npm complained and gave error that there is a version conflict between dependencies of two packages. I found out that two of the packages needed different versions of the dependency. I resolved the conflict, removed node_modules and after a npm install the missing dependency was installed as expected without manually installing it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# - Use form instead of messagebox I am working on an application for work and I need a customized messagebox to appear. I have created a simple form called Alert.cs that I have styled the way I want and added one button with a click method of this.Close(). now I want it to behave exactly like a standard messagebox.show(). I have the form showing but when I use the standard messagebox.show("text of alert") it waits to continue operation until the user click 'OK', this is what I want the form to do.

A: You will need to implement a static method for your Alert class if you want the exact MessageBox-like behaviour.
public static DialogResult Show(string text)
{
    Alert form = new Alert(text);
    return form.ShowDialog();
}

Now you can use the form by calling:
Alert.Show("my message");

A: You can use a modal windows form. Something like
Form frm = new Form();
frm.ShowDialog(this);

See Form.ShowDialog Method

Shows the form as a modal dialog box
  with the currently active window set
  as its owner.

Displaying Modal and Modeless Windows Forms

A: Use Form.ShowDialog();. This allows the form to act the same way as a MessageBox in the sense that it retains focus until closed.

A: You don't write how you currently display your Alert Form, but calling
alert.ShowDialog();

instead of alert.Show() should do the trick.
The ShowDialog that takes an owner is an even better alternative:
alert.ShowDialog(owner);


text:
Q: Regex - Optional Group With Replacement I need to capture up to four digits, as follows, in a named group:
    123       -> 123
    2357      -> 2357
    123 (11X) -> 11
    235 (7Y)  -> 7

As you can see, the bracketed number and letter is optional.
Though there appear to be similar questions on the forum, my limited knowledge prevents me from adapting their solutions.
My initial attempt is, as follows:
(?<ABC>\d{0,4})?|\((?<DEF>\d{0,4})(?<GHI>[A-Za-z])\)

Debuggex Demo
seems to capture the groups I need, but how do I automatically choose the correct group in a replacement context - ABC or DEF depending on the input?
Do I need a 'branch reset' so that I can give groups 'ABC' and 'DEF' the same name and, if so, how do I implement it?
Please advise?

A: After much trial and error, the following pattern works for .NET [ Solution ]:
    (?<ABC>\d{0,4}) ?\((?<ABC>\d{0,4})(?<GHI>[A-Za-z])?\)


text:
Q: Process return (int), to another program Good afternoon,
I have a process (console), where the main it will return an integer.
I will start this process from another in this way:
Process processo = new Process();

processo.StartInfo.FileName = caminhoExecutavel;
processo.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
processo.Start();

How can I test this return (integer) the first process?
explanation:
I have a program (1) that will call an executable (2) as above.
Need to test this program (1) return (int) this executable (2). because the main it returns an integer.
I'm not able to find how / where can I get this return.
NOTE: Even by code within the program (1).

A: If you wait for the process to exit, you can read the ExitCode property. See documentation.


text:
Q: Maven configuration with Spring Boot & multi modules - run application in Intellij I'm currently working on a REST API with Spring Boot.
I'm new to Maven and have just started coding with IDEA (don't know well this IDE yet), and I have a problem...
Here is my project structure :

*

*parent

*

*pom.xml

*main module

*

*controller

*domain

*App.java (Spring Boot main class)

*pom.xml

*sub module (need main module as dependency)

*

*controllers

*domain

*pom.xml

So when I run the project in Intellij, it starts, and I can access all URLs defined in the main module controller. But not the ones in the sub module controller... It looks like only the main module was loaded.
Here is my parent pom.xml :
<project>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.1.RELEASE</version>
</parent>

<modelVersion>4.0.0</modelVersion>

<name>Test :: Test :: Parent POM</name>

<groupId>test.test.test</groupId>
<artifactId>project-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>

<properties>
    <!-- Specify Java Compiler Version -->
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>

    <!-- Spring -->
    <spring-boot.version>1.2.1.RELEASE</spring-boot.version>

    <!-- Sonar -->
    <sonar-maven-plugin.version>2.5</sonar-maven-plugin.version>
    <sonar.language>java</sonar.language>
    <sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin>
    <sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
    <sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>

    <!-- Plugin -->
    <maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version>
    <jacoco-maven-plugin.version>0.7.3.201502191951</jacoco-maven-plugin.version>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

<modules>
    <module>submodule</module>
    <module>main</module>
</modules>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven-surefire-plugin.version}</version>
                <configuration>
                    <redirectTestOutputToFile>true</redirectTestOutputToFile>
                    <includes>
                        <include>**/*Test.java</include>
                        <include>**/*IT.java</include>
                        <include>**/*Story.java</include>
                    </includes>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>

    <plugins>
        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>${jacoco-maven-plugin.version}</version>
            <configuration>
                <destFile>${project.basedir}/../target/jacoco.exec</destFile>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>prepare-agent</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>sonar-maven-plugin</artifactId>
            <version>${sonar-maven-plugin.version}</version>
        </plugin>

    </plugins>
</build>

</project>

Here my main module pom.xml :
<project>
<parent>
    <artifactId>project-parent</artifactId>
    <groupId>test.test.test</groupId>
    <version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>main</artifactId>

<name>Test :: Test :: Main</name>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <commons-lang3.version>3.3.2</commons-lang3.version>
    <commons-codec.version>1.10</commons-codec.version>
    <jsr305.version>3.0.0</jsr305.version>

    <!-- Testing dependencies -->
    <http-commons.version>4.3.6</http-commons.version>
    <jbehave.version>3.9.5</jbehave.version>
    <assertj.version>1.7.1</assertj.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <dependency>
        <groupId>com.google.code.findbugs</groupId>
        <artifactId>jsr305</artifactId>
        <version>${jsr305.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>${commons-lang3.version}</version>
    </dependency>

    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>${commons-codec.version}</version>
    </dependency>

    <!-- Test dependencies -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>
    <dependency>
        <groupId>postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.1-901-1.jdbc4</version>
    </dependency>

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>${http-commons.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>fluent-hc</artifactId>
        <version>${http-commons.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-commons</artifactId>
    </dependency>
    <dependency>
        <groupId>org.jbehave</groupId>
        <artifactId>jbehave-spring</artifactId>
        <version>${jbehave.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.assertj</groupId>
        <artifactId>assertj-core</artifactId>
        <version>${assertj.version}</version>
    </dependency>

</dependencies>

<!-- Package as an executable jar -->
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

</project>

And here the sub module pom.xml :
<project>
<parent>
    <artifactId>project-parent</artifactId>
    <groupId>test.test.test</groupId>
    <version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>submodule</artifactId>

<name>Test :: Test :: Submodule</name>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <commons-lang3.version>3.3.2</commons-lang3.version>
    <commons-codec.version>1.10</commons-codec.version>
    <jsr305.version>3.0.0</jsr305.version>

    <!-- Testing dependencies -->
    <http-commons.version>4.3.6</http-commons.version>
    <jbehave.version>3.9.5</jbehave.version>
    <assertj.version>1.7.1</assertj.version>
</properties>

<dependencies>
    <dependency>
        <groupId>test.test.test</groupId>
        <artifactId>main</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
</dependencies>
</project>

I think that's correct, but not sure...
I run the project in Intellij with Maven with config :

*

*working directory is root (not sub-module)

*command line mvn spring-boot:run -Drun.arguments=--spring.profiles.active=dev -e -pl main

*property start-class with parent.main.App

Need your help to configure all that stuff to run Spring Boot with all sub-modules loaded in the IDE for dev purpose... because I readlly don't know what is wrong in my config !
Thx !

A: You need to tell SpringBoot where to look for your controllers. Per default that only happens in sub-packages of your @SpringBootApplication class (which will probably not include your sub module).
In order to change that you can use @ComponentScan("path.to.package") to change the default package.
Additionally, you can use @EntityScan to do the same for @Entity classes that might be in your sub-module.

A: Your project structured as:

*

*parent

*

*pom.xml

*main module

*

*controller

*domain

*App.java (Spring Boot main class)

*pom.xml (add sub moudle to main module as dependency)

*sub module

*

*controllers

*domain

*pom.xm

if your App.java in a package: com.xxxx.pro,then set the sub module's package is com.xxx.pro,such as your sub module's controller is TestController.java, and the code is:
package com.xx.pro.web;
@RestController
public class TestController{

}

so, this sub moudle's TestController will be sanned by App.java.Try it on, good luck.

A: also note that in case of JPA Entities and repositories are not in sub packages of Application.java's package then  @Entityscan and @EnableJpaRepositories MUST be declared in the Application class, e.g:
@Configuration
@ComponentScan(basePackages="com.my.pack")
@EnableAutoConfiguration
@EnableJpaRepositories(basePackages="com.my.pack")
@EntityScan(basePackages="com.my.pack")
public class Application{

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}


text:
Q: How to make GDB break at each system or library function call? I want to do that without specifying the name or address of all the system or library functions.
I would basically want to use gdb as strace or ltrace but with the possibility to have a look at the stack or memory addresses in real time.
Thanks!

A: Newer versions of gdb support "catch syscall", which should do what you want


text:
Q: JavaFX - How to use an executor to run tasks one at a time? I'm trying to create a Javafx application that takes screenshots from a URL. Where I'm running into issues is with threading. In my main method, I'm trying to run the two screenshots but it's getting stuck after loading the first page. I've tried to wrap the monitorPageStatus() (since it calls the actual saveToPng() function) method in a task that is submitted to the executor (code below). How can I properly submit the task to the executor so both screenshots are taken?
public class InsightScreenshot {
   {
         // Clever way to init JavaFX once
         JFXPanel fxPanel = new JFXPanel();
   }
   private Browser browser;
   public Stage stage;
   private Timer timer = new java.util.Timer();

   private ExecutorService exec = Executors.newSingleThreadExecutor(r -> {
    Thread t = new Thread(r);
    t.setDaemon(true); // allows app to exit if tasks are running
    return t ;
});

   @SuppressWarnings("restriction")
   /**
   *
    * @param url
   * @param imageName add png extension
   */
   public void showWindow(String url, String imagePath) {
         // JavaFX stuff needs to be done on JavaFX thread
         Platform.runLater(new Runnable() {
                private Stage window;

                @SuppressWarnings("restriction")
                @Override
                public void run() {
                      Stage window = new Stage();
                      window.setTitle(url);

                      browser = new Browser(url);
                      monitorPageStatus(imagePath, window);

                      VBox layout = new VBox();
                      layout.getChildren().addAll(browser);
                      Scene scene = new Scene(layout);
                      window.setScene(scene);
                      //window.setOnCloseRequest(we -> System.exit(0));
                      window.show();
                }
         });
   }

   private void monitorPageStatus(String imageName, Stage window) {

            timer.schedule(new TimerTask() {
        @SuppressWarnings("restriction")
        public void run() {
            Platform.runLater(() -> {

                if (browser.isPageLoaded()) {

                    System.out.println("Page now loaded, taking screenshot...");
                    saveAsPng(imageName);
                    window.close();
                    cancel();
                } else
                    System.out.println("Loading page...");

            });
        }
    }, 1000, 1000);

   }

   private void saveAsPng(String imageName) {
         WritableImage image = browser.snapshot(new SnapshotParameters(), null);
         //TODO change file path?
         File file = new File(imageName);
         try {
                ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file);
                System.out.println("Screenshot saved as " + imageName);
         } catch (IOException e) {
                e.printStackTrace();
         }
   }

   public static void main(String[] args) {

         InsightScreenshot pic = new InsightScreenshot();
         pic.showWindow("ttps://www.google.com", "/images/google.png");

         InsightScreenshot pic2 = new InsightScreenshot();
         pic2.showWindow("https://www.facebook.com", "/images/fb.png");

   }
}


text:
Q: Is LINQ-to-SQL + SQLite.NET + Stored Procedures + VISUAL STUDIO 2008 possible? So I want to retrieve data using stored procedures. Preferably via Linq2SQL.
So I can do something like this (example):
var productHistory = dbname.StoredProcedureMethod(value);

foreach(var product in productHistory)
{
    //stuff
}

This is something I'd like to be able to do in Visual Studio 2008 in .Net 3.5.
It is possible with Visual studio 2008 + .Net 3.5 + SQL Server 2008.
But firstly, I don't like SQL Server 2008 and secondly, I need the database to be absolutely portable.
I've always liked SQLite.net, but it is not a direct requirement - as long as the database solution is portable.
I haven't been able to set anything up but Visual studio 2008 + SQLite.Net.
So yeah, I am asking for your help :)

A: Linq to SQL works only with SQL Server, not with other DBMS. As an alternative, you could :

*

*use SQL Server Compact Edition : it is portable, and I think it's compatible with Linq to SQL (could anyone confirm ?)

*use Entity Framework rather than Linq to SQL. A few months ago, Microsoft announced they would stop support for Linq to SQL, EF is now the "official" Microsoft ORM. It is extensible and can support any DBMS if an adequate provider is available. And the SQLite.NET provider supports Entity Framework, I've been using it successfully for some time now.

Regarding stored procedures, if you really need them you can forget SQLite, because it doesn't support them.

A: You are likely to run into a non-movable roadblock: SQLite does not support stored procedures.


text:
Q: How to solve this IMO competition problem? Let $n>2$ be an integer. Let $f$ be a real-value function on a plane such that for every regular n-gon with vertices $A_1,A_2,...,A_n$, $f(A_1)+f(A_2)+...+f(A_n)=0$. Prove that $f$ is zero function.
Putnam 2009 asked to prove this for the case of a square which is much easier for me. However I don't have a clue on how to prove the general case.


text:
Q: Extract strings using fuzzy LR patterns in R I am struggling for long time.
I manage to extract everything between my Right and Left patterns in a string as you can see in the following example.
library(tidyverse)

data=c("everything will be ok one day")

str_extract(string = data, pattern = "(?<=thing).*(?=ok one)")
#> [1] " will be "

Created on 2022-01-26 by the reprex package (v2.0.1)
As you notice in the code, I extract everything between "thing" and "ok one".
I need to incorporate the possibility of mismatches inside these patterns.
I want to allow a maximum of two mismatches and consider indels and insertions.

Example1
for example one mismatch that I want to account for
is the insertion of letter "s" in everything
dat.1=c("everythings will be ok one day")

I would like in this case to be able to extract the the phrase
will be

Example 2
dat.2=c("everythingswillbeokoneday")

I would like in this case to be able to extract the the phrase
will be

PS:
This is just a simplified example. My actual data does not contain gaps, and it's complicated. I am looking forward to receiving your help and guidance.

A: One way is to use fuzzy matching of strings, relying, for instance, on package stringdist and computing, for each delimiter string (thing and ok, in your example), the respective matching score (that is what the function maxsim does below).
library(tidyverse)
library(stringdist)

dat.1=c("everythings will be ok one day")

maxsim <- function(df, delim)
{
  df %>%
    str_split(" ") %>% unlist %>%
    map(~ stringsim(delim,.x)) %>%
    which.max
}

dat.1 %>%
  str_split(" ") %>% unlist %>%
  .[ (maxsim(dat.1,"thing") + 1) : (maxsim(dat.1,"ok") - 1) ] %>%
  str_c(collapse = " ")

#> [1] "will be"


text:
Q: The inequality $a^*ca \le \|c\| a^*a$ in a pre-$C^*$-algebra Let $A$ be a pre-$C^*$-algebra, i.e. $A$ satisfies all axioms for a $C^*$-algebra except completeness. In other words, $A$ is an involutive algebra with a $C^*$-norm.
We say that $x \in A$ is positive (notation: $x \ge 0$) if there exists $a\in A$ with $x = a^*a$ and on self-adjoint elements we define the usual relation $x \le y \iff y-x \ge 0$.
Given a positive element $c \ge 0$ in $A$, and $a \in A$, does the inequality
$$a^*ca \le \|c\| a^*a$$
hold? For $C^*$-algebras, this result is well-known. A quick proof is given by faithfully representing $A \subseteq B(H)$ and using $c \le \|c\|1$. Does the same result continue to hold for pre $C^*$-algebras?

Context question: In the book "Hilbert $C^*$-modules" by Lance on p4, it is claimed that all results proved so far continue to hold for inner product modules defined over a pre-$C^*$-algebra.  The above inequality is used in the proof of proposition 1.1 and I wanted to check that it still works for pre $C^*$-algebras.

Bonus question: Is the sum of two positive elements again positive?

A: Given your definitions, the first one is an easy no. If $a = 1$ then it says $c \leq \|c\|$, which fails when $A$ is the polynomials in $C[0,1]$: let $c$ be the polynomial $x$, then $\|c\|= 1$ and $1-x$ is not of the form $p\bar{p}$ for any polynomial $p$.
For the second question, take $a = x^2 + y^2$ and $b = z^2$ in the polynomials on $[0,1]^3$. Then $a = (x + iy)(x- iy)$ and $b = z\cdot z$ are both positive, but their sum is not. (Suppose you had a polynomial $p$ with $p\bar{p} = x^2 + y^2 + z^2$. Then $p$ has to be linear in $x$, $y$, and $z$ and the lack of $xy$ and $xz$ cross terms forces the arguments of the coefficients of $y$ and $z$ to be the same or differ by $\pi$, which in either case creates a nonzero $yz$ cross term.)
But I think the usual definition of positivity in a pre C${}^*$- algebra is that it is positive in the completion, which would make both answers trivially yes.


text:
Q: Make ball bounce and eventually come to rest I've written some code to move a ball around the screen using an orientation sensor. I wanted to get the ball to bounce when it hits the bottom of the screen, sort of like under gravity. Could somebody help out with implementing the physics in my existing code? Flipping the velocity doesn't seem to work. Here's my ball class:
package perseus.gfx.test;

import everything

public class Ball extends View  {
RectF lol;
Paint paint, lpaint;
Bitmap bitmap;
Canvas canvas;
private float ballx = 150;
private float bally = 140;
private double speedx = 0;
private double speedy = 0; //ignore
private double accx, accy=0;
private float rad = 20;
private float mult = 0.5f;
private double xv, yv, xS, yS;
int width, height;
int xmax, ymax;
int xmin, ymin;

public Ball(Context context) {
    super(context);
    lol = new RectF();
    paint = new Paint();
    paint.setColor(Color.CYAN);
    lpaint = new Paint();
    lpaint.setColor(Color.GRAY);
}
public void moveBall()  {

    xv = accx * mult;
    yv = accy * mult;

    xS = xv * mult;
    yS = yv * mult;

    ballx -= xS;
    bally -= yS;

    // Collision detection
    if (ballx + rad > xmax) {

         ballx = xmax-rad;
    }
    else if (ballx - rad < 0) {

         ballx = rad;
    }
    if (bally + rad > 2*ymax/3) //Shouldn't take up the whole screen
    {

        bally = 2*ymax/3 - rad;
    }

    else if (bally - rad < 0) {

         bally =  rad;
    }

    try {
        Thread.sleep(20);
    }   catch(InterruptedException e) {}

    invalidate();
}
@Override
public void onMeasure(int widthM, int heightM)
{
    width = View.MeasureSpec.getSize(widthM);
    height = View.MeasureSpec.getSize(heightM);
    xmax = width-1;
    ymax = height-1;
    xmin = 0;
    ymin = 0;
    setMeasuredDimension(width, height);
    bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    canvas = new Canvas(bitmap);

}
@Override
public void onDraw(Canvas canvas)
{
    canvas.drawBitmap(bitmap, 0, 0, paint);
    lol.set(ballx - rad, bally-rad, ballx + rad, bally+rad);
    canvas.drawLine(0, 2*height/3, width, 2*height/3, lpaint);
    canvas.drawOval(lol, paint);
    canvas.drawText(xv + " " + yv, 0, height/2, lpaint);
    canvas.save();
    moveBall();
    canvas.restore();

}
}

A: So the key is to just add a bit of friction, just remove a tiny bit of acceleration (negative!) at each step in moveBall(). E.g.
    float friction = -0.001;

    xv = accx * mult + friction;
    yv = accy * mult + friction;

Then adjust the variable friction accordingly to suit your needs. For the collision you need to invert the velocity, e.g. bounce on bottom:
    bally = -bally;


text:
Q: Hashing a password and securing it I am a new programmer so please forgive me if what I am going to say doesn't make any sense.
I know that we store hashes instead of actual passwords to secure passwords in case someone gets access to the database but let's say if someone has got all the hashes and they know what password hashing function has been used in the program. Can't they use salt for that hash and hack into accounts?

A: First thing you need to understand the difference between encryption and hashing. Any data that is encrypted could be decrypted. But hashing is always one way. So any data which was hashed using a salt once cannot be decrypted.
Also you have to use a strong hashing algorithm. Because hackers could use "rainbow tables" to brute force and retry infinitely using random values to imitate your passwords.
Why would you expose your source code and database credentials?
In production database credentials are encrypted and used in application configuration files. You have to follow up security protocols.

A: I am going to give it a stab. So what you are describing is securing passwords in a vault. There are lots of ways you can do this. I like Window-Vault if you are doing something small. If you are using Ansible, Ansible-Vault works. Hashicorp makes a really good one too.
Now for storing. You could store passwords in a Password manager, like Bitwarden for instance. This would solve most of your problems.
To store passwords without a manager, ensure you have Encryption at rest, and Encryption in Transit. Encryption at rest is on the disk. Encryption in Transit is SSL/TLS.
You can store the passwords as a hash locally, but it isn't really that much more secure. As you stated, you can reverse the encryption if you can get physical access. Most choose to encrypt the disk and encrypt transit, and handle the rest via access to the machine or storage location via a user name and strong password (maybe a firewall too).
It isn't bad to store passwords in plain text somewhere. Eventually they have to be decrypted. The important thing is securing the storage location and the transit.


text:
Q: How to export data from rails api to xls? I have an json api built with rails.
This is url: https://kazatomprom-backend.herokuapp.com/organizations/suzak/blocks/1/notes
I want to export data to xls. But this data must be customized according to model attributes.
id| volume_value|user
 1|        887  |zhanabek@gmail.com
 2|        897  |john@gmail.com

I found some solution, but it requires the view, but I don't need a view, because this is api. So, how to export data using only api?

A: Something like this will work (It uses csv data to write to xls file):
CSV.open('foo.xls', "wb") do |csv|
  csv << ['id','volume_value','user']
  JSON.parse(json).each do |hash|
    csv << [hash['id'],hash['volume_value'],hash['user']['email']]
  end
end

A: There is a gem acts_as_xlsx you might want to see
https://github.com/randym/acts_as_xlsx
It allows you to call .to_xlsx method on ActiveRecord result like this
Posts.where(created_at > Time.now-30.days).to_xlsx

How to Use
Add the gem to your Gemfile and bundle install
   gem 'acts_as_xlsx'
# app/models/post.rb
   class Post < ActiveRecord::Base
     acts_as_xlsx
   end

 # app/controllers/posts_controller.rb
   class PostsController < ApplicationController
     # GET posts/xlsx
     def xlsx
       p = Post.to_xlsx
       p.serialize('public/downloads/posts.xlsx')
       send_file 'public/downloads/posts.xlsx', :type=>"application/xlsx"
     end
   end

 # dont forget to add posts/xslx to your routes!


text:
Q: Can i sort structure in c++ using stl sort I was trying to sort a structure using stl sort in C++ . But i get some error . Is it that we cannot sort a structure in c++ using stl sort or is it my fault in implementation , if its my fault do let me know the correction .
Here's the code (its very small :) )
#include<iostream>
#include<algorithm>
using namespace std;
struct log {
       int sd;
       int ed;
} log[1000];
bool key(int i,int j) {
 return (log[i].ed<log[j].ed);
}
int main() {
int n,i;
cin>>n;
sort(log,log+n,key);
for (i=0;i<n;i++) cin>>log[i].sd>>log[i].ed;
for (i=0;i<n;i++) cout<<log.sd<<","<<log.ed<<endl;
system("PAUSE");
}

A: Yes, you can. But your comparator should take two const log & (not int) arguments.


text:
Q:  doesn't work on NavigationView? I'm trying to make a Navigation Drawer, and inside the NavigationView I've added the layout_gravity="start" attribute, but it wont hide the View. this is my code:
<RelativeLayout  ... >

    <android.support.design.widget.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/navigation_menu"></android.support.design.widget.NavigationView>

</RelativeLayout>

What could be wrong? Thanks.

A: If you intend for the NavigationView to behave as a drawer, then the root View should be <android.support.v4.widget.DrawerLayout>, instead of <RelativeLayout>

A: I hope this works for you because layout_gravity cannot be used inside Relativelayout.
<androidx.drawerlayout.widget.DrawerLayout>
    <android.support.design.widget.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/navigation_menu"></android.support.design.widget.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>


text:
Q: Windows Vista having trouble accessing hard drive This is one of the more bizarre issues I've seen. One of the guys at my company has Vista on his laptop which worked just fine until earlier this week. All of a sudden, everything would run really slowly, but only intermittently. AFter playing with it a bit, it seems like windows is sometimes trying to access the C: drive like a network share or something.
In Outlook or Word, for example, it'll hang with a message in the toolbar of "Contacting C:\Users[username]\AppData...". This will usually eventually timeout, with the program saying it couldn't find the relevant file. (Either a Word doc or Outlook PST). And then sometimes if you try it again it'll immediately pop up and work like normal. IE exhibits similar behavior, but it's harder to tell what it's actually doing. But for example I'll open up one IE and it just hangs, but I can wait a little while and start another IE and it'll immediately work fine, while the first one is still hung.
Does anybody have any idea what's going on? It's got Norton on there and it reports no problems. I've tried stopping just about every service and it still seems to do it. It did seem to work better in Safe Mode, but I can't be sure because of the intermittent nature of the issue.
I'm also a programmer, not a Windows admin, I just have to play one because this is a tiny company, so I could be missing something really basic.
ETA: UAC is running.

A: Try running Filemon from Microsoft SysInternals toolset.
http://technet.microsoft.com/en-us/sysinternals/bb545027.aspx
This will give you a listing of files being accessed as well as if the access was successful or not. Some of the other tools on that site may also be of assistance to you figuring out what is slowing down the system.
There is some boutique spyware/viruses out there that can really get into the system, and Norton can not find it. Hopefully that isn't the problem.

A: Norton is prone to thrashing even the most powerful of computers and bringing them to a grinding halt so it might be worth disabling the onaccess scanning in norton whilst booted up normally to see if this has any effect.
Additionaly it might be worth checking the state of the drive to see if its having read issues. You can use chkdsk (Right click drive in my compiter and its on one of the properties tabs) It will probably ask you to reboot.
Also you could build an UBCD4Win boot disc which loads a cutdown version of windows into memory off a bootable cd which allows you to run a host of included diagnostics tools.
Hope this helps

A: A laptop at a company - does the user have some sort of roaming profile, or rather, do you have any of the profiles user settings pushed off to a network share somewhere? Using offline files or some such? You may have some sort of network connectivity problem that Vista is reporting in a non-intuitive way.


text:
Q: Apply CSS style when clicked on SVG element I am trying to set the CSS style for the clicked element. I have tried to put :active :clicked :targed with the class name and none of these worked. :hover effect works fine. Thanks for the answers.
HTML:

    <ellipse
    class="e-image"
       id="path3769-9"
       cx="43.089287"
       cy="103.09822"
       rx="43.845238"
       ry="39.498512"
       style="fill:#ff7f2a;stroke-width:0.26458332" />
    <text
    class="e-text"
       xml:space="preserve"
       style="font-style:normal;font-weight:normal;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.26458332"
       x="22.300594"
       y="99.318459"
       id="text3836"><tspan
         sodipodi:role="line"
         id="tspan3834"
         x="22.300594"
         y="99.318459"
         style="stroke-width:0.26458332">LANKS - </tspan><tspan
         sodipodi:role="line"
         x="22.300594"
         y="112.54762"
         style="stroke-width:0.26458332"
         id="tspan3838">TUMAS</tspan></text>

CSS:
.lankstumas:hover{
        .e-image{
            transition: .2s fill;
            fill: #FF8504!important;
        }
        .e.text{
            transition: .2s fill;
            fill:#fff!important;
        }
        }

A:
I am trying to set the CSS style for the clicked element.

One approach to achieve this effect is to give the element an HTML5 Custom data-* attribute like this:
data-clicked="false"

You can then use javascript, to detect a click on the element and update the attribute.
To detect the click with javascript, use:
myElement.addEventListener('click', myFunction, false);

To modify the attribute use:
myElement.dataset.myAttribute = myValue;

Working Example:

const boxes = document.getElementsByClassName('box');

const showClick = (e) => {
  event.target.dataset.clicked = 'true';
}

for (let i = 0; i < boxes.length; i++) {

  boxes[i].addEventListener('click', showClick, false);

}
.box {
  display: inline-block;
  width: 100px;
  height: 100px;
  margin: 6px;
  background-color: rgb(255, 0, 0);
  cursor: pointer;
}

.box::after {
  content: 'Click me!';
  display: block;
  text-align: center;
  line-height: 100px;
  color: rgb(255, 255, 255);
  font-weight: bold;
}

.box[data-clicked="true"] {
  color: rgb(255, 0, 0);
  background-color: rgb(255, 255, 0);
}

.box[data-clicked="true"]::after {
  content: 'Clicked!';
  color: rgb(255, 0, 0);
}

A: In your code you want to overwrite inline css. In order to change the color you need to delete the inline styles for the fill. Next comes an example:

svg{border:solid;width:90vh;}
.e-image{transition: .2s fill;}

.lankstumas:hover .e-image{fill: skyBlue; }
.lankstumas:hover .e-text{fill:#fff;}
<svg viewBox="-5 60 100 90">

    <ellipse
    class="e-image"
       id="path3769-9"
       cx="43.089287"
       cy="103.09822"
       rx="43.845238"
       ry="39.498512"
       fill="#ff7f2a"

        />
    <text
    class="e-text"
       xml:space="preserve"
       style="font-style:normal;font-weight:normal;font-size:10.58333302px;line-height:1.25;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;stroke:none;stroke-width:0.26458332"
       x="22.300594"
       y="99.318459"
       id="text3836">
      <tspan
         sodipodi:role="line"
         id="tspan3834"
         x="22.300594"
         y="99.318459"
         style="stroke-width:0.26458332">LANKS - </tspan><tspan
         sodipodi:role="line"
         x="22.300594"
         y="112.54762"
         style="stroke-width:0.26458332"
         id="tspan3838">TUMAS</tspan></text>

</svg>


text:
Q: ArrayList of objects serialization exception in c# I have an ArrayList which consist of lots of object created by me. I am trying to keep it. As far as I look, the best solution for that is to use binary formatter. But something is wrong with my code. It doesn't work either writing or reading. Here is my code;
namespace WindowsFormsApplication1
{
   public partial class Form1 : Form
   {
      private ArrayList allList = new ArrayList();
      private FileStream fileStream;
      private MemoryStream memoryStream;

      public Form1()
      {
          InitializeComponent();
          fileStream = new FileStream("pcdata.dat",FileMode.OpenOrCreate,FileAccess.ReadWrite);
          memoryStream = new MemoryStream();
      }
      public void acceptDevice(Device receivedDevice)
      {
          //Somehow I call this method
          allList.Add(receivedDevice);
          saveDeviceDataToFileStream();
      }
      private void saveDeviceDataToFileStream()
      {
          SerializeToStream(allList).WriteTo(fileStream);
      }
      private void loadDeviceDataFromFileStream()
      {
          fileStream.CopyTo(memoryStream);
          allList = (ArrayList)DeserializeFromStream(memoryStream);
      }
      public static MemoryStream SerializeToStream(object o)
      {
          MemoryStream stream = new MemoryStream();
          IFormatter formatter = new BinaryFormatter();
          formatter.Serialize(stream, o);
          return stream;
      }
      public static object DeserializeFromStream(MemoryStream stream)
      {
          IFormatter formatter = new BinaryFormatter();
          stream.Seek(0, SeekOrigin.Begin);
          if (null == stream)
          {
             return null;
          }
          object o = formatter.Deserialize(stream);
          return o;
    }
  }
}

This is my device class:
namespace WindowsFormsApplication1
{
    [Serializable]
    public class Device
    {
        public MyPanel panel;           //panel class that I created
        public String id;
        public int deviceNumber;

        public Device(String id, int deviceNumber)
        {
            panel = new MyPanel();
            this.id = id;
            this.deviceNumber = deviceNumber;
        }
    }
}

And this is myPanel class:
namespace WindowsFormsApplication1
{
    public class MyPanel : TableLayoutPanel
    {
        public Panel panel1 = new Panel();
        public Panel panel2 = new Panel();
        public Panel panel3 = new Panel();
        public Panel panel4 = new Panel();
        public PictureBox pictureBox1 = new PictureBox();
        public Label nameLabel = new Label();
        public MyPanel()
        {
            //...
        }
    }
}

This is it. When I tried to tun it I get this exception :

SerializationException was unhandled
An unhandled exception of type
  'System.Runtime.Serialization.SerializationException' occurred in
  mscorlib.dll
Additional information: 'WindowsFormsApplication1, Version=1.0.0.0,
  Culture=neutral, PublicKeyToken=null' Derlemesindeki
  'WindowsFormsApplication1.MyPanel' ...

A: I dont think you will be able to just serialize controls like that. I would suggest creating classes around the data you want to save and make the controls only responsible for display.
[Serializable]
public class MyPanelInfo
{
    public PanelInfo panel1;
    public PanelInfo panel2;
    public PanelInfo panel3;
    public PanelInfo panel4;
    public Image image;
    public string nameLabel;

    public MyPanelInfo()
    {

    }
}

[Serializable]
public class PanelInfo
{
    public string id;
    public string name;
}


text:
Q: Windows media foundation enumerating Camera devices I would like to enumerate the camera devices on my computer using Windows Media Foundation, I used the code on Microsoft : http://msdn.microsoft.com/en-us/library/windows/desktop/dd940326(v=vs.85).aspx
I reproduced the same code they use here : http://msdn.microsoft.com/en-us/library/windows/desktop/ee663604(v=vs.85).aspx
When I used their code I get my webcam device name, however my code doesn't find any camera capture device. I'm enable to find why.
Here is the code :
    #pragma once
#include <new>
#include <windows.h>
#include <mfapi.h>
#include <mfidl.h>
#include <mfreadwrite.h>
#include <Wmcodecdsp.h>
#include <assert.h>
#include <Dbt.h>
#include <shlwapi.h>
#include <mfplay.h>

#include <iostream>

const UINT WM_APP_PREVIEW_ERROR = WM_APP + 1;    // wparam = HRESULT

class DeviceList
{
    UINT32      m_cDevices; // contains the number of devices
    IMFActivate **m_ppDevices; // contains properties about each device

public:
    DeviceList() : m_ppDevices(NULL), m_cDevices(0)
    {

    }
    ~DeviceList()
    {
        Clear();
    }

    UINT32  Count() const { return m_cDevices; }

    void    Clear();
    HRESULT EnumerateDevices();
    HRESULT GetDevice(UINT32 index, IMFActivate **ppActivate);
    HRESULT GetDeviceName(UINT32 index, WCHAR **ppszName);
};

#include "DeviceList.h"

/*
* A templated Function SafeRelease releasing pointers memories
* @param ppT the pointer to release
*/

template <class T> void SafeRelease(T **ppT)
{
    if (*ppT)
    {
        (*ppT)->Release();
        *ppT = NULL;
    }
}

/*
* A function which copy attribute form source to a destination
* @ param pSrc is an Interface to store key/value pairs of an Object
* @ param pDest is an Interface to store key/value pairs of an Object
* @ param GUID is an unique identifier
* @ return HRESULT return errors warning condition on windows
*/

HRESULT CopyAttribute(IMFAttributes *pSrc, IMFAttributes *pDest, const GUID& key);

/*
* A Method form DeviceList which clear the list of Devices
*/

void DeviceList::Clear()
{
    for (UINT32 i = 0; i < m_cDevices; i++)
    {
        SafeRelease(&m_ppDevices[i]);
    }
    CoTaskMemFree(m_ppDevices);
    m_ppDevices = NULL;

    m_cDevices = 0;
}

/*
* A function which enumerate the list of Devices.
* @ return HRESULT return errors warning condition on windows
*/
HRESULT DeviceList::EnumerateDevices()
{
    HRESULT hr = S_OK;
    IMFAttributes *pAttributes = NULL;

    this->Clear();

    // Initialize an attribute store. We will use this to
    // specify the enumeration parameters.
    std::cout << "Enumerate devices" << std::endl;
    hr = MFCreateAttributes(&pAttributes, 1);

    // Ask for source type = video capture devices
    if (SUCCEEDED(hr))
    {
        std::cout << "Enumerate devices" << std::endl;
        hr = pAttributes->SetGUID(
            MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,
            MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID
            );
    }
    // Enumerate devices.
    if (SUCCEEDED(hr))
    {
        std::cout << "Enumerate devices:" << m_cDevices << std::endl;
        hr = MFEnumDeviceSources(pAttributes, &m_ppDevices, &m_cDevices);
    }

    SafeRelease(&pAttributes);

    return hr;
}

/*
* A function which copy attribute form source to a destination
* @ param index the index in an array
* @ param ppActivate is an Interface to store key/value pairs of an Object
* @ return HRESULT return errors warning condition on windows
*/

HRESULT DeviceList::GetDevice(UINT32 index, IMFActivate **ppActivate)
{
    if (index >= Count())
    {
        return E_INVALIDARG;
    }

    *ppActivate = m_ppDevices[index];
    (*ppActivate)->AddRef();

    return S_OK;
}

/*
* A function which get the name of the devices
* @ param index the index in an array
* @ param ppszName Name of the device
*/

HRESULT DeviceList::GetDeviceName(UINT32 index, WCHAR **ppszName)
{
    std::cout << "Get Device name" << std::endl;
    if (index >= Count())
    {
        return E_INVALIDARG;
    }

    HRESULT hr = S_OK;

    hr = m_ppDevices[index]->GetAllocatedString(
        MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME,
        ppszName,
        NULL
        );

    return hr;
}

#include <iostream>
#include "DeviceList.h"

HRESULT UpdateDeviceList()
{
    HRESULT hr = S_OK;
    WCHAR *szFriendlyName = NULL;

    DeviceList g_devices;

    g_devices.Clear();

    hr = g_devices.EnumerateDevices();

    if (FAILED(hr)) { goto done; }
    std::cout << "Nb devices found:"<< g_devices.Count() << std::endl;

    for (UINT32 iDevice = 0; iDevice < g_devices.Count(); iDevice++)
    {
        //std::cout << "" << std::endl;
        hr = g_devices.GetDeviceName(iDevice, &szFriendlyName);
        if (FAILED(hr)) { goto done; }
        std::cout << szFriendlyName << std::endl;
        // The list might be sorted, so the list index is not always the same as the
        // array index. Therefore, set the array index as item data.
        CoTaskMemFree(szFriendlyName);
        szFriendlyName = NULL;
    }
    std::cout << "End of EnumDeviceList" << std::endl;
done:
    return hr;
}

int main()
{
    std::cout <<"Main" << std::endl;
    UpdateDeviceList();
while (1);
return 0;

}

A: You are expected to do MFStartup(MF_VERSION); before you start calling other Media Foundation API functions.
Then you print m_cDevices before it is getting initialized one line below by MFEnumDeviceSources.
    std::cout << "Enumerate devices:" << m_cDevices << std::endl;
    hr = MFEnumDeviceSources(pAttributes, &m_ppDevices, &m_cDevices);

Having this fixed, your code will start getting you the devices.


text:
Q: Function parameter to pass different structures Is it possible to write a function, which

*

*Can receive different types of structures from the same parameter ( maybe void* ?), and

*Detects the type of the structure received in the function?

That is, when I call this function, I send a particular structure to it and when I call it again, I send a different type of structure.
Is this possible in C?
Thank you in advance.

A: The old-fashioned way to do this is to have some generic struct containing an enum and a void pointer like:
typedef enum
{
  FOO_TYPE,
  BAR_TYPE
} type_t;

typedef struct {
  type_t type;
  void*  data;
} foo_t

You then inspect the enum type and cast the data pointer to the appropriate type.
In modern standard C, you can alternatively create type-generic, type safe macros like this:
void func_int   (int x);
void func_float (float x);

#define func(x) _Generic((x), case int: func_int, case float: func_float) (x)

...

int i;
float f;
func(i);
func(f);


text:
Q: ArcGIS10.2 Data Merge error: 000732 I am running python in the ArcGIS python window.
ArcGIS shows error message when trying data merge from arcpy.

File "", line 1, in    File "c:\program files
(x86)\arcgis\desktop10.2\arcpy\arcpy\management.py", line 3816, in
Merge     raise e ExecuteError: ERROR 000732:

import os
import arcpy
arcpy.env.workspace = "C:/the shapefile folder/"

path = os.listdir("C:/the shapefile folder/")#unzipped all shapefiles to this folder
shapefile = []
for i in path:
    suffix = ".shp";
    if i.endswith(suffix):#getting all files end with '.shp' to a new list
        shapefile.append(i)
arcpy.Merge_management(shapefile,"C:/output folder")

Where is the problem?

A: you need to provide an output feature class (e.g. "C:/outputfolder/newfc.shp" or "C:/outputfolder/geodatabase.gdb/newfc", if geodatabase.gdb already exists) and not an output folder (C:/outputfolder) for the merge tool.
Also check that your shapefile have a defined CRS, but the error probably comes from the above output.


text:
Q: jquery bind getting invoked more than once Plain jQuery binding function is getting called twice for me, I have seen this problem when working with jQuery mobile also.
$(document).ready(function(){

$(window).bind("resize",function(){

$("#length").text($(window).width());
$("#length").show("slow");
$("#length").hide("slow");
});
});

1

fiddled : http://jsfiddle.net/2Yy7Q/

A: Well known browsers behaviour, a possible workaround:
http://jsfiddle.net/2Yy7Q/1/
$(document).ready(function () {
    (function () {
        var timeout;
        $(window).bind("resize", function () {
            clearTimeout(timeout);
            timeout = setTimeout(function () {
                $("#length").text($(window).width());
                $("#length").show("slow");
                $("#length").hide("slow");
            }, 50);
        });

    })();
});

NOTE  you could set timeout duration to 0, 50 is to give you the idea


text:
Q: what datatype to use to store "MMYYYY" format I am using .NET environment and wanted to track the expiration date found in credit cards. The date there is of the nature "MMYYYY". What would be a recommended way to store this ? Should I just use .NET string or instead use the .NET DateTime object ?

A: In almost all cases the easiest solution is often the best solution.  Its easy to maintain, easy for other programmers to recognize, and may even keep you out of trouble (ints and strings can lead to localization problems and invalid values).
A System.DateTime is the best option and gives you flexibility for those cards that may also expire on a given day (they are rare, but they do exist, and may become more prevalent with temporary credit cards becoming popular).  When storing the value just use the Date property of the System.DateTime struct since that will disregard the time components.

A: Store MM and YYYY as two separate integer values.

A: for this case that you want to store expiration of credit card, it's better if you define your struct like this. this ensures that invalid values will not happen.
public enum MonthOfYear
{
    Jan = 1,
    Feb = 2,
    ...
}

public struct CardExpiration
{
    public MonthOfYear Month;
    public int Year;
}

although, you can use DateTime to make it quicker.

A: Another way to store it as integer where result is:
VALUE = YYYY * 100 + MM
So for Jul 2011 you will have 2011 * 100 + 07 = 201107  for Oct 2015 you will have 201510 and Dec 2014 your will have 201412.  This way to do comparison if card is expired or not very easy, since you just need to compare two numbers.


text:
Q: Unequal length between strings after writing to a file - using same delimiter (tab) I have a short procedure in PL/SQL which uses UTL_FILE package to create and then write to a .txt file.
Tab is saved in its own variable (v_delimiter), declared as varchar2(5), with a value of chr(9).
The header is saved as a string, concatenated with the v_delimiter and then written to a file.
After that, the rest of the data from an explicit cursor is also written to a file, line by line.
In the end, when I open the txt file, there are unequal widths between some of the strings which make up a header. There are also unequal widths between some of the data from the cursor inside a final .txt file and I guess that shouldn't be since I am using one and the same delimiter (tab) to create a header and to create a string from a cursor.
I am using UTL_FILE.put_line_nchar function to write a Unicode line to a file.
I tried without declaring a delimiter as a variable, using literally chr(9) when concatenating and it is always the same result.
I am out of ideas why is this happening in the final txt file.
 v_file_handle     UTL_FILE.file_type ;
 v_output_path   VARCHAR2 (100) := '/Path/to/File' ;
 v_file_header   VARCHAR2 (32767) ;
 v_delimiter     VARCHAR2 (5) := chr(9) ;

v_file_handle := UTL_FILE.fopen_nchar (v_output_path,'string_1' || TO_CHAR (SYSDATE, 'dd_mm_yyyy') || '.txt','w', 32767); -- opening

v_file_header :='claimFileIdentifier'|| v_delimiter || 'claimFileOpenedDate'
|| v_delimiter|| 'claimStatus'|| v_delimiter|| 'claimStatusDate'|| v_delimiter|| 'incidentDateTime'|| v_delimiter|| 'incidentPlace'|| v_delimiter|| 'calculationType' ... -- header

 UTL_FILE.put_line_nchar ( v_file_handle, v_file_header ) ; --writing header to a file

 FOR rec IN cursor_candidates --iterating over a cursor

   LOOP

      UTL_FILE.put_line_nchar (
         v_file_handle,
            rec.claimFileIdentifier
         || v_delimiter
         || rec.claimFileOpenedDate
         || v_delimiter
         || rec.claimStatus
         || v_delimiter
         || rec.claimStatusDate
         || v_delimiter
         || rec.incidentDateTime
         || v_delimiter
         || rec.incidentPlace
         || v_delimiter ... ) ; -- writing cursor rows to a file

  END LOOP ;

  UTL_FILE.fclose ( v_file_handle );

Final txt file and unequal width between certain strings

A: That's kind of expected, in my opinion. Values are separated by the TAB character, but it doesn't mean that output will look "nice" when you look at it as a text file.
For example, following values are separated by TAB, but they look ugly:
a   b   c
Littlefoot  Scott   Tiger

If you e.g. imported that file into Excel and set TAB as column separator, every value would be in its own column and output would look pretty.
If you wanted text file to look nice as well, you'll have to use a different approach, e.g. LPAD numeric values (IDs, salaries, ...), RPAD textual strings (names, addresses, ...), possibly SUBSTR (to cut long values short).

A: This relating to the functionality of the client application that you use to open the output tab-separated values (TSV) file.
If I have the data:
longtitle   longtitle2  longtitle3
a   b   c
1234567890  123456789010234545  1234567788

and I open it in a basic text editor (such as Notepad) then the output is:

And the columns are unequal across the rows.
However, if I display the same data in an editor that supports TSV files (such as Notepad++) then it displays the same output with equal widths for the columns across the rows:

Importing the data into a spreadsheet application (such as Excel or OpenOffice), then the TSV is separated into cells and the output is:

And, again, the information is split into columns.

Do not change how you are outputting the file; instead, find a better way of viewing the output file with an application that supports formatting tab-separated values.


text:
Q: Multi-Window GUI using Python Traits How can I create two windows using Python traits? Something like
if __name__ == '__main__':
    main_gui = MainGUI()
    user_input = UserInput()

    main_gui.configure_traits()
    user_input.configure_traits()

The issue here is that user_input.configure_traits isn't called until main_gui is closed, but since I'd like to have interaction between the two windows this obviously won't do. Is there perhaps a way to mimic a 'close' function within MainGUI and UserInput without actually closing the window, so that the main body of the code can move on? Thanks!

A: What you are trying to do here is not traithonic.
What you should do is set up the user input window as a child window of the Main window, and use traits' system of event listening to track the user's interaction.  A very simple example:
class MainGUI(HasTraits):
  GUIWidgetsForMainGUI = Any
  user_window = Instance(UserInput)
  button = Button('Get User Input')

  traits_view=View(Item('GUIWidgetsForMainGUI'),
    Item('button'))

  def _button_fired(self):
    self.user_window.edit_traits()

  @on_trait_change('button')
  def or_alternately_you_can_use_listeners(self):
    self.user_window.edit_traits()

MainGUI().configure_traits()


text:
Q: Picking and posting multiple pics and vids using flutter In social media apps such as Instagram you can often publish a post with multiple pics and vids. In flutter there are couple of dependencies such as image/video picker which allow you to choose a single image or a single video, and a file manager dependency which allows you to pic multiple pics but no videos. Is there a dependency where we can pick multiple pics and vids and publish them as one post?
Thanks in advance!

A: Here is the workflow of what you should do:

*

*Add image_picker plugin in pubspec.yaml;

*Add Requied Permissions if any;

*Call ImagePicker.pick* and this will return you a file;

*Display your file or perform the action you needed.


text:
Q: Graphhopper exclude some roads I need to exclude some roads from routing.
I solve this problem implementing it with EdgefFilter
Or Is it better to use Weeighting interface?
Thanks
Antonio

A: This example is documented in the weighting docs so Weighting is perfect. But it could be done with an EdgeFilter too, although the Weighting is more powerful and you could e.g. introduce a high penalty instead of 100% blocking.


text:
Q: Confused about JavaScript prototypal inheritance with constructors I've read pages and pages about JavaScript prototypal inheritance, but I haven't found anything that addresses using constructors that involve validation. I've managed to get this constructor to work but I know it's not ideal, i.e. it's not taking advantage of prototypal inheritance:
function Card(value) {
    if (!isNumber(value)) {
        value = Math.floor(Math.random() * 14) + 2;
    }

    this.value = value;
}

var card1 = new Card();
var card2 = new Card();
var card3 = new Card();

This results in three Card objects with random values. However, the way I understand it is that each time I create a new Card object this way, it is copying the constructor code. I should instead use prototypal inheritance, but this doesn't work:
function Card(value) {
    this.value = value;
}

Object.defineProperty( Card, "value", {
    set: function (value) {
        if (!isNumber(value)) {
            value = Math.floor(Math.random() * 14) + 2;
        }

        this.value = value;
    }
});

This doesn't work either:
Card.prototype.setValue = function (value) {
    if (!isNumber(value)) {
        value = Math.floor(Math.random() * 14) + 2;
    }

    this.value = value;
};

For one thing, I can no longer call new Card(). Instead, I have to call var card1 = new Card(); card1.setValue(); This seems very inefficient and ugly to me. But the real problem is it sets the value property of each Card object to the same value. Help!

Edit
Per Bergi's suggestion, I've modified the code as follows:
function Card(value) {
    this.setValue(value);
}

Card.prototype.setValue = function (value) {
    if (!isNumber(value)) {
        value = Math.floor(Math.random() * 14) + 2;
    }

    this.value = value;
};

var card1 = new Card();
var card2 = new Card();
var card3 = new Card();

This results in three Card objects with random values, which is great, and I can call the setValue method later on. It doesn't seem to transfer when I try to extend the class though:
function SpecialCard(suit, value) {
    Card.call(this, value);

    this.suit = suit;
}

var specialCard1 = new SpecialCard("Club");
var specialCard2 = new SpecialCard("Diamond");
var specialCard3 = new SpecialCard("Spade");

I get the error this.setValue is not a function now.

Edit 2
This seems to work:
function SpecialCard(suit, value) {
    Card.call(this, value);

    this.suit = suit;
}

SpecialCard.prototype = Object.create(Card.prototype);
SpecialCard.prototype.constructor = SpecialCard;

Is this a good way to do it?

Final Edit!
Thanks to Bergi and Norguard, I finally landed on this implementation:
function Card(value) {
    this.setValue = function (val) {
        if (!isNumber(val)) {
            val = Math.floor(Math.random() * 14) + 2;
        }

        this.value = val;
    };

    this.setValue(value);
}

function SpecialCard(suit, value) {
    Card.call(this, value);

    this.suit = suit;
}

Bergi helped me identify why I wasn't able to inherit the prototype chain, and Norguard explained why it's better not to muck with the prototype chain at all. I like this approach because the code is cleaner and easier to understand.

A:
the way I understand it is that each time I create a new Card object this way, it is copying the constructor code

No, it is executing it. No problems, and your constructor works perfect - this is how it should look like.
Problems will only arise when you create values. Each invocation of a function creates its own set of values, e.g. private variables (you don't have any). They usually get garbage collected, unless you create another special value, a privileged method, which is an exposed function that holds a reference to the scope it lives in. And yes, every object has its own "copy" of such functions, which is why you should push everything that does not access private variables to the prototype.
 Object.defineProperty( Card, "value", ...

Wait, no. Here you define a property on the constructor, the function Card. This is not what you want. You could call this code on instances, yes, but note that when evaluating this.value = value; it would recursively call itself.
 Card.prototype.setValue = function(){ ... }

This looks good. You could need this method on Card objects when you are going to use the validation code later on, for example when changing the value of a Card instance (I don't think so, but I don't know?).

but then I can no longer call new Card()

Oh, surely you can. The method is inherited by all Card instances, and that includes the one on which the constructor is applied (this). You can easily call it from there, so declare your constructor like this:
function Card(val) {
    this.setValue(val);
}
Card.prototype...

It doesn't seem to transfer when I try to extend the class though.

Yes, it does not. Calling the constructor function does not set up the prototype chain. With the new keyword the object with its inheritance is instantiated, then the constructor is applied. With your code, SpecialCards inherit from the SpecialCard.prototype object (which itself inherits from the default Object prototype). Now, we could either just set it to the same object as normal cards, or let it inherit from that one.
SpecialCard.prototype = Card.prototype;

So now every instance inherits from the same object. That means, SpecialCards will have no special methods (from the prototype) that normal Cards don't have... Also, the instanceof operator won't work correctly any more.
So, there is a better solution. Let the SpecialCards prototype object inherit from Card.prototype! This can be done by using Object.create (not supported by all browsers, you might need a workaround), which is designed to do exactly this job:
SpecialCard.prototype = Object.create(Card.prototype, {
    constructor: {value:SpecialCard}
});
SpecialCard.prototype.specialMethod = ... // now possible

A: In terms of the constructor, each card IS getting its own, unique copy of any methods defined inside of the constructor:
this.doStuffToMyPrivateVars = function () { };

or
var doStuffAsAPrivateFunction = function () {};

The reason they get their own unique copies is because only unique copies of functions, instantiated at the same time as the object itself, are going to have access to the enclosed values.
By putting them in the prototype chain, you:

*

*Limit them to one copy (unless manually-overridden per-instance, after creation)

*Remove the method's ability to access ANY private variables

*Make it really easy to frustrate friends and family by changing prototype methods/properties on EVERY instance, mid-program.

The reality of the matter is that unless you're planning on making a game that runs on old Blackberries or an ancient iPod Touch, you don't have to worry too much about the extra overhead of the enclosed functions.
Also, in day-to-day JS programming, the extra security from properly-encapsulated objects, plus the extra benefit of the module/revealing-module patterns and sandboxing with closures VASTLY OUTWEIGHS the cost of having redundant copies of methods attached to functions.
Also, if you're really, truly that concerned, you might do to look at Entity/System patterns, where entities are pretty much just data-objects (with their own unique get/set methods, if privacy is needed)...  ...and each of those entities of a particular kind is registered to a system which is custom made for that entity/component-type.
IE: You'd have a Card-Entity to define each card in a deck.
Each card has a CardValueComponent, a CardWorldPositionComponent, a CardRenderableComponent, a CardClickableComponent, et cetera.
CardWorldPositionComponent = { x : 238, y : 600 };

Each of those components is then registered to a system:
CardWorldPositionSystem.register(this.c_worldPos);

Each system holds ALL of the methods which would normally be run on the values stored in the component.
The systems (and not the components) will chat back and forth, as needed to send data back and forth, between components shared by the same entity (ie: the Ace of Spade's position/value/image might be queried from different systems so that everybody's kept up to date).
Then instead of updating each object -- traditionally it would be something like:
Game.Update = function (timestamp) { forEach(cards, function (card) { card.update(timestamp); }); };
Game.Draw = function (timestamp, renderer) { forEach(cards, function (card) { card.draw(renderer); }); };

Now it's more like:
CardValuesUpdate();
CardImagesUpdate();
CardPositionsUpdate();
RenderCardsToScreen();

Where inside of the traditional Update, each item takes care of its own Input-handling/Movement/Model-Updating/Spritesheet-Animation/AI/et cetera, you're updating each subsystem one after another, and each subsystem is going through each entity which has a registered component in that subsystem, one after another.
So there's a smaller memory-footprint on the number of unique functions.
But it's a very different universe in terms of thinking about how to do it.


text:
Q: How to check if the map and reduce operations are being done all nodes I have a cluster with 3 nodes , when I place my file in node1 it gets replicated to nodes 2 and 3.
This I am able to verify using the http://localhost:9870 and in browse filesystem.
And when I run the wordcount program how to check if the map and reduce operations are executed in nodes 1,2,3?
Is there anyway we can check this?

A: You can look at the YARN UI to see which nodes executed which tasks


text:
Q: DateFormat system.currenttimemillis() As the date is in Milli second format,  How do i convert it to have a DD/MM/YY format??
Long Ldate = System.currentTimeMillis();
String date = Ldate.toString();

A: Please use this code. This will help you.
long time = System.currentTimeMillis();
SimpleDateFormat dayTime = new SimpleDateFormat("dd/MM/yy");
String str = dayTime.format(new Date(time));


text:
Q: The guard has gone beserk (or how do I keep multiple MAPI clients running together?) I have a standalone program that I am trying to hook into MAPI to send emails automatically using the default system (Outlook for the most part) available.  For the most part, it works quite well, and everything sends fine.  However, after a while, Outlook will start to flip out about my program's accessing the MAPI system, and will start to refuse to show anything until all MAPI users (my program and Outlook) are closed and re-opened.  My best guess at this stage is that I'm not using a proper set of flags when logging in to the MAPI system, though I can't see why.  My current set is MAPI_ALLOW_OTHERS, MAPI_EXTENDED, and MAPI_USE_DEFAULT.  Can anyone suggest a different combination that lets Outlook continue to ignore me, and keep the guard placated?  Thanks.

A: I experienced something similar a while back and was able to work around it by centralizing all of my extended MAPI calls from a single point of entry, and added a queue to insure that only one MAPI event from my application was occurring at any point in time.


text:
Q: Were the Egyptian Four Horsemen characters from the comics? In the opening sequence of X-Men: Apocalypse, we see the "Four Horsemen" of Apocalypse

 during his life transfer ritual.

These are not the original Four Horsemen of Apocalypse from the comics: War, Famine, Pestilence, & Death. However, are the characters shown in the film other mutants from the comics, or original characters?

A: According to the IMDB page for the film, they are given exaclty these names, War, Famine, Pestilence, Death. This choice though might have been made only for nominal/practical purposes as they are not named in any part of it.

The one who dies last, surviving long enough to protect Apocalypse's body is named as Death and seems to control various powers, including telepathy, telekinisis, force field creation..


text:
Q: Set position of a select integrated into a table I have a table and i sticked the table head, everything is okay but look at the select that i have integrated into my table:
Before scrolling table
After scrolling table
Look at the select, it goes over the table head, how can i do please ?
It's the react-responsive-select https://www.npmjs.com/package/react-responsive-select

A: change fix header CSS property z-index to a maximum value. I think it will solve your problem. Let me know if there is an issue with that.I will help you as much as I can.


text:
Q: extra one color with photoshop Does anyone know how I can extract just the black from the image below?
http://d365447.u142.fasthit.net/logoidea.png

A: Select > Color Range > Blacks ?
Of course, there isn't really any black in the image - just a continuous range of red values, green values and blue values. You want to extract all pixels where r < cutoff, g < cutoff, b < cuttoff.
Try this,
Copy the image,
make a new layer filled with a solid colour of your choosing. Using the button at the bottom of the layers palette 'add a layer mask'.
In the layers palette alt-click on the empty layer mask thumbnail. You should now see an empty canvas - you are editing the layer mask.
Paste your image into the layer mask. It should appear greyscale. Press Apple-i (apologies, assuming mac) to invert it.
Exit layer mask edit mode by alt-clicking on the thumbnail again.
You should now see your solid colour layer masked by your inverted image, which roughly corresponds to the darkest values.
Change the fill colour of the layer to whatever you like. Black if you want the shadows.
try applying a curves filter to the mask to tweak the results.


text:
Q: Powershell script is error when run Release Azure Pipeline I created a release pipeline on Azure DevOps and got a PowerShell script error message "Exit code 1 returned from process: file name 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"  as in the image below although I could connect to virtual machine by running Registration script on the PowerShell administrator.Please help me to pass this case
enter image description here
And this is my powerShell config on Azure :enter image description here

A: I tried running the below command to install the IIS server feature in Azure DevOps pipeline like below:-
I created one Self-Hosted Agent and ran your command inside the self hosted agent VM just to check if it runs correctly :-

I ran the same command in my Azure DevOps YAML pipeline but added Start-Process command to start PowerShell task in elevated state as Administrator.
Script:-
trigger:

- main

pool:

name: Default

steps:

- script: echo Hello, world!

displayName: 'Run a one-line script'

- script: |

echo Add other tasks to build, test, and deploy your project.

echo See https://aka.ms/yaml

displayName: 'Run a multi-line script'

- task: PowerShell@2

inputs:

targetType: 'inline'

script: |

$script = "Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServerRole"

Start-Process powershell.exe -Verb RunAs -ArgumentList '-NoProfile', '-Command', $script

With  both the commands:-
# Starter pipeline

# Start with a minimal pipeline that you can customize to build and deploy your code.

# Add steps that build, run tests, deploy, and more:

# https://aka.ms/yaml

trigger:

- main

pool:

name: Default

steps:

- script: echo Hello, world!

displayName: 'Run a one-line script'

- script: |

echo Add other tasks to build, test, and deploy your project.

echo See https://aka.ms/yaml

displayName: 'Run a multi-line script'

- task: PowerShell@2

inputs:

targetType: 'inline'

script: |

$script = "Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServerRole"

"Enable-WindowsOptionalFeature -Online -FeatureName ASPNET45 -All"

Start-Process powershell.exe -Verb RunAs -ArgumentList '-NoProfile', '-Command', $script

Output:-


text:
Q: Know if user enabled/disabled check spelling on iPhone Is there any way to know (Programmatically) if a user enabled/disabled check spelling
(General->Keyboard->check spelling) ?

A: No, there is no way you can find this out programatically.

A: It is not possible in iOS .
But your generate Red UnderLine for wrong spelling.
[textView setSpellCheckingType:UITextSpellCheckingTypeYes];


text:
Q: Error using ps2pdf I used to work on linux in a virtual Box and now I'm using a computer with Ubuntu 16.04.
I have some ps files I need to convert to pdf and I used to run the command
ps2pdf file.ps file.pdf in my previous computer, but now it doesn't work, I get the following error:
/usr/bin/gs: symbol lookup error: /usr/lib/libgs.so.9: undefined symbol: FT_Property_Set

I tried using convert file.ps file.pdf and it doesn't work either, I get the error:
convert.im6: not authorized `sc1.ps' @ error/constitute.c/ReadImage/454.
convert.im6: no images defined `sc.pdf' @ error/convert.c/ConvertImageCommand/3044.

A: Finally, I followed the steps in the duplicate: How to tell libgs to use another freetype implementation?
However, I didn't have the file libfreetype.so.6.14.0 to replace the original file libfreetype.so.6, so I just deleted it (changed its name) and it worked. Don't know why it worked, but it did. Thanks everyone anyway!

A: Echo Paula's answer, remove or edit libfreetype.so.6. Reason mentioned in https://stackoverflow.com/questions/57396756/gnuplot-error-undefined-symbol-ft-property-set. I met similar error when I try to open rstudio on ubuntu.

rstudio: symbol lookup error:
  /usr/lib/rstudio/plugins/platforms/../../lib/libQt5XcbQpa.so.5:
  undefined symbol: FT_Property_Set

The following codes work for me:
cd /usr/local/lib
sudo mv libfreetype.so.6 libfreetype.so.abc


text:
Q: Can Flink Interval Join shares stream? I'm trying to understand IntervalJoin operation on Flink and got a question.
Let's assume we have three streams A, B and C.
Here, we interval join two streams each like A-C and B-C.
In java code, it would show like below.
    // join stream A and stream C
  SingleOutputStreamOperator<SensorReadingOutput> joined1 = A
            .intervalJoin(C)
            .between(Time.seconds(-1), Time.seconds(0))
            .process(new IntervalJoinFunction());

    // join stream B and stream C
  SingleOutputStreamOperator<SensorReadingOutput> joined2 = B
          .intervalJoin(C)
          .between(Time.seconds(-1), Time.seconds(0))
          .process(new IntervalJoinFunction());

As we see, stream C is joined twice.
Here, can the stream C be shared among two streams A and B?
That is, does the stream C exist as single or duplicated(copy) for each A and B?
I am confusing because of two points in IntervalJoin operation.

*

*Every time we call .process at last of interval join, we create new IntervalJoinOperator. I think stream C would be copied.

*In IntervalJoinOperator, the records are cleaned up using internal timer service that is triggered by the event time based watermark. Stream A and B would have different watermark and I think it would affect the stream C's retention period, so stream C should be copied and managed individually.

However, when I made a test code to see if three streams records with the same key are collected in same task instance, they do.
Anybody knows the fact? Thank you!

A: For someone who wonders same question, the answer is 'they don't share the stream'.
Instead, another duplicated stream is created for another IntervalJoin.
I've done some tests to print the buffer's address inside the IntervalJoinOperator.
For A-C and B-C joining, the same value of record C which is joined with A and B both shows different address.
If the stream is shared, address of record in stream C would be same.
I think this is because of two reasons.

*

*Whenever .intervalJoin is called for keyedStream, new IntervalJoinOperator is created and it contains its own buffer. New buffers would be created every time thus sharing the stream does not make sense.

*Also, the watermark of stream A and B would be different. The watermark decides the retention period of buffers in IntervalJoinOperator, thus sharing the buffer also does not make sense here.


text:
Q: Why this simple script in CasperJS doesn't work on bestbuy.com I'm doing some exercises with CasperJS and I'm stuck in a pretty simple exercise.
I don't know if bestbuy.com website blocks the connection in some way. I've tried some different websites and they just work fine.
The Title is not printed on the console and the phantomjs task doesn't exit from the task.
Here you have the simple script:

var casper = require('casper').create({
  verbose:true,
  logLevel:'debug',
  pageSettings:{
    loadImages: true,
    loadPlugins: false,
    userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
  }
});

var url = 'http://www.bestbuy.com/';

casper.start(url, function () {
  this.echo(this.getTitle());
});

casper.run();

Can somebody, please explain what is this happening?
Thanks :)

A: For some reason it looks like bestbuy might be blocking your useragent.
This works for me:-
var casper = require('casper').create({
  verbose:true,
  logLevel:'debug'
});

var url = 'http://www.bestbuy.com/';

casper.start(url, function () {
  this.echo(this.getTitle());
});

casper.run();

This outputs the title correctly


text:
Q: git push origin master:refs/heads/master what does this do When I create a new repo on my gitolite repository I always have to enter the following command before I can start pushing code to the server.
git push origin master:refs/heads/master
What does it do ?
My guess is that is has to do with the head reference not sure. Could someone explain it to me?

A: master:refs/heads/master is a refspec.
refspecs are of the form +<src>:<dst>
So here master is the ref on your local repo that you are pushing to the refs/heads/master refspec on the remote (origin). master is short for refs/heads/master actually.
In fact, you can just do git push origin master whereby it will push master on your local to master on remote. Only when you want to push to a different ref do you need to explicitly specify the destination ref.
Also just  git push has default behaviour too, which probably wouldn't have been the case before you did the first push and created a branch (master ) on the remote. So it would have seemed like you need to do the command you had mentioned. Refer to the manual

A: There's three parts to this command:
git push

This invokes the push command
origin

This names the remote to which you are pushing. This is either one of the named remotes stored in .git/config (you can list these with git remote), a URL, or the token . which means the current repository.
master:refs/heads/master

This is called a "refspec", and you can read about it in the man page for git push. But in general, it's comprised of two parts, separated by a colon. The first part is the name of a local branch, and the second part is the name of a branch on the remote repository (in this case, origin). This particular refspec could be shortened to master:master.
In general, one can shorten refspecs even further. Just specifying master as the refspec is equivalent to using the same name on the remote, so master is the same as master:master.

A: The default behavior of git push, which is presumably what you describe as "pushing code to the server", is to only push local branches that have a matching branch, by name, on the remote you're pushing to. When you create a new repo, it has no branches in it, so a simple git push will push nothing. You have to explicitly push a branch by name first. Thereafter, the default behavior will work as you expect it to.
P.S. Actually, you only have to git push origin master. What it does is push your local master to the gitolite repo as master, since you didn't specify a different name. If you said git push origin master:foo, then the branch you locally call "master" would be known as "foo" on gitolite.
P.P.S. You can switch default push behavior between "nothing", "matching" (the default), "trackings"/"upstream", and "current". See the settings for "push.default" on the git-config man page.

A: It sets up tracking for you. You can use the shorthand for this:
git push origin master

The part after the colon is the name of the branch on the remote repo. If you omit it, git assumes you want the same name.
Hope this helps.


text:
Q: Open Graph api for feed returning inconsistent results Called the https://graph.facebook.com/{id}/feed url is randomly missing data.
Here's what I did

*

*Create a test user for my sandbox mode app with publish_stream and read_stream permissions

*Add a post to their wall via POST to graph.facebook.com/{id}/feed?access_token={token}

*Login as test user and confirm post was added to their news feed

*GET on graph.facebook.com/{id}/feed to view JSON data

So when I hit the feed, sometimes the successfully created Feed Post is in the JSON, and sometimes it's not.  Continually hitting that API endpoint (i.e. hitting refresh over and over in my browser) will have the data pop in and out in no discernable pattern.
I have no idea what I could be doing wrong, or if it's just Facebook for that matter.  What could be the problem?

A: I experienced this as well. My solution: Add 'user_groups' to the list of required permissions. Log out, log in again and everything should work.


text:
Q: Swift Package Manager - Realm as a sub dependency of a integrated package - Testing not possible in the main project Setup
iOS, xCode 13, Realm 10.20
MainProject integrates two swift packages using Swift Package Manager: LayerPersistence and LayerNetwork.
LayerPersistence packages has a dependency on

*

*Realm

LayerNetwork packages has a dependency on

*

*Alamofire

MainProject builds and runs without issues.
Tests for MainProject do not build. Generates the following:
Error: Missing required modules: 'Realm.Private', 'Realm'

When I exclude LayerPersistence from the MainProject -> Tests run with no issues.
What I tried and it didn't work
I have tried to manually map the module with: -fmodule-map-file=.....some path to file.....Realm.modulemap but without success.
I have tried to include Realm manually in link binary with libraries of the test targets.
What works
Downgrading to Realm Version 5.5.2 in the LayerPersistence and manually linking Realm to all tests targets of the MainProject via
Build Phases -> Link Binary With Libraries

does the trick, but keeps me out of new Realm Versions.
Objective
To have the most recent version of Realm in the package integrated via SPM and still be able to run test in the MainProject

Note:
Tests in LayerPersistence and LayerNetwork run without issues.
There are some solutions in Internet but they do not resolve issues with the newer versions of Realm:
https://github.com/apple/swift-nio/issues/1128
https://github.com/realm/realm-swift/issues/6301
"Missing required module 'XYZ'" on Unit Tests when using Swift Package Manager


text:
Q: Pointing Jenkins to Use Another Plugin Repository Good afternoon,
As I understand Jenkins, if I need to install a plugin, it goes to Jenkins Plugins
The problem I have is Jenkins is installed on a closed network, it cannot access the internet. Is there a way I can download all of the plugins, place them on a web server on my local LAN, and have Jenkins reach out and download plugins as necessary? I could download everything and install one plugin at a time, but that seems a little tedious.

A: You could follow some or all of the instructions for setting up an artifactory mirror for the plugin repo.
It will need to be a http/https server and you will find that many plugins have a multitude of dependencies

A: The closed network problem:
You can take a cue from the Jenkins Docker install-plugins.sh approach ...
This script takes as input a list of plugins, and optionally versions (eg: $0 workflow-aggregator:2.6 pipeline-maven:3.6.5 job-dsl:1.70) and will download all the plugins and dependencies into a working directory.
Our approach is to create a file (under version control) and redirect that to the command line input (ie: install-plugins.sh $(< plugins.lst).
You can download from where you do have internet access and then place on your network, manually copying them to your ${JENKINS_HOME}/plugins directory and restart the instance.
The tedious list problem:
If you only specify top-level plugins (ie: what you need), every time you run the script, it will resolve the latest dependencies. Makes for a short list, but random dependencies if they get updated at https://updates.jenkins.io. You can use a two-step approach to address this. Use the short-list to download the required plugins and dependencies. Store the generated explicit list for future reference or repeatability.