text:
Q: Configuration Issue with Tycho/Maven: "Tycho build extension not configured" I have been following Vogella's tutorial (http://www.vogella.com/articles/EclipseTycho/article.html) on using Tycho to set up a Maven build environment for my project. My project is already quite big with several plugins, features and an update site, however I managed to get mvn clean and mvn compile to work fine, and followed the tutorial all the way up to mvn install. The issue I am facing now is confusing. I consistently get the following error:
[INFO] --- tycho-p2-director-plugin:0.16.0:materialize-products (materialize-products) @ parent ---
[DEBUG] Configuring mojo org.eclipse.tycho:tycho-p2-director-plugin:0.16.0:materialize-products from plugin realm ClassRealm[plugin>org.eclipse.tycho:tycho-p2-director-plugin:0.16.0, parent: sun.misc.Launcher$AppClassLoader@35ce36]
[DEBUG] Configuring mojo 'org.eclipse.tycho:tycho-p2-director-plugin:0.16.0:materialize-products' with basic configurator -->
[DEBUG]   (f) directorRuntime = internal
[DEBUG]   (f) installFeatures = true
[DEBUG]   (f) profile = DefaultProfile
[DEBUG]   (f) project = MavenProject: com.micrium.configbuilder:parent:1.1.0-SNAPSHOT @ C:\Documents and Settings\Thomas Sylvester\git\plugin-suite\com.micrium.configbuilder.tycho.master\pom.xml
[DEBUG]   (f) session = org.apache.maven.execution.MavenSession@1335332
[DEBUG]   (f) source = targetPlatform
[DEBUG] -- end configuration --
[INFO] No product definitions found. Nothing to do.
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] parent ............................................ FAILURE [0.201s]

Snipped the list of plugins from this stack trace. They were all skipped. Parent had the failure.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 37.735s
[INFO] Finished at: Thu Feb 21 06:42:47 PST 2013
[INFO] Final Memory: 65M/158M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.eclipse.tycho:tycho-p2-director-plugin:0.16.0:materialize-products (materialize-products) on project parent: Execution materialize-products of goal org.eclipse.tycho:tycho-p2-director-plugin:0.16.0:materialize-products failed: Tycho build extension not configured for MavenProject: com.micrium.configbuilder:parent:1.1.0-SNAPSHOT @ C:\Documents and Settings\Erika Redmark\git\plugin-suite\com.micrium.configbuilder.tycho.master\pom.xml -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.eclipse.tycho:tycho-p2-director-plugin:0.16.0:materialize-products (materialize-products) on project parent: Execution materialize-products of goal org.eclipse.tycho:tycho-p2-director-plugin:0.16.0:materialize-products failed: Tycho build extension not configured for MavenProject: com.micrium.configbuilder:parent:1.1.0-SNAPSHOT @ C:\Documents and Settings\Erika Redmark\git\plugin-suite\com.micrium.configbuilder.tycho.master\pom.xml
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:225)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
        at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
        at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: org.apache.maven.plugin.PluginExecutionException: Execution materialize-products of goal org.eclipse.tycho:tycho-p2-director-plug
in:0.16.0:materialize-products failed: Tycho build extension not configured for MavenProject: com.micrium.configbuilder:parent:1.1.0-SNAPSHO
T @ C:\Documents and Settings\Erika Redmark\git\plugin-suite\com.micrium.configbuilder.tycho.master\pom.xml
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:110)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
        ... 19 more
Caused by: java.lang.IllegalStateException: Tycho build extension not configured for MavenProject: com.micrium.configbuilder:parent:1.1.0-SN
APSHOT @ C:\Documents and Settings\Erika Redmark\git\plugin-suite\com.micrium.configbuilder.tycho.master\pom.xml
        at org.eclipse.tycho.core.utils.TychoProjectUtils.getTargetPlatform(TychoProjectUtils.java:63)
        at org.eclipse.tycho.p2.facade.RepositoryReferenceTool.addTargetPlatformRepository(RepositoryReferenceTool.java:116)
        at org.eclipse.tycho.p2.facade.RepositoryReferenceTool.getVisibleRepositories(RepositoryReferenceTool.java:97)
        at org.eclipse.tycho.plugins.p2.director.DirectorMojo.getTargetPlatformRepositories(DirectorMojo.java:167)
        at org.eclipse.tycho.plugins.p2.director.DirectorMojo.getSourceRepositories(DirectorMojo.java:145)
        at org.eclipse.tycho.plugins.p2.director.DirectorMojo.execute(DirectorMojo.java:93)
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
        ... 20 more
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException

I see that the root of the cause is that the Target Platform is somehow undefined. But when I look up Target Platform on the Eclipse wiki (http://wiki.eclipse.org/Tycho/Target_Platform)  it states:

In order allow Tycho to resolve the project dependencies against
  anything from a specific p2 repository, add that repository in the
   section of the POM... In terms of the target platform,
  this means that the entire content of the p2 repositories specified in
  this way become part of the target platform.

I have that section in my POM. In fact, here is the full content of my parent POM (defined in a seperate general project as per the tutorial). I omitted only the declaration of all my modules:
<?xml version="1.0" encoding="UTF-8"?>
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.micrium.configbuilder</groupId>
    <artifactId>parent</artifactId>
    <version>1.1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <modules>
        ... bunch of modules ...
    </modules>

    <properties>
        <tycho-version>0.16.0</tycho-version>
    </properties>

    <repositories>
        <repository>
            <id>helios</id>
            <layout>p2</layout>
            <url>http://download.eclipse.org/releases/helios</url>
        </repository>
    </repositories>

    <build>
        <plugins>

            <plugin>
                <groupId>org.eclipse.tycho</groupId>
                <artifactId>tycho-maven-plugin</artifactId>
                <version>0.16.0</version>
                <extensions>true</extensions>
            </plugin>
            <plugin>
                <groupId>org.eclipse.tycho</groupId>
                <artifactId>tycho-p2-director-plugin</artifactId>
                <version>0.16.0</version>
                <executions>
                    <execution>
                        <id>materialize-products</id>
                        <goals>
                            <goal>materialize-products</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>archive-products</id>
                        <goals>
                            <goal>archive-products</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>

    </build>

</project>

Have I missed something? I seemed to have defined what the documentation addresses as the target platform. Am I even seeing the right issue?

A: The problem is that you are trying to execute the tycho-p2-director-plugin in your parent POM. This won't work – the plug-in can only be executed in modules with eclipse-repository packaging type. Moving the configuration tycho-p2-director-plugin configuration into your eclipse-repository module(s) will solve the problem described here.
Unfortunately, Tycho doesn't give a good error message in this case. It states "Tycho build extension not configured", but in fact it is configured but is just not executed for the packaging type pom.


text:
Q: How can I plot NDVI time series from multiple polygon into one graph with a single line instead of one line each polygon? I want to plot NDVI time series from multiple polygon into one graph with a single line instead of one line for each polygon.
Here's part of my code:
var countries = ee.FeatureCollection("USDOS/LSIB_SIMPLE/2017");
var TanzaniaBoundary = countries.filter(ee.Filter.eq('country_na','Tanzania'));

// Create image collection of S-2 imagery for the perdiod 2020
var S2 = ee.ImageCollection("COPERNICUS/S2_SR")

//filter start and end date
.filterDate('2020-01-01', '2020-12-31')

//filter cloud cover
.filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE',20))

//filter according to drawn boundary
.filterBounds(TanzaniaBoundary);

//Map.addLayer(S2,{bands: ['B4', 'B3', 'B2'],min:0, max: 3000}, 'True colour image');
Map.addLayer(table, {color: 'red'}, 'cassava point');

// Function to calculate and add an NDVI band
var addNDVI = function(image) {
return image.addBands(image.normalizedDifference(['B8', 'B4']));
};

// Add NDVI band to image collection
var S2 = S2.map(addNDVI);
// Extract NDVI band and create NDVI median composite image
var NDVI = S2.select(['nd']);
var NDVImed = NDVI.median(); //I just changed the name of this variable ;)

// Create palettes for display of NDVI
var ndvi_pal = ['#d73027', '#f46d43', '#fdae61', '#fee08b', '#d9ef8b',
'#a6d96a'];

// Create a time series chart.
var plotNDVI1 = ui.Chart.image.seriesByRegion(S2,North,ee.Reducer.mean(),
'nd',500,'system:time_start', 'system:index')
              .setChartType('LineChart').setOptions({
                title: 'NDVI short-term time series',
                hAxis: {title: 'Date'},
                vAxis: {title: 'NDVI'}
});

// Display.
print(plotNDVI1);

// Display NDVI results on map
Map.addLayer(NDVImed.clip(North), {min:-0.5, max:0.9, palette: ndvi_pal}, 'NDVI')

and complete in following link:
https://code.earthengine.google.com/33153e20a937e5a7b5360bb0696bfa4b

A: You need to share the table so the code will work,
I made an app that create NDVI chart for polygon/s
https://harelg25.users.earthengine.app/view/ndvi-chart
I can share the code if this what you looking for

redpajama_set_name: RedPajamaStackExchange


text:
Q: From Google Analytics to (nearly) access.log Context: Many people want to export data from Google Analytics and migrate to another analytics tool, but there isn't a ready-to-use tool yet, see this issue of a well-known open-source project.
It seems that it's not possible to get raw logs from Google Analytics, as stated in this question or here as well.
Of course, one could use his own Apache access.log files, but these files are not always available (for example I haven't stored the logs from 5 years ago, because I knew everything was in Google Analytics, now I see my mistake!).

A partial solution could be: let's export Google Analytics data to Apache-like access.log files. Then this data can be easily imported in any analytics tool.
Question: I have explored the Google Analytics GUI, but I don't find a feature that allows to batch export all past traffic as a log file in the form (include the referrer, user agent, etc.)
mywebsite.com:5.130.131.132 - - [23/Oct/2016:12:08:58 +0200] "GET /bla/abc.php HTTP/1.1" 302 241 "http://www.blabla.com" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"

Is there a feature in Google Analytics that allows to do this?

A: No, for various reasons:

*

*Google Analytics does not expose IP addresses

*GA records tracking requests to Google servers, not requests to you own server, so GA would not know about the request method for a resource

*dito for response status (if it has arrived at GA its 200 by default, else the hit would not have been recorded) and content length

*I do not think GA exposes the full User Agent String

You would either have to add this information via custom dimensions and/or override the sendHitTask to send a copy of the (unprocessed) data to a tracking server of your own. In that case you'd have to implement GA on all of your error pages (for 40x and 50x error statuses) and of course it would only work for future data, it would still not help with data already collected.
The Premium version of GA (recently renamed Google Analytics 360) allows (via BigQuery) for more data fields to be exported, but that would set you back 150 000 USD per year, so it's probably not an option.


text:
Q: Dealing with multiple Azure Pipelines with multiple Environment targets I'm trying to set up a pipelines template to streamline releases. We have numerous repos, and multiple team environments that need to utilize this. The release pipeline should look like this:
Build -> Dev Deploy -> Test Deploy -> UAT Deploy -> Prod Deploy
When the user manually runs the pipeline they should be allowed to specify which environment they are running for (ie: Team 1, Team 2; then the Dev Deploy step knows to use the Team 1 Dev environment for example). I first attempted to use a separate variable template that contained the environments in one spot. This does not work according to Azure Pipelines parameter value from variable template, other than allowing users to type a freeform string which is not ideal. The workarounds as far as I know are:

*

*Add the list of environments to every azure-pipelines.yml (not feasible as we have many repos and have environments changing frequently)

*Provide a freeform text box that the user can type in their environment (not a good solution as it allows typos and is generally just a bad user experience)

This is my current workaround, which "works" but is not ideal. UAT/Prod is not tied to a successful Test stage completion, because it would require all Test stages to succeed, and we typically will only deploy to the team's environment that is currently working on the repo. And since not all stages will always run, an app deployed to prod will still show the pipeline is still waiting on stages to run with the blue clock.

- stage: DeployToTeam1Dev
  displayName: Deploy to Team1 Dev
  dependsOn:
  - Build
  jobs:
  - template: ../../TaskGroups/DotNetCore/webDeploy-v2.yml
    parameters:
      environment: Team1 Dev
      testRegion: true
      siteName: ${{ parameters.siteName }}
      virtualAppName: ${{ parameters.virtualAppName }}

- stage: DeployToTeam1Test
  displayName: Deploy to Team1 Test (MIVA)
  dependsOn:
  - DeployToTeam1Dev
  jobs:
  - template: ../../TaskGroups/DotNetCore/webDeploy-v2.yml
    parameters:
      environment: Team1 Test
      testRegion: true
      siteName: ${{ parameters.siteName }}
      virtualAppName: ${{ parameters.virtualAppName }}

- stage: DeployToTeam2Dev
  displayName: Deploy to Team2 Dev
  dependsOn:
  - Build
  jobs:
  - template: ../../TaskGroups/DotNetCore/webDeploy-v2.yml
    parameters:
      environment: Team2 Dev
      testRegion: true
      siteName: ${{ parameters.siteName }}
      virtualAppName: ${{ parameters.virtualAppName }}

- stage: DeployToTeam2Test
  displayName: Deploy to Team2 Test (UAT)
  dependsOn:
  - DeployToTeam2Dev
  jobs:
  - template: ../../TaskGroups/DotNetCore/webDeploy-v2.yml
    parameters:
      environment: Team2 Test
      testRegion: true
      siteName: ${{ parameters.siteName }}
      virtualAppName: ${{ parameters.virtualAppName }}

- stage: DeployToTeam3Dev
  displayName: Deploy to Team3 Dev
  dependsOn:
  - Build
  jobs:
  - template: ../../TaskGroups/DotNetCore/webDeploy-v2.yml
    parameters:
      environment: Team3 Dev
      testRegion: true
      siteName: ${{ parameters.siteName }}
      virtualAppName: ${{ parameters.virtualAppName }}

- stage: DeployToTeam3Test
  displayName: (NYI) Deploy to Team3 Test
  dependsOn:
  - DeployToTeam3Dev
  jobs:
  - job: Team3TestDeploy
    timeoutInMinutes: 10
    pool:
      vmImage: 'ubuntu-latest'
    steps:
    - bash: echo "Team3 Test does not currently exist. Skipping this stage"

- stage: DeployToTeam4Dev
  displayName: Deploy to Team4 Dev
  dependsOn:
  - Build
  jobs:
  - template: ../../TaskGroups/DotNetCore/webDeploy-v2.yml
    parameters:
      environment: Team4 Dev
      testRegion: true
      siteName: ${{ parameters.siteName }}
      virtualAppName: ${{ parameters.virtualAppName }}

- stage: DeployToTeam4Test
  displayName: (NYI) Deploy to Team4 Test
  dependsOn:
  - DeployToTeam4Dev
  jobs:
  - job: Team4TestDeploy
    timeoutInMinutes: 10
    pool:
      vmImage: 'ubuntu-latest'
    steps:
    - bash: echo "Team4 Test does not currently exist. Skipping this stage"

- stage: DeployToUAT
  displayName: (NYI) Deploy to UAT
  dependsOn:
  - Build
  jobs:
  - job: UATDeploy
    timeoutInMinutes: 10
    pool:
      vmImage: 'ubuntu-latest'
    steps:
    - bash: echo "UAT is not yet implement"

- stage: DeployToProd
  displayName: Deploy to Prod
  dependsOn:
  - DeployToUAT
  jobs:
  - template: ../../TaskGroups/DotNetCore/webDeploy-v2.yml
    parameters:
      environment: Prod
      testRegion: false
      siteName: ${{ parameters.siteName }}
      virtualAppName: ${{ parameters.virtualAppName }}

Has anyone else ran in to a similar problem and come up with a solution besides hardcoding a list of environments in every azure-pipelines.yml? Thanks for the help in advance.


text:
Q: How to fix "ImportError: cannot import name 'setup' form 'cx_Freeze' " I'm sorry not to use English well.
I made a game with Python 3.7 and pygame.
I tried to build an exe with cx_Freeze version 5.1.1 but an ImportError happens...
Someone uploaded a question with the same error but not resolved: cx_Freeze- ImportError: cannot import name setup.
I tried to change from cx_Freeze import setup, Executable to import cx_Freeze and then use cx_Freeze.setup and cx_Freeze.Executable, but then an error setup not in cx_Freeze happens...
This is my install.py code
from cx_Freeze import setup, Executable
import cx_Freeze
setup(
    name = "hello",
    options={"build_exe": {"packages":["pygame"],
                           "included_files":["UFO.bmp","UFO_Monster.bmp","boss_Atack.jpg","boss.png","background_1.png","bullet.png","boom.png","shot.wav","explosion.wav","mybgm.wav","D2coding.ttf","Meteor.png"]}},
    version = "0.1",
    executables = [
    cx_Freeze.Executable('Main.py'),
    cx_Freeze.Executable('Boss_class.py'),
    cx_Freeze.Executable('Boss_class_Attack.py'),
    cx_Freeze.Executable('Meteor.py'),
    cx_Freeze.Executable('UFO_class.py'),
    cx_Freeze.Executable('UFO_Monster.py')
]
)

This is the error message :

Traceback (most recent call last):
        File "cx_Freeze.py", line 2, in
          from cx_Freeze import setup, Executable
        File "C:\Users```\source\repos\PythonGame\cx_Freeze.py", line 2, in
      from cx_Freeze import setup, Executable
      ImportError: cannot import name 'setup' from 'cx_Freeze' (C:\Users```\source\repos\PythonGame\cx_Freeze.py)

A: Do you have a file named cx_Freeze.py directly in your source directory, instead of importing through a package directory and possibly through the one installed with pip?
The path shows cx_Freeze.py and not the expected path from an installed package.


text:
Q: ping удаленного компьютера на Lua Интересует такой вопрос. Как пропинговать с портом на Lua удаленный компьютер/сервер в сети если неизвестно на какой ОС будет использоваться скрипт и очень критично быстродействие пинга?
Пробовал эту команду io.popen() но проблема в том что если комп не доступен, скрипт может зависнуть с блокировкой потока на некоторое время, что в моем случае недопустимо.
Нужно простое и быстрое решение которое пинговало на Lua удаленный комп/серв и если он не ответил сразу то не ждать его, а сразу обрывать связь и возвращать отказ. Пинг возможен как по IP адресу так и по имени с портом например - google.com 80 (port).
Никак не могу найти в интернете решение этой задачи.

A: Можно рассмотреть попытку открытия порта через сокет, если доступен порт, то соединение состоится, таймаут сами укажите:
require("socket")

local host = "87.250.250.242"

local conn = socket.tcp()
conn:settimeout(1, 't') -- таймаут 1 сек
local res = conn:connect(host, 80)
if res then     print("Connected")
else    print('Error connect')
end

conn:close()

-- Name to IP
local name = socket.dns.tohostname(host)
print (host, name)
-- IP to Name
local adr = "google.com"
local info = socket.dns.toip(adr)
print(adr,info)

результат:
Connected
87.250.250.242  ya.ru
google.com  142.251.1.138

A: Для виндовс всё сложно, но можно попробовать cygwin.
Для посиксов (линукс, мак, бсд, cygwin)
#!/usr/bin/env lua

local M = require 'posix.sys.socket'

if M.SOCK_RAW and M.SO_BINDTODEVICE then
   -- Open raw socket

   local fd, err = M.socket(M.AF_INET, M.SOCK_RAW, M.IPPROTO_ICMP)
   assert(fd, err)

   -- Optionally, bind to specific device

   local ok, err = M.setsockopt(fd, M.SOL_SOCKET, M.SO_BINDTODEVICE, 'wlan0')
   assert(ok, err)

   -- Create raw ICMP echo (ping) message

   local data = string.char(0x08, 0x00, 0x89, 0x98, 0x6e, 0x63, 0x00, 0x04, 0x00)

   -- Send message

   local ok, err = M.sendto(fd, data, {family=M.AF_INET, addr='8.8.8.8', port=0})
   assert(ok, err)

   -- Read reply

   local data, sa = M.recvfrom(fd, 1024)
   assert(data, sa)

   if data then
      print('Received ICMP message from ' .. sa.addr)
   end
end

Для определения имени добавь
r, err = M.getaddrinfo('www.lua.org', 'http', {family=M.AF_INET, socktype=M.SOCK_STREAM})
r[1].addr

Для установки таймаутов нужно добавить в этот код select и неблокирующие сокеты.
https://luaposix.github.io/luaposix/examples/ping.lua.html
https://luaposix.github.io/luaposix/examples/socket.lua.html
Пинг работает без порта, но если мы говорим о syn scan атаке, то это уже другой код.
Можно в этом случае обойтись более простой luasocket но будет блокировка до таймаута.


text:
Q: A question about Green function in Laplace equations Let $\Omega$ open bounded be given and $G(x,y)$ denote the Green function in Evans setting. That is, we have
$$ \Delta_yG(x,y)=\delta_{x-y} $$
and
$$ G(x,y)=0 $$
if $y\in\partial\Omega$.
Now for $u$ we define
$$ u(x):=\int_\Omega G(x,y)f(y)dy $$
where $f(y)$ is bounded and integrable. I want to prove that
$$ u(x)\to0 \,\,\,\text{ as }x\to \partial\Omega$$
This is intuitively right but I can not prove it in details... Please help me with that. Thank you!

A: Here's an outline
First of all note that, by the maximum principle, there is a constant $c=c_n$ (the normalization constant in the definition of the fundamental solution for the laplacian), so that $|G(x,y)|\leq c|x-y|^{2-n}$. Therefore, by a variant of the dominated convergence theorem, it's enough to show that
$$
\int_\Omega \frac{|f(y)|}{|x-y|^{n-2}} dy \to \int_\Omega \frac{|f(y)|}{|z-y|^{n-2}}dy, \qquad \text{ when } x\to z\in \partial \Omega.
$$
This is easy to see: Clearly the integrands converge pointwise a.e. in $\Omega$, and moreover the functions $f_x(y)=|x-y|^{2-n}$ are uniformly bounded (in $x$) in $L^p(\Omega)$ for $p<n/(n-2)$, and thus they're weakly convergent as $x\to z$ by uniqueness of the pointwise and weak limits. But since $f\in L^\infty(\Omega) \subset L^{p'}(\Omega)$, we conclude the desired limit.


text:
Q: Executing commands by visiting webpage? I run an Ubuntu server, I have two gameservers on this which need semi-regular updates.
They are run under a gameserver-specific account named 'gs', in screens.
I have a 'runupdate.sh' script which contains the following line:
/var/gs/steamcmd/one.sh;/var/gs/steamcmd/two.sh; (one line because windows CR/LF was throwing errors)
one.sh/two.sh are very similar scripts, the contents of one.sh are:
screen -r tf2_1 -X quit;
/var/gs/steamcmd/steamcmd.sh +runscript /var/gs/steamcmd/update_tf2_1.txt;
screen -d -m -S tf2_1 /var/gs/tf2/1/srcds_run -game tf -port 27015 +sv_pure 2 +map cp_badlands +maxplayers 24;

these scripts work perfectly when run as the 'gs' user.
for access purposes I would like the gameservers to always be run in screens assigned to the 'gs' account.
currently, I would like a php script to run when I visit a webpage on www.mysite.com/admin/restartservers12345 which will execure the 'runupdate.sh' script and issue a restart of the servers while updating them, my updateservers12345.html document currently looks like:
<!DOCTYPE html>

<?php
echo exec('/var/gs/runupdate.sh')
?>

Server Updating...

the issue is that this script seems to be run as 'www-data' or the otherwise default Apache account, which means it cannot access the gameserver screens running on 'gs'.
currently I would like to have a box onscreen into shich people need to type the password for the gs account, and then hit enter, after which a script like
exec(echo $textboxpassword | su -s - gs -c '/var/gs/runupdate.sh')
will run, effectively running that script as the 'gs' account.
currently when trying to run that command through ssh I get an error su: must be run from a terminal and I can't seem to confirm if any of that php code is being executed properly on my server.
any help would be much appreciated. thank you.

A: you should use "sudo" instead of "su"
Add user www-data to sudoers list, you even can allow only single command '/var/gs/runupdate.sh' to execute from www-data as sudoer.
/etc/sudoers.d/www-data
www-data ALL=(ALL) NOPASSWD:  /var/gs/runupdate.sh

Update 1:
You can use
sudo -u gs bash -c '/var/gs/runupdate.sh'

And it will execute runupdate.sh from gs user
You can allow execution without password by follow lines at /etc/sudoers.d/www-data
www-data ALL=(gs) NOPASSWD:  /var/gs/runupdate.sh


text:
Q: $f(g(h(x)))=0$ has $8$ real roots Find all quadratic polynomials $f(x),g(x)$ and $h(x)$ such that the polynomial $f(g(h(x)))=0$ has roots $1,2,3,4,5,6,7$ and $8$.
I don't know what to do. Making a $8$ degree equation is quite tedious. Thanks.

A: For any two distinct numbers $r_1, r_2$, there is a quadratic $f$ with these as roots, and in fact the general such $f$ is $a (x - r_1)(x - r_2)$ where $a$ is a nonzero constant.  So now you want
$g(h(x))$ to take value $r_1$ on four of $1,2,\ldots,8$ and $r_2$ on the other four. Now the four $x$'s (let's say $x_1, \ldots, x_4$) for which $g(h(x)) = r_1$ must correspond to two different values of $h$, say $s_1, s_2$ with $g(s_1) = g(s_2) = r_1$, $h(x_1) = h(x_2) = s_1$ and $h(x_3) = h(x_4) = s_2$; similarly the four $x$'s ($x_5$ to $x_8$) for which $g(h(x)) = r_2$ must correspond to two other values of $h$, with $h(x_5) = h(x_6) = s_3$, $h(x_7) = h(x_8) = s_4$, $g(s_3) = g(s_4) =r_2$.  Now two points where a quadratic takes the same value must be symmetric with respect to the critical point of the quadratic.  Thus $x_1 + x_2 = x_3 + x_4 = x_5 + x_6 = x_7 + x_8$.
But $x_1, x_2, \ldots, x_8$ must be $1,2,\ldots, 8$ in some order.  The only way to split up $1,2,\ldots,8$
into pairs with the same sum is $(1,8), (2,7), (3,6), (4,5)$.
So let's say $x_1 = 1$ and $x_2 = 8$.  Thus $h(x) = a (x - 9/2)^2$ for some constant $a$, making $h(1)=h(8) = 49 a/4$, $h(2) = h(7) = 25a/4$,
$h(3) = h(6) = 9a/4$, $h(4)=h(5) = a/4$.  But those four values can't be split into two pairs with the same sum.  So the problem (assuming you're asking for non-constant quadratics) has no solution.  Of course there are lots of solutions where $f$, $g$ or $h$ is constant.
Are you sure you don't want the roots to be, say, $1,2,5,8,10,13,16,17$?

A: The polynomial $$F(x)=\prod_{1\le k\le 8}(x-k)$$ has a derivative equal to
$$4(2x-9)(x^6-27x^5+288x^4-1539x^3+4299x^2-5886x+3044)$$ where the second 6-degree factor is irreducible (verify this, for example, in WolframAlpha).
Therefore if $F(x)=f(g(h(x)))$  then
$$F'(x)=f'(g(h(x)))\cdot g'(h(x))\cdot h'(x)$$ which is a contradiction because $F'(x)$ is a product of only two irreducible factors.


text:
Q: Java: how to resize an image on the gpu I have an application that needed to resize a lot of big grayscale images (up to 4000 * 4000).
I don't want to use java graphics because it works on the CPU. Is there a way to perform resize on the GPU similar to directX9::StretchRect.
In stretchRect I get the resize and the rendering in a single step.

A: The problem with scaling that makes it (sometimes) not that friendly to parallelization (Which is the reason people use GPUs) is the need for interpolation during scaling. More specifically, the averaging of color values from surrounding pixels to get the value for the new pixel (when expanding) or averaging all surrounding pixels intelligently into a single color value that you try and represent multiple pixels by (when shrinking).
This requires you to know all the values around a given pixels which means all the rows above/below/left/right of the pixels need to be ready-to-be-read.
I am sure you can do image scaling on the GPU, I just don't think you'll get high-quality scaling that is super-parallelized in which case doing it on the CPU is likely what you want here.
If there is some unique aspect to the image scaling that you are doing where it can be seriously parallelized and each row or set of rows can be averaged out without the image data round them, then yes that would be an excellent thing to push to the GPU.


text:
Q: How to show html in file in react-pdf component?     import sample from './response.pdf'

React-pdf Component.
<Document
    file={sample}
     onLoadSuccess={this.onDocumentLoad} >
    <Page pageNumber={pageNumber} />
 </Document>

I am using manual PDF in the document component. So its working fine
Is there any way to show Html file in file key.
example: I have a html like this
sample1=Html code etc ...
<Document
    file={sample1}
     onLoadSuccess={this.onDocumentLoad} >
    <Page pageNumber={pageNumber} />
 </Document>

This I tried, Can anyone guide be how to use this.

A: This is just a PDF viewer that takes whole file as a parameter and displays it to you.
To convert an HTML string/file to PDF you would need another package that uses string content as stream and converts it for you.
You can have a look at this package available
html-to-pdf
Usage
var htmlToPdf = require('html-to-pdf');
var html = ...; //Some HTML String from code above

htmlToPdf.convertHTMLString(html, 'path/to/destination.pdf',
    function (error, success) {
        if (error) {
            console.log('Oh noes! Errorz!');
            console.log(error);
        } else {
            console.log('Woot! Success!');
            console.log(success);
        }
    }
);


text:
Q: Custom wait condition in boto3 for efs boto3 provides default waiters for some services like EC2, S3, etc. This is not provided by default for all services. Now, I've a case where an EFS volume is created and the lifecycle policy is added to the file system. The EFS creation takes some time and the lifecycle policy isn't in the required efs state. i.e., efs created.
How to wait for EFS to be created in a python boto3 code, so that policies can be added?

A: Looks like a waiter doesn't exist for this, but you can create your own customer waiters like this:
import boto3
from botocore.waiter import WaiterModel
from botocore.waiter import create_waiter_with_client

client = boto3.client('efs')
waiter_name = "LifeCycleCompleted"
waiter_config = {
    "version": 2,
    "waiters": {
        "LifeCycleCompleted": {
            "operation": "DescribeLifecycleConfiguration",
            "delay": 60, # Number of seconds to delay
            "maxAttempts": 5, # Max attempts before failure
            "acceptors": [
                {
                    "matcher": "path",
                    "expected": lifecycle_policy,
                    "argument": "length(LifecyclePolicies[]) > `0`",
                    "state": "success"
                }
            ]
        }
    }
}
waiter_model = WaiterModel(waiter_config)
efs_lifecycle_waiter = create_waiter_with_client(waiter_name, waiter_model, client)

efs_lifecycle_waiter.wait(FileSystemId='MyFileSystemId')

A: Or Use something simpler as mentioned by @jordanm
import time
import boto3

efs_client = boto3.client('efs')

filesystem_status=""
while filesystem_status != "available":
    response = efs_client.describe_file_systems(
            FileSystemId=file_system_id,
            )
    filesystem_status=response["FileSystems"][0]["LifeCycleState"]
    print(f"{file_system_id} {filesystem_status} .... waiting")
    time.sleep(20)


text:
Q: Stuck in understanding asynchronous behavior of node js I'm learning node js callbacks and asynchronous behavior from this site. From the examples given, I've written following code to understand it better.
function callbackTester (callbackFn){
    console.log('From callback tester.');
    callbackFn();
}

function pollingWait(){
    while (true) {}
}

callbackTester(() => {
    console.log('From anonymous function.');
    setTimeout(()=>{
        console.log("I'm waiting!");
    }, 500);
    // pollingWait();
});
console.log('I am the last one');

Now, when I comment out pollingWait() function, it works as expected. It gives following output:
From callback tester.
From anonymous function.
I am the last one
I'm waiting!

Now when I comment out the setTimeout function and add pollingWait(),  program goes in infinite loop. I think this is also an expected behavior as node js is single threaded and cannot avoid infinite loops. So how this asynchronous behavior works under the hood?
How it decides to when to continue execution and when not to? Is it possible to make my own function which acts as asynchronous like setTimeout?

A:
I think this is also an expected behavior as node js is single threaded and cannot avoid infinite loops.

Node.js isn't single-threaded anymore, but there is just one main thread unless you create worker threads.

So how this asynchronous behavior works under the hood?

Node.js's main thread works on a loop: Your top-level code runs and returns, then any queued action (such as a timer callback) is run and returns, and then the next queued action runs and returns, etc. That's how setTimeout works: When it's time for the timer to fire, the event loop sees that and queues a call to the timer callback. Also note that while Node.js has only one main JavaScript thread by default, that doesn't mean Node itself is single-threaded. In particular it may do I/O processing on another internal thread.

Is it possible to make my own function which acts as asynchronous like setTimeout?

Only by using something that already provides asynchronous behavior and wrapping it. Those would include:

*

*setTimeout

*setImmediate

*process.nextTick

*A promise's then or catch callback

At first glance you might think async functions do that, but they don't, really: The code in an async function runs synchronously up until the first time it waits on a promise resolution (or up until it returns). So the asynchronousness is really just the same as the last bullet point above: A then or catch callback.
What you can't do (without a worker thread) is busy-wait like your pollingWait does, because nothing else can happen on the thread that busy-wait is running on.

A: Try this thing:
let done = false;

setTimeout(() => {
  done = true
}, 5);

const eventLoopQueue = () => {
  return new Promise(resolve =>
    setImmediate(() => {
      console.log('event loop');
      resolve();
    })
  );
}

const run = async () => {
  while (!done) {
    console.log('loop');
    await eventLoopQueue();
  }
}

run().then(() => console.log('Done'));


text:
Q: log4j properties DailyRollingFileAppender does not work I want daily logs with the log file appended with the date in yyyy-dd-mm format. When I use DailyRollingFileAppender, a new log file is not created. The logs are written to the same log file. Also, the date Pattern provided is not considered. The log file created is LoggerFile.log. And every content(even on the next day) is written to this file.
I am using the log4j-1.2.17 jar. I am developing in Netbeans 7.3.1 in Java.
Is there anyone using this JAR and facing such a problem. Please help!
Here is the content of the properties file I use:
# Root logger option
log4j.rootLogger=ERROR,FILE,stdout

# Define the file appender
log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender

log4j.appender.FILE.File=.//..//logs//LoggerFile.log

# Define the layout for file appender
log4j.appender.FILE.DatePattern='.'yyyy-MM-dd
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS zzz} %5p     %c{1}:%L - %m%n

log4j.appender.FILE.MaxFileSize=10MB

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L -  %m%n`

A: I had similar requirements of daily log file rotation.. (Though the question is older, thought the answer would help others)..
Key points:

*

*First of all, we can avoid using DailyRollingFileAppender. Why? DailyRollingFileAppender has been observed to exhibit synchronization issues and data loss. The log4j extras companion includes alternatives which should be considered for new deployments and which are discussed in the documentation for org.apache.log4j.rolling.RollingFileAppender. Reference: Documentation of Daily Rolling File Appender

*Apache extras log4j, Would suggest to use org.apache.log4j.rolling.RollingFileAppender with the Time based rolling policy

*May find a sample configuration for time based rotation of log.
Hope this helps.

A: First of all you have an error because the DailyRollingFileAppender does not support the property MaxFileSize.
Then you can try to remove the char ' from the DatePattern:
Try changing
log4j.appender.FILE.DatePattern='.'yyyy-MM-dd

to
log4j.appender.FILE.DatePattern=.yyyy-MM-dd

A: Try to add another line   log4j.appender.file.Append=true
The full code looks like below
            # Root logger option
            log4j.rootLogger=DEBUG, file, stdout

            # Daily rolling file appender
            log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
            log4j.appender.file.File=logs/mylogs.log
            log4j.appender.file.Append=true
            log4j.appender.file.DatePattern='.'dd-MM-yyyy
            log4j.appender.file.MaxFileSize=10MB
            log4j.appender.file.MaxBackupIndex=100
            log4j.appender.file.encoding=UTF-8
            log4j.appender.file.layout=org.apache.log4j.PatternLayout
            log4j.appender.file.layout.ConversionPattern=%d{dd-MM-yyyy HH:mm:ss} %-5p %c{1}:%L - %m%n


text:
Q: Is there a way to return a Stored Procedure Return_Value to the python script executing it? I am writing a python script that should update a log table and notify me of it. Part of this script is to execute a SQL Server stored procedure.
I get an email telling me the status of the script as well as the status of the Stored procedure  depending on the return value. But I can't seem to get my stored procedure to return the Return_Value.
The script executes the stored procedure but receives no feedback.
I have tried using SQLAlchemy:
resulta = engine.execute(text(""" DECLARE @return int EXEC @return = [MYPROC] '{User}', '{Status}'
                         SELECT 'RETURN' = @return """.format(User = curruser, Status = 'Pass')).execution_options(autocommit=True))

My resulta returns: <sqlalchemy.engine.cursor.LegacyCursorResult object at 0xXXXXXXXXXX>
I have also tried using cursors:
resultb = cur.execute(""" DECLARE @return int EXEC @return = [MYPROC] '{User}', '{Status}'
                         SELECT 'RETURN' = @return """.format(User = curruser, Status = 'Pass'))

My resultb returns: NoneType object
I have also tried replacing the SELECT with a RETURN but that seems to cause more issues.
Please help.

A: You certainly can do this using pyodbc Cursors. You need to know in advance how many result sets are returned by the stored procedure that you're executing so that the result set with the return code is where you expect.
The following example executes sp_helpdb with a @dbname parameter, which returns two result sets from the stored procedure itself and the third result set holds the return code...
import pyodbc

server = 'tcp:127.0.0.1,1433'
database = 'master'
username = 'sa'
password = 'StrongPassw0rd'

connStr = 'DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password
cnxn = pyodbc.connect(connStr)
cursor = cnxn.cursor()

params = ( ('tempdb') )
result = cursor.execute("""
    declare @ReturnCode int;
    exec @ReturnCode = sp_helpdb @dbname = ?;
    select @ReturnCode as ReturnCode;
""", params)

# 1st result set from stored procedure...
databaseColumns = tuple([column[0] for column in result.description])
databaseRows = result.fetchall()
print(databaseColumns)
print(databaseRows)
print()

result.nextset()

# 2nd result set from stored procedure...
logicalFileColumns = tuple([column[0] for column in result.description])
logicalFileRows = result.fetchall()
print(logicalFileColumns)
print(logicalFileRows)
print()

result.nextset()

# 3rd result set for return code...
returnCodeColumns = tuple([column[0] for column in result.description])
returnCodeRows = result.fetchall()
print(returnCodeColumns)
print(returnCodeRows)
print()

That outputs the following to the console...
('name', 'db_size', 'owner', 'dbid', 'created', 'status', 'compatibility_level')
[
  ('tempdb', '     24.00 MB', 'sa', 2, 'Apr 29 2022', 'Status=ONLINE, Updateability=READ_WRITE, UserAccess=MULTI_USER, Recovery=SIMPLE, Version=904, Collation=SQL_Latin1_General_CP1_CI_AS, SQLSortOrder=52, IsAutoCreateStatistics, IsAutoUpdateStatistics', 150)
]

('name', 'fileid', 'filename', 'filegroup', 'size', 'maxsize', 'growth', 'usage')
[
  ('tempdev', 1, '/var/opt/mssql/data/tempdb.mdf', 'PRIMARY', '8192 KB', 'Unlimited', '65536 KB', 'data only'),
  ('templog', 2, '/var/opt/mssql/data/templog.ldf', None, '8192 KB', 'Unlimited', '65536 KB', 'log only'),
  ('tempdev2', 3, '/var/opt/mssql/data/tempdb2.ndf', 'PRIMARY', '8192 KB', 'Unlimited', '65536 KB', 'data only')
]

('ReturnCode',)
[(0, )]


text:
Q: Are there infinitely many Mersenne numbers coprime to a given integer? That is, given a positive integer m, is the set
$\{n\mid \gcd(m,2^n-1)=1\}$
where n is a positive integer infinite?

A: We have $n>0$ and $\gcd(2^n-1,m)>1$ only if $2^n\equiv 1\pmod p$ for some $p|m$ (and only if $p$ is odd). If $k_p>0$ is minimal with $2^{k_p}\equiv 1\pmod p$, then $k_p\ge2$. At least the infinitely many $n$ with $n\equiv 1\pmod {k_p}$ for all odd $p|m$ thus have $\gcd(m,2^n-1)=1$.


text:
Q: Quartic Formula existance There is a formula for cubic equations and quadratic equations. Is there a formula for the equations in the form $ax^4+bx^3+cx^2+dx+f=0$ I also skipped $e$ because of Euler's constant.

A: Here is my version:
Let the biquadratic be $$a_0 x^4 +4a_1 x^3 +6a_2 x^2 +4a_3 x + a_4=0$$
and the two invariants are
$$g_2=a_0 a_4 -4 a_1 a_3 +3 a_2^2$$
$$g_3=a_0 a_2 a_4 -a_0 a_3^2 -a_1^2 a_4  +2 a_1a_2 a_3 -a_2^3.$$
Then the resolvent cubic is
$$4z^3 -g_2 z -g_3=0$$
with roots
$$u_0=\frac{1}{2}\sqrt[3]{g_3 +\sqrt{g_3^2 +\left(\frac{g_2}{3}\right)^3}}+\frac{1}{2}\sqrt[3]{g_3 -\sqrt{g_3^2 +\left(\frac{g_2}{3}\right)^3}}$$
$$u_1= \frac{\zeta^2}{2}\sqrt[3]{g_3 +\sqrt{g_3^2 +\left(\frac{g_2}{3}\right)^3}}+\frac{\zeta}{2}\sqrt[3]{g_3 -\sqrt{g_3^2 +\left(\frac{g_2}{3}\right)^3}}$$
$$u_2=\frac{\zeta}{2}\sqrt[3]{g_3 +\sqrt{g_3^2 +\left(\frac{g_2}{3}\right)^3}}+\frac{\zeta^2}{2}\sqrt[3]{g_3 -\sqrt{g_3^2 +\left(\frac{g_2}{3}\right)^3}}$$
And the roots of the biquadratic are given by
$$r_0=-\frac{1}{a_0} \left[a_1 + \sqrt{a_1^2 -a_0a _2  -a_0 u_0 } + \sqrt{a_1^2 -a_0a _2  -a_0 u_1 } + \sqrt{a_1^2 -a_0a _2  -a_0 u_2 }\right]$$
$$r_1=-\frac{1}{a_0}\left[a_1 + \sqrt{a_1^2 -a_0a _2  -a_0 u_0 } - \sqrt{a_1^2 -a_0a _2  -a_0 u_1 } - \sqrt{a_1^2 -a_0a _2  -a_0 u_2 }\right]$$
$$r_2=-\frac{1}{a_0}\left[a_1 - \sqrt{a_1^2 -a_0a _2  -a_0 u_0 } - \sqrt{a_1^2 -a_0a _2  -a_0 u_1 } + \sqrt{a_1^2 -a_0a _2  -a_0 u_2 }\right]$$
$$r_3=-\frac{1}{a_0}\left[a_1 -\sqrt{a_1^2  -a_0a _2  -a_0 u_0 } + \sqrt{a_1^2 -a_0a _2  -a_0 u_1 } - \sqrt{a_1^2 -a_0a _2  -a_0 u_2 }\right]$$


text:
Q: Correct way of passing data from one observable to other I have two HTTP APIs -

*

*Gets a list of tableNames

*Gets a list of metadata

I am working on an Angular 5 application where the metadata (from 2nd API) before being displayed has to be modified by using the table names (from 1st API).
Therefore, I see the task as follows-
I have two observables. The first observable connects to the tableNames API and brings tableNames. The second observable connects to the metadata API, brings metadata and modifies the metadata according to the tableNames API output. I would like to keep the final product (modified metadata) as an observable which the angular application can subscribe to.
Currently, the code looks currently looks something like below-
private tablesNames: ReadonlyArray<String> | undefined;

this.getTablesNamesObservable().subscribe(
      tablesNames => { this.tablesNames = tablesNames; }
    );

// modify metadata uses tableNames to modify the metadata
this.modifiedMetadataObservable = this.metadataService.getOperatorMetadata()
                                      .map(metadata => this.modifyMetadata(metadata));

I didn't feel good about the code since I was assuming synchrony between two async operations. The doubt was proved right after reading this article. So, using the approach suggested in the article, I changed the code to give tableNames as a parameter to generate new Observables and use switchMap (I could have used concatMap/flatMap but switchMap suited my requirements).
this.getTablesNamesObservable().switchMap(
      tableNames =>{this.metadataService.getOperatorMetadata()
                        .map(metadata => this.modifyMetadata(metadata, tableNames));}
      );

Is this the correct way to go about this task or are there other better techniques to achieve this?

A: If getTablesNamesObservable and getOperatorMetadata are independent, it would make more sense to use combineLatest:
Observable.combineLatest(
  this.getTablesNamesObservable(),
  this.metadataService.getOperatorMetadata()
).map(([tableNames, metadata]) => this.modifyMetadata(metadata, tableNames));

Then modifyMetadata will be called whenever either observable emits a value.
By using switchMap, you unsubscribe and resubscribe to the observable returned by getOperatorMetadata whenever the observable returned by getTablesNamesObservable emits. And if they are independent - that is, getOperatorMetadata does not need to be passed the table names - doing do seems unnecessary.
If the observables each emit only a single value - or if you want only the last-emitted value of each - use forkJoin instead of combineLatest.


text:
Q: C++ Macro pasting: is it possible? Using QT5 - MinGW:
I'like to write something like:
_MyProperty (long,PropertyName);

and have it expanded this way:
long p_PropertyName;  // this is the private variable
void PropertyName_Get (const long& newVal) {p_PropertyName = newVal;} // setter function
long PropertyName_Set () {return p_PropertyName;} // getter function
__property <MyClass,long,&MyClass::PropertyName_Get,&MyClass::PropertyName_Set> PropertyName;

(using the underscore to evidentiate what should be added to the tokens)
I tried with macro pasting etc. but i'm not able to do it.
Is it possible?

A: It should work like this:
#define _MyProperty(TYPE,NAME) TYPE p_##NAME; \
void NAME##_Get (const TYPE& newVal) {p_##NAME = newVal;} \
TYPE NAME##_Set () {return p_##NAME;} \
__property <MyClass,TYPE,&MyClass::NAME##_Get,&MyClass::NAME##_Set> NAME;

The most important parts:

*

*The ## operator glues together parts of a name. You must use it to combine the arguments with other name fragments. If you do not use it and only write p_NAME, the lexer would not recognize that NAME is a parameter

*You must escape each new line by placing a \ in front of the line break.


text:
Q: TABLE 1 data needs to populated to table2 by grouping I have
TABLE 1
col1 col2 col3 col4
1    1    1     AP
1    2    1     MP
4    2    1     MP
1    3    1     AP
2    2    2     JP
2    4    2     JP
8    7    2     LP
8    7    2     LP
8    8    3     HP
2    4    3     HP
3    9    3     ZP
6    9    3     ZP
I have a requirement that i have move data from table 1 to Table 2 by satisfying requirements
TABLE2
col1 col2 col3 col4
2    3    1    AP
5    2    1    MP
4     4    2   JP
16    7    2   LP
10    8    3   HP
9     9    3   ZP
where values col3 are grouped in such a way that we should sum all the values of col1 and where  as max value of col2 needs to be populated
Any answers or clues will be appriciated

A: INSERT INTO table2
SELECT SUM(col1),MAX(col2),col3
FROM table1
GROUP BY col3;

A: Does this work?
select sum(col1) col1, max(col2) col2, col3 col3
into table2
group by col3

A: Can you try with nosid's statement? Just make sure to add col4 in the select and group by statements. Does that work?
INSERT INTO table2
SELECT SUM(col1),MAX(col2),col3, col4
FROM table1
GROUP BY col3,col4;


text:
Q: How to assign a product source from Event Observer When a product is saved, I want to check if the product has an inventory source set, and if not, set one. The event name I'm observing is catalog_product_save_after.
This is the Observer code:
class validateProductSources implements ObserverInterface
{

    /**
     * @var Http
     */
    protected $request;
    protected $productRepoInterface;
    protected $sourceItemsBySku;

    protected $_sourceItemsSaveInterface;
    protected $_sourceItemFactory;

    public function __construct(
        Http $request,
        ProductRepositoryInterface $productRepoInterface,
        GetSourceItemsBySkuInterface $sourceItemsBySku,
        SourceItemsSaveInterface $sourceItemsSaveInterface,
        SourceItemInterfaceFactory $sourceItemFactory
    )
    {
        $this->request = $request;
        $this->productRepoInterface = $productRepoInterface;
        $this->sourceItemsBySku = $sourceItemsBySku;
        $this->_sourceItemsSaveInterface = $sourceItemsSaveInterface;
        $this->_sourceItemFactory = $sourceItemFactory;
    }

    public function execute(Observer $observer)
    {
        $this->request->getParams();
        $productId = $this->request->getParam('id');
        $product = $this->productRepoInterface->getById($productId);
        $sku = $product->getSku();
        $sourceItems = $this->sourceItemsBySku->execute($sku);
        if(!$sourceItems){
            $sourceItem = $this->_sourceItemFactory->create();
            $sourceItem->setSourceCode('default');
            $sourceItem->setSku($sku);
            $sourceItem->setQuantity(1);
            $sourceItem->setStatus(1);
            $this->_sourceItemsSaveInterface->execute([$sourceItem]);
        }
    }
}

The code is executed. I know this because I've tested it with the logger. The products source is not set though.
What baffles me is that if I use the same code in a controller (minus the request to get the product ID), the source is successfully set.
Could anyone tell me Why this happens, and how to fix it?

A: I was able to fix this by changing catalog_product_save_after to controller_action_catalog_product_save_entity_after in events.xml, and using the following code:
public function execute(Observer $observer)
    {
        $product = $observer->getData('product');
        $sku = $product->getSku();
        $sourceItems = $this->sourceItemsBySku->execute($sku);
        if(!$sourceItems){
            $sourceItem = $this->_sourceItemFactory->create();
            $sourceItem->setSourceCode('default');
            $sourceItem->setSku($sku);
            $sourceItem->setQuantity(1);
            $sourceItem->setStatus(1);
            $this->_sourceItemsSaveInterface->execute([$sourceItem]);
        }
    }


text:
Q: Find upper limit for this probability using Chebychev's inequality. If $X$ is a continuous random variable which is distributed evenly in (0,10):
a)How do we compute exactly $P\{|X-5| \gt 4\}$?
b)Can we give an upper limit using Chebyshev's inequality and how?
*Can someone get to the final solution of b (Abishanka Saha made a good start)? It would help very much.

A: $$P(|X-5|<4)=P(1<X<9)=\frac{8}{10}$$
Chevychev's Inequality says that
$$P(|X-\mu|<\epsilon)\leq\frac{E(X^2)}{\epsilon^2}$$
Here $\mu=5$, $\epsilon=4$, Find $EX^2$ for the given distribution.
See here


text:
Q: selected view in UITabBar How can i detect when user select an item of tab bar?
I want to run some commands on each time, when user select the second or the thirt tab bar view.
(I have a tab bar based project, and the viewcontrollers for tabBar items are selected in interface builder)

A: I solved this problem with using"viewWillApear:(BOOL)animated" method in each view-s of tabBar.

A: There is a method in UITabBarDelegate called:
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item;

You can certainly do what you want with ;)

A: A tab bar and tab bar controller both have delegate methods: UITabBarDelegate and UITabBarControllerDelegate. You can use the tabBar:didSelectItem: method of the UITabBarDelegate to detect when the user selects different items on the bar.


text:
Q: rails 4 app in subdirectory - precompiled assets point to root instead of subdirectory Rails 4.1.1 production installation using Apache/Passenger configured to run rails app in a subdirectory "/myapp" instead of the root of the site.
All links in the app work fine, but in production references to assets in SCSS file, for example
    background-image: image-url('logo.png');

get compiled to:
    background-image: url("/assets/logo-<hash>.png");

instead of:
    background-image: url("/myapp/assets/logo-<hash>.png");

I tried doing something like this when precompiling assets:
    RAILS_ENV=production RAILS_RELATIVE_URL_ROOT=/myapp rake assets:precompile

but that had no effect.
I also tried setting config.relative_url_root in the config/environments/production.env file, with no luck.
The Rails guides say to set config.action_controller.relative_url_root, but that results in a missing method error.
I eventually gave up and embedded the image in the CSS file by using:
    background-image: asset-data-url('logo.png');

which works, but only by avoiding the subdirectory problem altogether.
I know Rails makes you pay for not following conventions, but having an app in a subdirectory is not exactly outlandish.
I've seem all kinds of posts on this problem, but it's hard to get a straight answer.  It seems to have been fixed a few times for earlier versions of Rails, but it's not clear if the fixes ever got into the standard Rails distribution.

A: In our case, we were able to make two changes, which seem to be working for us in Rails 4.1.6 :
1) In application.rb, assume there is a module named "MyAppName < Rails::Application". In here, we have
config.relative_url_root = "/myapp"

2) In config.ru:
map MyAppName::Application.config.relative_url_root || "/" do
  run Rails.application
end

Without the config.ru update, things don't work properly.

A: After adding the jquery-ui-rails gem to another app deployed in a subdirectory, I had the same problem with the assets referred to by the built-in CSS for jQuery UI.  I refused to modify the 3rd-party CSS files just to fix this problem, especially since Rails seems to be handling all paths (other than asset paths) correctly out of the box.
After pulling my hair out for some time, I don't know what prompted me to re-run the rake assets:precompile task exactly as given here.  To my complete surprise, everything worked perfectly, both my own image URLs and jQuery UI's.
What made the difference?  If I call the rake script from the app's bin folder as shown below, all the asset URLs are built incorrectly, without the subdirectory.
RAILS_ENV=production RAILS_RELATIVE_URL_ROOT=/myapp bin/rake assets:precompile

If instead I run rake via bundle exec, as follows, all the asset paths are generated correctly, including the subdirectory.
RAILS_RELATIVE_URL_ROOT=/myapp RAILS_ENV=production bundle exec rake assets:precompile

As to why this is happening, I can only conclude that running bin/rake does not load the right gems.


text:
Q: Generate random key for a row with SQL Loader I'm loading a large amount of data with SQL Loader.
The target table has a unique, system-generated PK.
When the table is populated by the business application, the key is generated programatically.
The extract file for the bulk upload doesn't have key in the record. Also, the upload is running in multiple threads, because of the extremely large volumes, and in stages - one file a day.
Is there way to populate a column with random key char(14), directly in SQL Loader? In other words, can I have something like that in the Control File:
ID EXPRESSION (random number creation expression),
name char(10),
age number

so from the data file
Joe, 10
Mary, 5

I'll create data:
719287398 Joe  10
645743657 Mary 5

A: Something like ID EXPRESSION "dbms_random.string('l',14)" can be used.


text:
Q: Why can't my FreeBSD 6.1 (vmware player client under Win7) do DNS in Bridged mode I have a 64-bit FreeBSD 6.1 client, running under Windows 7 (64-bit)  via VMWare player 3.0, with networking set to bridge mode.
DHCP goes fine on boot...   I get correct adress/gateway/nameserver info... I have good connectivity to the world in that I can ping any host I can name by IP addr, (including both of the nameservers in resolv.conf,) ...but I can't resolve any names.
Inside the Windows box, the network interface has VMWare Bridge Protocol enabled, and the windows side of things has full connectivity.
dig replies with:
;; connection timed out; no servers could be reached
...even if I use "dig @server_ip_addr" to point it at a pingable, working nameserver
If I set VM networking to NAT mode, I can get outbound connectivity (with happy DNS) but, of course, can't do INBOUND connectivity, which I need.
Thoughts?

A: Might as well answer my own question in case someone else has a similar problem...
After much thrashing, I found out that it was related to the Shrewsoft VPN driver I was also running, which ran at startup whether or not I connected to the VPN. Updating to the 2.1.6 Beta driver caused my problem to go away.


text:
Q: LINQ: Inner join to the First row in a sub query? I have two classes, basically one holds Members and the other Sessions.
They are joined together with a common field called "name". There is one member but can be many Sessions.
So if I do a standard join I get back 1 member and many sessions. I just want to get back the first row of sessions.
The session has field called SessioEndTime. So I need to order by DESC on this to pick out the first record.
This is my linq; I have returns too many. I think I need a subquery but I am a little confused.
  var sessions = from m in this.members
                   join s in this.sessions
                   on m.Name equals s.Name
                   select new { MemberName = m.Name, SessionTime = s.SessioEndTime};

Edit
To make it clear, imagine I have five members, each member has NUMEROUS sessions. I just wish to receive my five members but with only one session each, that session is the LATEST session which can be got from the SessioEndTime.

A: Try this:
var sessions =
    from m in this.members
    join s in
    (
        from se in this.sessions
        group se by se.Name into g
        select new {Name = g.Key, SessioEndTime = g.Max(a=>a.SessioEndTime)}
    )
    on m.Name equals s.Name
    select new { MemberName = m.Name, SessionTime = s.SessioEndTime}


text:
Q: jQuery datetime picker set year range good day. I downloaded a jQuery plugin here to have a dateTime picker but I want to change the range from 1900 - current year right now. I tried using the
minDate and maxDate

but doesn't work. I also tried using this codes
changeMonth: true,
changeYear: true,
yearRange:'1900:' + new Date().getFullYear()

but nothing keeps working and still throws me to the range 1950 - 2050. thanks
UPDATE
ok so my code and the code posted was correct. it was throwing the year due to a command in the jquery.datetimepicker.full.js wherein the
    yearStart: 1950,
    yearEnd: 2050,

was set to this. I simply changed it to this
    yearStart: 1900,
    yearEnd: new Date().getFullYear(),

Thanks for the help guys.

A: You can add YearRange as shown below.it will works..
$('#dtp').datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true,
yearRange: "-100:+50",
autoSize: true
});

or

      <meta charset = "utf-8">
      <title>jQuery UI Datepicker functionality</title>
      <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">

Enter Date: <input type = "text" id = "datepicker-13">


text:
Q: How to Click one button and active 2 buttons in the same time Hello im at coding a multi-step form and my jquery script split my form in different sections with the fieldset tag so all and good.
I need somehow a code that if a click over a button to activate the same time the other button that is hidden , Hidden because as i mention jquery split my form in different sections so for example:
If /fieldset tag than fieldset> the other other form start, and my forms have headers and footers tag inside them so  if i click over the next button and the button is placed inside the footer tag it changes just the footer container
So if i put another button inside the fieldset and push there next it work just i want but i want the button to be placesd in the footer for aesthetic aspect so .
The ieda was to hide the button inside fieldset tag and link it with the button inside the footer tag any idea  here is my code thanks in advance!
      <section1>
    <input type="checkbox" name="copy">Send a copy to my e-mail address
</section1>

<input type='button' name="Next" class='next action-button' value='Próximo' />

    <header1>
        <input type='button' name='Next' class='next action-button' value='Próximo' />
    </header1>

</fieldset>

script : in this link look at the js section : http://codepen.io/pedroG/pen/hKarC
i tried this `
</section1>
    <input type="button" class='hidden_button' style='display:none'  value="Próximo" />

                    <header1>
  <input type="button" name="Next" id='button1' class="next action-button "  value="Próximo"/>
                    </header1>

but still with no success`

A: Give them both an ID and use jQuery's click function.
$('#button1').click(function(){ $('#button2').click() });

A: Give the both a class and not an id because the is for one element and not more ,so we make :
<input type='button' id='button1' />
<input type='hidden' class='hidden_button' />
<input type='hidden' class='hidden_button' />
$('#button1').click(function()
{
 $('.hidden_button').attr('type','button');
});

or this code :
<input type='button' id='button1' />
<input type='button' class='hidden_button' style='display:none'/>
 <input type='button' class='hidden_button' style='display:none'/>

$('#button1').click(function()
{
 $('.hidden_button').show();

});

A: A better way would be to change your jquery so that your form is not split up but if that isn't an option you could use something like this
$(document).ready(function(){
    $("#mainButton").click(function(){
        $( "#button2" ).click();
        $( "#button3" ).click();
    });
});

A: One click  clicking two buttons in same time :
Html:
<input type="button" name="Next" id='button2' class="next action-button " value="Próximo" />

                    <header1>
        <input type="button" name='Next' id='button1'   class='next action-button '  value='Próximo' />
        </header1>

Jquery:

Thanks to all the guys who helped me .


text:
Q: Adding a 'Grooveshark' entry to Google's black navigation bar I'm trying to make a tweak to Google's black navigation bar (this thing at the top)
More specifically, I want to have a button that you can click to transpose your current search query to Grooveshark's search.
It's basically the same thing as when you search for something on Google, you hit the 'YouTube' link at the top and it searches for whatever you input on Google's website, on YouTube.
I've asked StackOverflow for help before a while back when I was new to programming (also questions pertaining to userscripts), but honestly, the respondents did most of the work for me in their replies, which I apologize for, as this was not my intention.
Because of this, I decided I wanted to make this one on my own as much as I could, and for the most part, I did (albeit with lots of Googling :)
However, now that everything is working in JSFiddle, I'm having trouble 'porting' it to userscript and finalizing it.
To be more specific, the Grooveshark logo does not even show up on Google's website while using my userscript on the intended pages.
I even copied part of the Google HTML source to JSFiddle to see if it would work there, and it did.
I'm still rather new to JavaScript (as in: 'I have not used it in any serious manner before today') and as such, it took me a while to put this script together.
So my questions are these:

*

*How do I adapt this piece of Javascript to work on Google's website by using a userscript?

*I added an 'alt' attribute to the Grooveshark logo, but this does not show up in my browser (chrome) while it does when viewing source or inspecting. Why is this, and how do I fix it?
Here's the userscript I have so far:
// ==UserScript==
// @name           GoogleGroovesharkBar
// @description    Adds a 'Search on Grooveshark' option to Google's black navigation bar
// @include        google.com/*
// @include        google.nl/*
// @include        https://www.google.com/*
// @include        https://www.google.nl/*
// @include        http://www.google.com/*
// @include        http://www.google.nl/*
// @require        http://code.jquery.com/jquery-1.10.1.min.js

//by Soullesswaffle
//Versions : 0.8
// ==/UserScript==

function addGroove(retrievedText) {
    var bar = document.getElementById("gbzc");
    var grooveyImage = document.createElement("img");
    var link = document.createElement("a");
    var listy = document.createElement("li");
    grooveyImage.src = "http://cdn.androidpolice.com/wp-content/uploads/2012/08/nexusae0_146.png";
    grooveyImage.style.height = "28px";

    //grooveyImage.alt doesn't display in chrome for me, but when inspecting the element the alt attribute is present and correct.
    if (retrievedText === "") {
        link.href = "http://grooveshark.com";
        grooveyImage.alt = "Grooveshark";
    } else {
        link.href = "http://grooveshark.com/#!/search?q=" + retrievedText;
        grooveyImage.alt = "Search for '" + retrievedText + "' on Grooveshark";
    }

    //Nest and display everything
    link.appendChild(grooveyImage);
    listy.appendChild(link);
    listy.id = "grvshrkbtn";
    if (!document.getElementById("grvshrkbtn")) {
        bar.appendChild(listy);
    } else {
        bar.replaceChild(listy, document.getElementById("grvshrkbtn"));
    }
}

//Initialize
$(document).ready(function () {
    addGroove(document.getElementById("gbqfq").value);
});

//Watch textfield for changes
$("#gbqfq").bind("input", function () {
    addGroove($(this).val());
});

Thanks in advance!

A: Why it doesn't work in Chrome:
To run this on Firefox, you need to install the Greasemonkey add-on.  Likewise, to run this in Chrome, you need to install the Tampermonkey extension.
Chrome has limited, native support for userscripts, but it doesn't support @require and a bunch of other goodies.  Save yourself some hassle and use Tampermonkey.
Avoid conflicts: Requiring jQuery is good, but unfortunately, due to changes in Greasemonkey (and now Tampermonkey), it can cause conflicts with some websites if the sandbox is switched off.  To avoid potential conflicts, always use an explicit @grant to control the sandbox.
Change the end of your metadata block to:
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/

About the alt attribute:
Remember that the alt attribute is only supposed to be displayed if the image doesn't load for some reason.  Is the image loading?
Perhaps you want the title attribute, since it's often used for tooltips.
Change this code snippet:
if (retrievedText === "") {
    link.href = "http://grooveshark.com";
    grooveyImage.alt = "Grooveshark";
} else {
    link.href = "http://grooveshark.com/#!/search?q=" + retrievedText;
    grooveyImage.alt = "Search for '" + retrievedText + "' on Grooveshark";
}

to this:
if (retrievedText === "") {
    link.href = "http://grooveshark.com";
    grooveyImage.alt    = "Grooveshark icon supposed to be here";
    grooveyImage.title  = "Grooveshark";
} else {
    link.href = "http://grooveshark.com/#!/search?q=" + retrievedText;
    grooveyImage.alt    = "Grooveshark icon supposed to be here";
    grooveyImage.title  = "Search for '" + retrievedText + "' on Grooveshark";
}

Or just set the image's alt once to "Grooveshark icon", and only switch the title.


text:
Q: How to pass cell value as parameter in google apps script function? I'm in need of some help with the final part of my code. I'm working with an API to get the name of the street and city from the government database and i use the Zip code and house number as input. The API i have working, but the final step is to pass cell values (Zip code, house number) as parameters into my formula. I cannot seem to get this working.
Here is my code:
function postHuisNaarStraat (ref1, ref2){

  var PCCell = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(ref1).getValue();
  var HNCell = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(ref2).getValue();

  var postcode = "filters[postcode]=" + PCCell;
  var huisnummer = "filters[huisnummer]=" + HNCell;

  var API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  var url = "https://api.overheid.io/bag?" + postcode + "&" + huisnummer;
  var response = UrlFetchApp.fetch(
    url,
    {
      "headers":{
        "ovio-api-key":API_KEY,
        "Accept":"application/hal+json",
        "Content-Type":"application/json"
      }
    }
  );

  // parse JSON reply
  var json = response.getContentText();
  var data = JSON.parse(json);

  // Logger.log(data);
  Logger.log(data["_embedded"]["adres"][0]["openbareruimte"]);

}

Please help me get the data from my cells (postcode, housenumber) and add their respective value in my formula.
Here is what i want to do but cant get working

A: Replace
  var PCCell = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(ref1).getValue();
  var HNCell = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(ref2).getValue();

by
  var PCCell = ref1;
  var HNCell = ref2;

or even better (as this will make your code shorter), instead of  ref1 and ref2 as function argument names use PCCell and HNCell, respectivelly.
Resources

*

*https://developers.google.com/apps-script/guides/sheets


text:
Q: Upload file in angular / web API I created a function that add a new user with Angular/WebAPI ,  so in angular i send the object like this :
 AddUser(person : person):Observable<person>
  {
    return this.http.post<person>(this.baseUrl,person);
  }

and in WebAPI i got the data :
[HttpPost]
  public async Task<ActionResult<Person>> PostPerson(Person person)
  {

Now I want to add a picture of each user, and i don't know how it's gonna be the objet in angular, should i add a property  imageProfile as File which i'm not sure if it's possible , or it should be a string of the uploaded file.
export class person {
    idPerson:number=0;
    fname : string ="" ;
    lname : string  ="";
    password : string ="";
    idCategory? :number;
    nameCategory:string="";
    imageProfile :
}

A: That's very good info from Codemaze, as always. The remark from Lavstsen is not correct, there's no need for a separate call.
For example, you could have a form linked to the structure of the person-type:
initializeForm() {
    this.personForm = this.form.group({
        fname: [''],
    })
}

In your onSubmit-method, you seize the date from your form and put in a dto, in this example through a getPersonDto-method
private getPersonDto(): PersonDto {
    let dto = new PersonDto();
    dto.fname = this.imageForm.controls.fname.value;
    return dto;
}

and next you can solve it like this:
const formData = new FormData();
    formData.append('Imagefile', this.selectedFile, this.selectedFile.name);
    formData.append('fname', personDto.fname); // needs to be strings => toString()
    this.personApiClient.uploadImageFile(this.personId, formData)
        .subscribe((res: any) => {
            this.uploadOrDeleteResults = res;
            this.showToastrMessageSuccess("PAGES.COMMON.TOASTR.TITLE.SUCCESSFULCREATE", "PAGES.COMMON.TOASTR.MESSAGE.SUCCESSFULCREATE");
        },
            (error) => {
                this.crudHasErrors = true;
                this.errorHttpErrorResponse = error;
                this.errors = this.errorHttpErrorResponse.error;
            },

you don't need the dto-step as such, but if you structurally always use dto's in your application, it would make more sense
Take care and good luck

A: I have another workaround but this will only work for very small files where you don't need upload percentage to show on UI.
I have my controller like this:
    [HttpPost("/api/sign-up")]
    public void SaveUser([FromForm] UserModel info)
    {
        _logger.LogDebug(null, "Hello", info); // Just to see contents of info object in debugger
    }

and make your model like this:
public class UserModel
{
    [FromForm(Name = "avatar")]
    public IFormFile Avatar { get; set; }

    [FromForm(Name = "email")]
    public string Email { get; set; }

}


text:
Q: SQL Encrypt a Column syntax error I tried this example Column encryption example
But in this line:
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'SQLAuthority'

I get that error:

There was an error parsing the query. [ Token line number = 1,Token line offset = 8,Token in error = MASTER ]


text:
Q: how to set currentdate as mindate in calendar component of primefaces? I am using calendar component of primefaces. I want to set mindate=currentdate. I want restrict user to select date before current date. I am using JSF2.0.

A: If you are using omnifaces, you can do this:
<p:calendar ... mindate="#{now}" />

A: Just bind it as a bean property the usual way.
<p:calendar ... mindate="#{bean.currentDate}" />

By the way, the way how you created the current date is clumsy. Just invoking the Date's own constructor is sufficient. Using the Calendar for this purpose only brings unnecessary overhead along.
private Date currentDate = new Date();

public Date getCurrentDate() {
    return currentDate;
}

A: <p:calendar mindate="today">

A: Try this,
 <p:calendar mindate="calwidget.today()" widgetVar="calwidget" value="#{bean.date}">


text:
Q: Can I load solr schema file from another server? I am running solr on 5 different instance. Making change in schema/dataconfig file is a big task as I need to make changes on each server.
Can I load schema file from a server? So that same path can be defined in each solrconfig and changes will be reflected on each solr instance.

A: If you're running Solr on multiple instances, you should really consider moving to a cluster based installation (i.e. SolrCloud). This will give you a common schema across servers and allow you to easily create collections and make changes across all nodes in your network at the same time.
You can use a shared file system, but it'll still require you to access each server (which you can do through the core API if you want to automate it) to reload the core to make it pick up any changes to the schema.


text:
Q: Difference between `shl di` and `shl di, 1` I tried to compile the following with NASM
shl di

which, according to this very non-sketchy source should multiply di by 2 once. However, I get an "invalid combination of opcode and operands" from NASM. After a bit of head-scratching, resolved to using
shl di, 1

which is magically OK with NASM and everything is OK with me too, except that now I am left with a question because, off the top of my head, I could have sworn that the first form was a thing, but maybe I'm misremembering things.
So, which is it?

A: Apparently, NASM requires the count even if it's 1. Inspection of the generated machine code reveals that shl di and shl di, 1 indeed generate the same opcodes.


text:
Q: How frequent do you need to do camera calibration for ArUco? How important it is to do camera calibration for ArUco? What if I dont calibrate the camera? What if I use calibration data from other camera? Do you need to recalibrate if camera focuses change? What is the practical way of doing calibration for consumer application?

A: Before answering your questions let me introduce some generic concepts related with camera calibration. A camera is a sensor that captures the 3D world and project it in a 2D image. This is a transformation from 3D to 2D performed by the camera. Following OpenCV doc is a good reference to understand how this process works and the camera parameters involved in the same. You can find detailed AruCo documentation in the following document.
In general, the camera model used by the main libraries is the pinhole model. In the simplified form of this model (without considering radial distortions) the camera transformation is represented using the following equation (from OpenCV docs):

The following image (from OpenCV doc) illustrates the whole projection process:

In summary:
P_im = K・R・T ・P_world

Where:

*

*P_im: 2D points porojected in the image

*P_world: 3D point from the world

*K is the camera intrinsics matrix (this depends on the camera lenses parameters. Every time you change the camera focus for exapmle the focal distances fx and fy values whitin this matrix change)

*R and T are the extrensics of the camera. They represent the rotation and translation matrices for the camera respecively. These are basically the matrices that represent the camera position/orientation in the 3D world.

Now, let's go through your questions one by one:

How important it is to do camera calibration for ArUco?

Camera calibration is important in ArUco (or any other AR library) because you need to know how the camera maps the 3D to 2D world so you can project your augmented objects on the physical world.

What if I dont calibrate the camera?

Camera calibration is the process of obtaining camera parameters: intrinsic and extrinsic parameters. First one are in general fixed and depend on the camera physical parameters unless you change some parameter as the focus for example. In such case you have to re-calculate them. Otherwise, if you are working with camera that has a fixed focal distance then you just have to calculate them once.
Second ones depend on the camera location/orientation in the world. Each time you move the camera the RT matrices change and you have to recalculate them. Here when libraries such as ArUco come handy because using markers you can obtain these values automatically.
In few words, If you don't calculate the camera you won't be able to project objects on the physical world on the exact location (which is essential for AR).

What if I use calibration data from other camera?

It won't work, this is similar as using an uncalibrated camera.

Do you need to recalibrate if camera focuses change?

Yes, you have to recalculate the intrinsic parameters because the focal distance changes in this case.
What is the practical way of doing calibration for consumer application?
It depends on your application, but in general you have to provide some method for manual re-calibration. There're also method for automatic calibration using some 3D pattern.


text:
Q: Improving a GET request using the default Go HTTP client I'd like to improve the GET request that I'm using in a function using the net/http package in Go.
I'm using bodyText, err := ioutil.ReadAll(resp.Body) in the function, but I'm not sure if this is the best way to get the JSON response from the server.
// Getting HTTP Status code
func StatusF (url string, token string) *statusf {
    // Setup req
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        log.Fatal(err)
    }
    req.Header.Set("Authorization", token)

    // Request
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }

    // Close response
    defer resp.Body.Close()

    // Getting the response from the server
    bodyText, err := ioutil.ReadAll(resp.Body)
    fmt.Printf("response:%s", bodyText)

    var myvar StructureJson // we create an empty instance of StructureJson
    err = json.Unmarshal([]byte(bodyText), &myvar)
    if err != nil {
        panic(err)
    }

    // Return the JSON object
    return &myvar
}

A: According to the comments if I want to improve the function I can include err := json.NewDecoder(resp.Body).Decode(&myvar) and delete the intermediate bodyText buffer:
// Getting HTTP Status code
func StatusF (url string, token string) *statusf {
    // Setup req
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        log.Fatal(err)
    }
    req.Header.Set("Authorization", token)

    // Request
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        panic(err)
    }

    // Close response
    defer resp.Body.Close()

    var myvar StructureJson // we create an empty instance of StructureJson
    err := json.NewDecoder(resp.Body).Decode(&myvar)
    if err != nil {
        panic(err)
    }

    // return the JSON object
    return &myvar
}


text:
Q: How to send files via a socket in python I just coded a little client/server program. I used the socket module of python3 for this.
And i wanted to know how to not only send strings but other datatypes besides the basic datatypes. So for example, images as jpgs or whatever or how to send mp4 or avis something like that so basically visual datatypes that are used in the daily life.
My first thought was to code it exactly the same as with strings:
socket_name.send(bytes('string'))

but then i would need a function to convert the datatype into bytes and back on the server and I couldn't find one that provides this.
So I searched for other functions and found sendfile and makefile. I tried them out but I couldn't find how to use them properly and it didn't work.
So my question is simply how to send visual data via a socket in python3.


text:
Q: Javascript: Class Design Pattern - pseudo-polymorphism In Kyle Simpson's You-Don't-Know-Js books series while discussing the class pattern implementation in pre-es6 javascript in this & Object Prototypes book of the series he mentioned in chapter 4 what he called pseudo-polymorphism.
He described this pseudo-polymorphism saying:

But because of JavaScript's peculiarities, explicit pseudo-polymorphism (because of shadowing!) creates brittle manual/explicit linkage in every single function where you need such a (pseudo-)polymorphic reference. This can significantly increase the maintenance cost. Moreover, while explicit pseudo-polymorphism can emulate the behavior of "multiple inheritance", it only increases the complexity and brittleness.

From what i could understand here, This pseudo-polymorphism is a bad behavior that we better avoid because of the explicit calling for the SUPER class like in his example about calling Vehicle class from inside of Car class so we would do this as an explicit call like this :
function Car () {
    Vehicle.call( this );
}
//also overriding Vehicle's methods
Car.prototype.methodName = function( p1 ) {
    //manipulate p1 then call the super method.
    Vehicle.prototype.methodName.call( this, p1 );
};

But i am wondering if the problem here is related to the explicit use of Vehicle class name then why we don't just do this :
function Car () {
    this.super = Object.getPrototypeOf( this ).constructor;
    this.super.call( this );
}
//also overriding Vehicle's methods
Car.prototype.methodName = function( p1 ) {
    //manipulate p1 then call the super method.
    this.super.prototype.methodName.call( this, p1 );
};

Isn't this kind of faking or emulating the super keyword in other class-oriented-languages which solving the problem ?

A:
...why we don't just do this...

Because it doesn't work, but you're far from the first person to fall down that trap. :-) Try adding a LuxuryCar subclass of Car to see the problem: Now this.super (even in Car code) refers to Car, not Vehicle.
There are patterns that make it possible to avoid explicitly using the name Vehicle in Car in ES5-level code (I wrote one of them up in 2009), but they're obsolete now; instead, we use class syntax from ES2015 (transpiling if necessary):

class Vehicle {
    methodName() {
        console.log("Vehicle#methodName");
    }
}
class Car extends Vehicle {
    methodName() {
        super.methodName();
        console.log("Car#methodName");
    }
}
class LuxuryCar extends Car {
    methodName() {
        super.methodName();
        console.log("LuxuryCar#methodName");
    }
}

const l = new LuxuryCar();
l.methodName();


text:
Q: Javascript repetition of events If the focus is on the input was only one time it works but if more then attached event begins to work as many times as eliment was in focus. How to make a click event to execute only once? Below is the code.
$('.menuName').focusin(function(){

        $(this).parent().append('

');

        inputclr = $(this);
        intutval = $(inputclr).val();

        $(document).on('click', '.cleartext', function() {

            $('.menuName').placeholder();
                $(inputclr).attr('placeholder',intutval);
            $('.pinch_text').html('click');
            $(inputclr).val('').focus();

        });
    });

A: You should remove any listeners by using the off function:
$(document).off('click','.cleartext').on('click', '.cleartext', function() {

    $('.menuName').placeholder();
        $(inputclr).attr('placeholder',intutval);
    $('.pinch_text').html('click');
    $(inputclr).val('').focus();

});

A: Bring your code outside focus event
 $(document).on('click', '.cleartext', function() {

            $('.menuName').placeholder();
                $(inputclr).attr('placeholder',intutval);
            $('.pinch_text').html('click');
            $(inputclr).val('').focus();

        });
var inputclr , intutval ;
$('.menuName').focusin(function(){

        $(this).parent().append('

');

        inputclr = $(this);
        intutval = $(inputclr).val();

    });


text:
Q: Know when dictation has ended in a UITextView I'd like to know when dictation has end (ideally also when it started).
My UIViewController which includes the UITextView conforms to the UITextInputDelegate protocol.
To make it work I had to subscribe to the UITextInputCurrentInputModeDidChangeNotification
override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeInputMode:", name: UITextInputCurrentInputModeDidChangeNotification, object: nil)
}

and add the delegate there (it didn't work simply adding it to the viewDidLoad())
func changeInputMode(sender : NSNotification) {
    textView.inputDelegate = self
}

Starting and stopping dictation the UITextInput now correctly calls the required delegate methods:
func selectionWillChange(textInput: UITextInput){    }
func selectionDidChange(textInput: UITextInput){    }
func textWillChange(textInput: UITextInput){    }
func textDidChange(textInput: UITextInput){    }

However what doesn't get called is
func dictationRecordingDidEnd() {
    println("UITextInput Dictation ended")
}

Why? How can I get notified/call a method on dictation having ended?

A: Okay, here's what worked for me not using the UITextInput protocol but the UITextInputCurrentInputModeDidChangeNotification instead.
func changeInputMode(sender : NSNotification) {
    var primaryLanguage = textView.textInputMode?.primaryLanguage

    if primaryLanguage != nil {
        var activeLocale:NSLocale = NSLocale(localeIdentifier: primaryLanguage!)
        if primaryLanguage == "dictation" {
            // dictation started
        } else {
            // dictation ended
        }
    }
}


text:
Q: Phonegap detect backButton event fail When I use https://build.phonegap.com/ to build my application in android, my code to process the detection of the back button does not work.
Though I have used the following code to do it :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet"  href="css/jquery.mobile-1.4.1.min.css">
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/jquery210.js"></script>
<script type="text/javascript" src="js/engine2.js"></script>
<script type="text/javascript" src="js/jqm141.js"></script>
<script type="text/javascript">
function onLoad(){
    document.addEventListener('deviceready', function() {
        navigator.splashscreen.show();
        document.addEventListener("backbutton", ShowExitDialog, false);
    }, false);
}

function ShowExitDialog() {
    if (navigator.notification) {
        navigator.notification.confirm(
            ("Are you sure ?"),
            alertexit,
            'Exit',
            'Yes,No'
        );
    }
}

function alertexit(button){
    if(button=="1" || button==1){
        navigator.app.exitApp();
    }
}
</script>
</head>

<body onLoad="onLoad()">

...

</body>
</html>

I get when pressing the back button, my application does not respond to anything. How do I add a detection function to Back button??

A: Use this simple code...
 document.addEventListener("deviceready", appReady, false);
        function appReady()
        {
            document.addEventListener('backbutton', function(e){
                      if (confirm("Press a button!"))
                      {
                     alert("You pressed OK!");
                     navigator.app.exitApp();
                      }
                    else
                      {
                        alert("You pressed Cancel!");
                      }
              }, false);
        }


text:
Q: Do I have to use DataAnnotations if I use jQuery Validation? I use jQuery Validation and some custom properties like maxlength in my Razor View and with the help of these functionality, I am able to prompt and limit the user from leaving a blank field or exceeding max character limit. So, in this case do I have to use [Required], [Range] or some other DataAnnotations in my Entity classes?

A: Data annotations allow for a simple way to add validation on both the server side and the client side in a single location in your code.
With your current technique, is validation being performed on the server as well as the client? Remember that, with javascript, you give the client your source code and even allow them to disable it if they choose, which means you can't rely on it for validation.
DataAnnotations are highly recommended unless you have a better/preferred approach.


text:
Q: calculate steps of turtles among neighbors In the world, the two types of agents, individuals and messages, are randomly positioned in the two-dimensional attitudinal space.
If an individual believes the messages, he or she creates links with the messages.
Then, an individual adjusts his or her attitudinal position based on the calculation of distances from oneself to the messages.
Here, I have a problem.
I would like to make an individual move twice more when exposed to a message with a high value than when exposed to one with a low value.
But what I can do right now is just averaging the distance among the messages.
Here's what I've done so far
breed [individuals individual]
breed [messages message]
messages-own [value]
undirected-link-breed [messagelinks messagelink]

to setup
  ca
  create-individuals 100 [initiate-individuals]
  reset-ticks
end

to go
  new-messages
end

to initiate-messages
  ifelse random-float 1 < value-p [ set value "H" ] [set value "L"]
end

to initiate-individuals
  setxy random-xcor random-ycor
end

to new-messages
  create-messages 30 [
  initiate-messages
  ask individuals [
    integrate-messages myself
]
]
end

to integrate-messages [newmessages]
  if random-float 1 < 0.3
    [create-messagelink-with newmessages
    setxy mean [xcor] of messagelink-neighbors mean [ycor] of messagelink-neighbors]
end

A: I am making the assumption that integrate-messages is intended to handle a set of messages, even though when a receiver executes it in your code it is only the newly created message itself, not all newly created messages.  There are likely several ways to handle the problem of giving "H" messages more influence than "L" messages, but perhaps the most straightforward to simply to use a weighted average of the messages' xcors and ycors.  I've written a short model that does that in integrate-messages.
breed [messages message]
breed [receivers receiver]
undirected-link-breed [messagelinks messagelink]

messages-own [value]

to setup
  clear-all
  create-receivers 1 [
    setxy random-xcor random-ycor
    set color green
  ]
  create-messages 5 [
    setxy random-xcor random-ycor
    set value ifelse-value (random-float 1 < 0.5) ["H"] ["L"]
    set color blue
    set label value
  ]
  reset-ticks
end

to go
  ask one-of receivers [
    integrate-messages n-of 3 messages
  ]
end

to integrate-messages [newmessages]
  ;to indicate which messages are being received.
  ask newmessages [set color red ]
  create-messagelinks-with newmessages [set color red]

  ;now calculate the weighted position relative to ALL linked messages.
  let mssgs [other-end] of my-messagelinks
  let wghts map [x -> ifelse-value ([value] of x = "H") [2] [1]] mssgs
  let xc sum (map [[m w] -> w * [xcor] of m ] mssgs wghts)
  let yc sum (map [[m w] -> w * [ycor] of m ] mssgs wghts)
  set xcor xc / sum wghts
  set ycor yc / sum wghts

  ;to show where the receiver ends up.
  set color red
end


text:
Q: Handle new TCP connections synchronously I know nodejs is asynchronous by nature and it is preferable to use that way, but I have a use case where we need to handle incoming TCP connections in synchronous way. Once a new connections received we need to connect to some other TCP server and perform some book keeping stuff etc and then handle some other connection. Since number of connections are limited, it is fine to handle this in synchronous way.
Looking for an elegant way to handle this scenario.
net.createServer(function(sock) {
    console.log('Received a connection - ');
    var sock = null;
    var testvar = null;

    sock = new net.Socket();
    sock.connect(PORT, HOST, function() {
        console.log('Connected to server - ');
    });

    //Other listeners
}

In the above code if two connections received simultaneously the output may be (since asynchronous nature):
Received a connection
Receive a connection
Connected to server
Connected to server

But the expectation is:
Received a connection
Connected to server
Receive a connection
Connected to server

What is the proper way of ding this?
One solution is implement a queue kind of solution with emitting  'done' or 'complete' events to handle next connection.
For this we may have to take the connection callback out of the createServer call. How to handle scoping of connection and other variables (testvar) in this case?
In this case what happens to the data/messages if received on connections which are in queue but not yet processed and not yet 'data' listener is registered.?
Any other better solutions will be helpful.

A: I think it is important to separate the concepts of synchronous code vs serial code. You want to process each request serially, but that can still be accomplished while handling each request asynchronously. For your case, the easiest way would probably be to have a queue of requests to handle instead.
var inProgress = false;
var queue = [];
net.createServer(function(sock){
    queue.push(sock);

    processQueue();
});

function processQueue(){
    if (inProgress || queue.length === 0) return;
    inProgress = true;

    handleSockSerial(queue.shift(), function(){
        inProgress = false;

        processQueue();
    });
}

function handleSockSerial(sock, callback){
    // Do all your stuff and then call 'callback' when you are done.
}

Note, as long as you are using node >= 0.10, the data coming in from the socket will be buffered until you read the data.