text:
Q: Ошибка во время Deploy (Heroku) Всем привет
Я использую готовый скрипт "VK2Discord" от автора "MrZillaGold" и пытаюсь загрузить его на "Heroku", но во время установки получаю ошибку:
Enumerating objects: 28, done.
Counting objects: 100% (28/28), done.
Delta compression using up to 4 threads
Compressing objects: 100% (25/25), done.
Writing objects: 100% (28/28), 62.58 KiB | 7.82 MiB/s, done.
Total 28 (delta 0), reused 0 (delta 0), pack-reused 0
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Building on the Heroku-20 stack
remote: -----> Determining which buildpack to use for this app
remote: -----> Node.js app detected
remote:
remote: -----> Creating runtime environment
remote:
remote:        NPM_CONFIG_LOGLEVEL=error
remote:        NODE_VERBOSE=false
remote:        NODE_ENV=production
remote:        NODE_MODULES_CACHE=true
remote:
remote: -----> Installing binaries
remote:        engines.node (package.json):  >=15.0.0
remote:        engines.npm (package.json):   unspecified (use default)
remote:
remote:        Resolving node version >=15.0.0...
remote:        Downloading and installing node 16.5.0...
remote:        Using default npm version: 7.19.1
remote:
remote: -----> Installing dependencies
remote:        Installing node modules
remote:
remote:        added 246 packages, and audited 247 packages in 9s
remote:
remote:        16 packages are looking for funding
remote:          run `npm fund` for details
remote:
remote:        found 0 vulnerabilities
remote:
remote: -----> Build
remote:        Running build
remote:
remote:        > vk2discord@2.1.8 prebuild
remote:        > node ./scripts/buildInit.mjs
remote:
remote:
remote:        > vk2discord@2.1.8 build
remote:        > tsc && node ./scripts/cleanUpBuild.mjs
remote:
remote:        Version 4.3.5
remote:        Syntax:   tsc [options] [file...]
remote:
remote:        Examples: tsc hello.ts
remote:                  tsc --outFile file.js file.ts
remote:                  tsc @args.txt
remote:                  tsc --build tsconfig.json
remote:
remote:        Options:
remote:         -h, --help                                         Print this message.
remote:         -w, --watch                                        Watch input files.
remote:         --pretty                                           Stylize errors and messages using color and context (experimental).
remote:         --all                                              Show all compiler options.
remote:         -v, --version                                      Print the compiler's version.
remote:         --init                                             Initializes a TypeScript project and creates a tsconfig.json file.
remote:         -p FILE OR DIRECTORY, --project FILE OR DIRECTORY  Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'.
remote:         -b, --build                                        Build one or more projects and their dependencies, if out of date
remote:         -t VERSION, --target VERSION                       Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'.
remote:         -m KIND, --module KIND                             Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'.
remote:         --lib                                              Specify library files to be included in the compilation.
remote:                                                              'es5' 'es6' 'es2015' 'es7' 'es2016' 'es2017' 'es2018' 'es2019' 'es2020' 'es2021' 'esnext' 'dom' 'dom.iterable' 'webworker' 'webworker.importscripts' 'webworker.iterable' 'scripthost' 'es2015.core' 'es2015.collection' 'es2015.generator' 'es2015.iterable' 'es2015.promise' 'es2015.proxy' 'es2015.reflect' 'es2015.symbol' 'es2015.symbol.wellknown' 'es2016.array.include' 'es2017.object' 'es2017.sharedmemory' 'es2017.string' 'es2017.intl' 'es2017.typedarrays' 'es2018.asyncgenerator' 'es2018.asynciterable' 'es2018.intl' 'es2018.promise' 'es2018.regexp' 'es2019.array' 'es2019.object' 'es2019.string' 'es2019.symbol' 'es2020.bigint' 'es2020.promise' 'es2020.sharedmemory' 'es2020.string' 'es2020.symbol.wellknown' 'es2020.intl' 'es2021.promise' 'es2021.string' 'es2021.weakref' 'esnext.array' 'esnext.symbol' 'esnext.asynciterable' 'esnext.intl' 'esnext.bigint' 'esnext.string' 'esnext.promise' 'esnext.weakref'
remote:         --allowJs                                          Allow javascript files to be compiled.
remote:         --jsx KIND                                         Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'.
remote:         -d, --declaration                                  Generates corresponding '.d.ts' file.
remote:         --declarationMap                                   Generates a sourcemap for each corresponding '.d.ts' file.
remote:         --sourceMap                                        Generates corresponding '.map' file.
remote:         --outFile FILE                                     Concatenate and emit output to single file.
remote:         --outDir DIRECTORY                                 Redirect output structure to the directory.
remote:         --removeComments                                   Do not emit comments to output.
remote:         --noEmit                                           Do not emit outputs.
remote:         --strict                                           Enable all strict type-checking options.
remote:         --noImplicitAny                                    Raise error on expressions and declarations with an implied 'any' type.
remote:         --strictNullChecks                                 Enable strict null checks.
remote:         --strictFunctionTypes                              Enable strict checking of function types.
remote:         --strictBindCallApply                              Enable strict 'bind', 'call', and 'apply' methods on functions.
remote:         --strictPropertyInitialization                     Enable strict checking of property initialization in classes.
remote:         --noImplicitThis                                   Raise error on 'this' expressions with an implied 'any' type.
remote:         --alwaysStrict                                     Parse in strict mode and emit "use strict" for each source file.
remote:         --noUnusedLocals                                   Report errors on unused locals.
remote:         --noUnusedParameters                               Report errors on unused parameters.
remote:         --noImplicitReturns                                Report error when not all code paths in function return a value.
remote:         --noFallthroughCasesInSwitch                       Report errors for fallthrough cases in switch statement.
remote:         --types                                            Type declaration files to be included in compilation.
remote:         --esModuleInterop                                  Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'.
remote:         @<file>                                            Insert command line options and files from a file.
remote:
remote: -----> Build failed
remote:
remote:        We're sorry this build is failing! You can troubleshoot common issues here:
remote:        https://devcenter.heroku.com/articles/troubleshooting-node-deploys
remote:
remote:        Some possible problems:
remote:
remote:        - Dangerous semver range (>) in engines.node
remote:          https://devcenter.heroku.com/articles/nodejs-support#specifying-a-node-js-version
remote:
remote:        Love,
remote:        Heroku
remote:
remote:  !     Push rejected, failed to compile Node.js app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to st-news-bot.
remote:
To https://git.heroku.com/st-news-bot.git
 ! [remote rejected] main -> main (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/st-news-bot.git'

Для этого я скачал их официальное приложение "Heroku CLI" и, следуя инструкции, пытаюсь создать сборку, заранее включив в настройках проекта функцию "Add buildpack", где в качестве сборки выбираю "nodejs"
Инструкция от "Heroku":

Подскажите, пожалуйста, что я делаю не так?

A: Посмотрел детальнее логи, почитал документацию Heroku, открыл package.json и обнаружил, что мой бот уже пытается создать свою сборку
Я удалил строчку, отвечающую за это в "package.json" вот здесь:
"scripts": {
    "build": "tsc && node ./scripts/cleanUpBuild.mjs",
  },

После этого действия сборка нормально сгенерировалась и прекрасно работает


text:
Q: OpenGl program - shows only black screen I tried simple openGl program to draw triangle, i am able to see only black screen on window.
Below is the code for your reference.
Let me know what i am doing wrong.
// Headers
#include <GL/glew.h>
#include <GL/glut.h>//Drawing funciton
#include <GL/freeglut.h>
// Link statically with GLEW
#define GLEW_STATIC

// Shader sources
const GLchar* vertexSource =
    "##version 300 es\n"
    "in vec2 position;"
    "void main()"
    "{"
    "    gl_Position = vec4(position, 0.0, 1.0);"
    "}";
const GLchar* fragmentSource =
    "##version 300 es\n"
    "out vec4 outColor;"
    "void main()"
    "{"
    "    outColor = vec4(1.0, 1.0, 1.0, 1.0);"
    "}";

int main(int argc,char**argv)
{    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
    glutInitWindowSize(800,600);
    glutCreateWindow("GW");
    //glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE,GLUT_ACTION_GLUTMAINLOOP_RETURNS);

    // Initialize GLEW
    glewExperimental = GL_TRUE;
    glewInit();

    // Create Vertex Array Object
    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    // Create a Vertex Buffer Object and copy the vertex data to it
    GLuint vbo;
    glGenBuffers(1, &vbo);

    GLfloat vertices[] = {
         0.0f,  0.5f,
         0.5f, -0.5f,
        -0.5f, -0.5f
    };

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    // Create and compile the vertex shader
    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexSource, NULL);
    glCompileShader(vertexShader);

    // Create and compile the fragment shader
    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
    glCompileShader(fragmentShader);

    // Link the vertex and fragment shader into a shader program
    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glBindFragDataLocation(shaderProgram, 0, "outColor");
    glLinkProgram(shaderProgram);
    glUseProgram(shaderProgram);

    // Specify the layout of the vertex data
    GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
    glEnableVertexAttribArray(posAttrib);
    glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0);

    bool running = true;
    while (running)
    {
        // Clear the screen to black
        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        // Draw a triangle from the 3 vertices
        glDrawArrays(GL_TRIANGLES, 0, 3);

        // Swap buffers
        glutSwapBuffers();
    }

    glDeleteProgram(shaderProgram);
    glDeleteShader(fragmentShader);
    glDeleteShader(vertexShader);

    glDeleteBuffers(1, &vbo);

    glDeleteVertexArrays(1, &vao);

    return 0;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Heavy load produces possible memory leak in netty when using ejb-remoting in wildfly We have two wildfly 16 server running on Linux. First with JDK 11.0.2, second with JDK 8.
Wildfly 1 has a remote outbound connection to wildfly 2 which is used for HTTP-remoting. This is necessary because it has to run with Java 8 32 bit.
When we perform a load test after 100.000 requests from wildfly 1 to wildfly 2 response time increases steadily.
A heap dump analysis of wildfly 2 using MAT gives us some information about the problem. The heap dump shows a lot of 'io.netty.buffer.Poolchunks' that use about 73% of the memory.
Seems the inbound buffers won't be cleaned properly.
Wildfly 2 does not recover when the load stops.
Is there any workaround or setting to avoid this?


text:
Q: what is r.Scheme()+":///test.server" in grpc Dial call in all grpc test cases Normally we pass the server address like for example "localhost:56666" or "someserver:9999" to the Dial method of grpc-go.
ex: grpc.Dial("localhost:56666", grpc.WithInSecure())
But in the test cases given in grpc-go repo (refer below links), the first argument to Dial is mentioned as "*Dial(r.Scheme()+":///test.server", WithInsecure(), WithTimeout(5*time.Second))*". When I print that value by running these go test files, I observed this address value as "bykrwuxel00s:///test.server"
https://github.com/grpc/grpc-go/blob/master/balancer/roundrobin/roundrobin_test.go#L102
https://github.com/grpc/grpc-go/blob/master/clientconn_test.go#L135
How does this work as a valid server address?

A: The "scheme" element of a gRPC URI target basically indicates only the target's "type". See https://github.com/grpc/grpc/blob/master/doc/naming.md#name-syntax for more details.
For example, in that way, gRPC clients can look at that type and decide what name resolution mechanism to use (internally, each "resolver" is registered under a unique scheme).
In this case, it looks like that test is using a custom resolver that it generated from a call to "GenerateAndRegisterManualResolver", which dynamically generated a unique scheme for global registration: https://github.com/grpc/grpc-go/blob/7c1d326729dc9b0a07135f8902ddcc050ff8ab64/resolver/manual/manual.go#L89


text:
Q: How do I perform this Partial Fraction Decomp.? Disclaimer: I am not a student trying to get free internet homework help. I am an adult who is learning Calculus. I am deeply grateful to the members of this community for their time.
$$\int{\frac{1}{(x^2+2x-4)(x+3)}}dx$$
This led me to $$A=1, B=-1, C=-1$$
However I don't know how to integrate the following:
$$\int{\frac{x-1}{(x^2+2x-4)}}dx$$
Here is my work:

A: $$
\begin{split}
\int \frac{x-1}{(x^2+2x-4)} dx
 &= \int \frac{x+1}{x^2+2x-4} + \int \frac{-2}{x^2+2x-4} \\
 &= \frac{1}{2} \ln\left|x^2+2x-4\right| + (-2)\int\frac{dx}{(x+1)^2-5}
\end{split}
$$
$$\int \frac{dx}{(x+1)^2-5}=\frac{1}{2\sqrt{5}}\int(\frac{1}{x+1-\sqrt{5}}-\frac{1}{x+1+\sqrt{5}})dx
 $$


text:
Q: Checking if a date is within 7 days of the current time So I have a php function which interacts with a database and pulls data out. However I have a date stamp (in this case an upload date). I want to make it so that if something has been uploaded within the last 7 days, it posts that to users to make them aware of it being 'new'.
So far I have this:
if( strtotime($rows['Date']) > strtotime('now') ) {
    echo '

';
}

The $rows thing is taken care of and works from some other code above this line. But this is the line I am concerned with.
I want to say "if the date in the database is older than the current time, and is less than 7 days old, do the following {
 //echo the stuff about it being new
}
Problem is, how do I phrase that if statement to make it within 7 days? Absolutely cannot think of how unfortunately. I'm sure it is quite simple! Thank you

A: if( strtotime($rows['Date']) > strtotime('-7 day') ) {
    echo '

';
}

The strtotime('-7 day') part returns the time 7 days ago.


text:
Q: Counting All articles using withCount() I am using withCount() to count the number of articles in a category, everything works well.
The question is how to count and display the number of articles for All categories?
Controller
$categories = BlogCategory::withCount('articles')->get();

blade.php

All

   @foreach($categories as $category)

id}}" value="{{ $category->title }} ({{ $category->articles_count }})">{{ $category->title }} ({{ $category->articles_count }})

   @endforeach

({{ $category->articles_count }}) responsible for counting articles

A: you can use count method:
$allArticlesCount=Article::query()->count();

and do not forget to send it to your view as well.
a better approach is to get the count directly form the result you already got from db like @Apuv Bhavsar in his comment:
$allArticlesCount = $categories->sum('articles_count');

unless you have some conditions to apply this approach reduce the trips count to DB.


text:
Q: Xcode link error "symbol(s) not found for architecture x86_64" I'm facing next error after updating to the latests versions of the pods I'm using:
Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_Flurry", referenced from:
  objc-class-ref in AnalyticsKitFlurryProvider.o
ld: symbol(s) not found for architecture x86_64

I've been trying several ideas after googling:

*

*Delete pods and workspace and regenerate

*Upgrade/downgrade Cocoapods

*Change target settings to: "Build Active Architecture Only = Yes"; "Valid Architectures = arm64, armv7, armv7s, i386"

None of them works.
I think this issue is related to mixing swift and objective c pods.
Here is my Podfile:
source 'https://github.com/CocoaPods/Specs.git'
source 'https://pventura1976.visualstudio.com/DefaultCollection/_git/Specs'
platform :ios, '8.0'
use_frameworks!

target 'kPlant' do

pod 'pventuraLib'
pod 'iPlantLib'
pod 'AnalyticsKit/Flurry'
pod 'FLEX'
pod 'PBFlatUI'
pod 'MSDynamicsDrawerViewController'
pod 'LAWalkthrough', :git => 'https://github.com/pventura1976/LAWalkthrough'
pod 'RPFloatingPlaceholders'
pod 'iCarousel'
pod 'FXImageView'
pod 'BlockAlertsAnd-ActionSheets', :git => 'https://github.com/pventura1976/BlockAlertsAnd-ActionSheets', :commit => 'ccbfd6464691863bc594fe235906202c751ed39f'
pod 'MTMigration'
pod 'VTAcknowledgementsViewController'
pod 'RMDateSelectionViewController'
pod 'RMPickerViewController'
pod 'AAShareBubbles'
pod 'TapkuLibrary'
pod 'AFNetworking'
pod 'TSAssetsPickerController'
pod 'MWPhotoBrowser', :git => 'https://github.com/SmileBack/MWPhotoBrowser'
pod 'BSKeyboardControls'
pod 'InstagramKit'
pod 'PEPhotoCropEditor'
pod 'CRToast'
pod 'BFNavigationBarDrawer'
pod 'Nimbus'
pod 'pop'
pod 'LBBlurredImage'
pod 'ASValueTrackingSlider'
pod 'M13BadgeView'
pod 'KGModal', :git => 'https://github.com/pventura1976/KGModal', :commit => '72b40d400d8acbdc9abc1a07aeedf6304db6b173'
pod 'SSKeychain'
pod 'PNChart'
pod 'JBChartView'
pod 'Ensembles'
pod 'Ensembles/Dropbox'
pod 'Dropbox-iOS-SDK'
pod 'DZNEmptyDataSet', :git => 'https://github.com/dzenbot/DZNEmptyDataSet', :commit => '526b54ca6c15e6a3cee3e92cea5c43e13a59f968'
pod 'M13ContextMenu'
pod 'WCFastCell'
pod 'SWTableViewCell'
pod 'UIScrollSlidingPages', :git => 'https://github.com/iEdward/UIScrollSlidingPages'
pod 'UIImage-ResizeMagick'
pod 'SVPullToRefresh'
pod 'ISO8601DateFormatterValueTransformer'
pod 'MagicalRecord'
pod 'SVProgressHUD'
pod 'PAPreferences'
pod 'ReactiveCocoa'
pod 'Mantle'
pod 'INTULocationManager'
pod 'RateLimit'
pod 'SDiPhoneVersion'
pod 'ContextMenu.iOS', :git => 'https://github.com/pventura1976/Context-Menu.iOS'

end

target 'kPlantTests' do

end

It includes two private pods (iPlantLib and pventuraLib).
Here is the Podfile.lock:
PODS:
  - AAShareBubbles (1.1.0)
  - AFNetworking (2.6.0):
    - AFNetworking/NSURLConnection (= 2.6.0)
    - AFNetworking/NSURLSession (= 2.6.0)
    - AFNetworking/Reachability (= 2.6.0)
    - AFNetworking/Security (= 2.6.0)
    - AFNetworking/Serialization (= 2.6.0)
    - AFNetworking/UIKit (= 2.6.0)
  - AFNetworking/NSURLConnection (2.6.0):
    - AFNetworking/Reachability
    - AFNetworking/Security
    - AFNetworking/Serialization
  - AFNetworking/NSURLSession (2.6.0):
    - AFNetworking/Reachability
    - AFNetworking/Security
    - AFNetworking/Serialization
  - AFNetworking/Reachability (2.6.0)
  - AFNetworking/Security (2.6.0)
  - AFNetworking/Serialization (2.6.0)
  - AFNetworking/UIKit (2.6.0):
    - AFNetworking/NSURLConnection
    - AFNetworking/NSURLSession
  - AnalyticsKit/Core (1.2.7)
  - AnalyticsKit/Flurry (1.2.7):
    - AnalyticsKit/Core
    - FlurrySDK
  - ASValueTrackingSlider (0.11.2)
  - BFNavigationBarDrawer (1.0.2)
  - BlockAlertsAnd-ActionSheets (1.0.6):
    - BlockAlertsAnd-ActionSheets/TableAlertView (= 1.0.6)
  - BlockAlertsAnd-ActionSheets/TableAlertView (1.0.6)
  - Box (1.2.2)
  - BSKeyboardControls (2.2)
  - CMPopTipView (2.2.0)
  - ContextMenu.iOS (1.0.0)
  - CRToast (0.0.8)
  - DACircularProgress (2.3.1)
  - Dropbox-iOS-SDK (1.3.13)
  - DZNEmptyDataSet (1.5.2)
  - Ensembles (1.4.1):
    - Ensembles/Core (= 1.4.1)
  - Ensembles/Core (1.4.1)
  - Ensembles/Dropbox (1.4.1):
    - Dropbox-iOS-SDK
    - Dropbox-OSX-SDK
    - Ensembles/Core
  - FLEX (2.0.6)
  - FlurrySDK (6.7.0):
    - FlurrySDK/FlurrySDK (= 6.7.0)
  - FlurrySDK/FlurrySDK (6.7.0)
  - FXImageView (1.3.5)
  - iCarousel (1.8.2)
  - InstagramKit (3.6.8):
    - AFNetworking (~> 2.0)
    - InstagramKit/Exclude-UICKeyChainStore (= 3.6.8)
  - InstagramKit/Exclude-UICKeyChainStore (3.6.8):
    - AFNetworking (~> 2.0)
  - INTULocationManager (4.0.0)
  - iPlantLib (0.0.9):
    - INTULocationManager
    - MagicalRecord
    - Mantle
    - PAPreferences
    - pventuraLib
    - ReactiveCocoa
  - ISO8601DateFormatter (0.7)
  - ISO8601DateFormatterValueTransformer (0.7.0):
    - ISO8601DateFormatter (~> 0.7)
    - RKValueTransformers (~> 1.1.0)
  - JBChartView (2.8.15)
  - KGModal (1.1.1-Cabo)
  - LAWalkthrough (1.0.0)
  - LBBlurredImage (0.2.2)
  - M13BadgeView (1.0.4)
  - M13ContextMenu (1.0.3)
  - MagicalRecord (2.3.0)
  - Mantle (2.0.5):
    - Mantle/extobjc (= 2.0.5)
  - Mantle/extobjc (2.0.5)
  - MBProgressHUD (0.9.1)
  - MSDynamicsDrawerViewController (1.5.1)
  - MTMigration (0.0.5)
  - MWPhotoBrowser (1.4.0):
    - DACircularProgress
    - MBProgressHUD (~> 0.8)
    - PSTCollectionView (~> 1.2)
    - SDWebImage (~> 3.5.4)
  - Nimbus (1.2.0):
    - Nimbus/AttributedLabel (= 1.2.0)
    - Nimbus/Badge (= 1.2.0)
    - Nimbus/Collections (= 1.2.0)
    - Nimbus/Collections (= 1.2.0)
    - Nimbus/Core (= 1.2.0)
    - Nimbus/CSS (= 1.2.0)
    - Nimbus/Interapp (= 1.2.0)
    - Nimbus/Launcher (= 1.2.0)
    - Nimbus/Models (= 1.2.0)
    - Nimbus/NetworkControllers (= 1.2.0)
    - Nimbus/NetworkImage (= 1.2.0)
    - Nimbus/Overview (= 1.2.0)
    - Nimbus/PagingScrollView (= 1.2.0)
    - Nimbus/Photos (= 1.2.0)
    - Nimbus/Textfield (= 1.2.0)
    - Nimbus/WebController (= 1.2.0)
  - Nimbus/AttributedLabel (1.2.0):
    - Nimbus/Core
  - Nimbus/Badge (1.2.0):
    - Nimbus/Core
  - Nimbus/Collections (1.2.0):
    - Nimbus/Core
  - Nimbus/Core (1.2.0)
  - Nimbus/CSS (1.2.0):
    - AFNetworking (~> 2.1)
    - Nimbus/Core
    - Nimbus/Textfield
  - Nimbus/Interapp (1.2.0):
    - Nimbus/Core
  - Nimbus/Launcher (1.2.0):
    - Nimbus/Core
    - Nimbus/PagingScrollView
  - Nimbus/Models (1.2.0):
    - Nimbus/Core
  - Nimbus/NetworkControllers (1.2.0):
    - Nimbus/Core
  - Nimbus/NetworkImage (1.2.0):
    - AFNetworking (~> 2.1)
    - Nimbus/Core
  - Nimbus/Overview (1.2.0):
    - Nimbus/Core
    - Nimbus/Models
  - Nimbus/PagingScrollView (1.2.0):
    - Nimbus/Core
  - Nimbus/Photos (1.2.0):
    - Nimbus/Core
    - Nimbus/PagingScrollView
  - Nimbus/Textfield (1.2.0):
    - Nimbus/Core
  - Nimbus/WebController (1.2.0):
    - Nimbus/Core
  - PAPreferences (0.5)
  - PBFlatUI (1.1.0)
  - PEPhotoCropEditor (1.3.1)
  - PNChart (0.8.7):
    - UICountingLabel (~> 1.2.0)
  - pop (1.0.8)
  - PSTCollectionView (1.2.3)
  - pventuraLib (0.0.12):
    - AnalyticsKit/Flurry
    - CMPopTipView
    - ISO8601DateFormatterValueTransformer
    - SVProgressHUD
  - RateLimit (1.2.0)
  - ReactiveCocoa (3.0.0):
    - ReactiveCocoa/UI (= 3.0.0)
    - Result (~> 0.4.1)
  - ReactiveCocoa/Core (3.0.0):
    - ReactiveCocoa/no-arc
    - Result (~> 0.4.1)
  - ReactiveCocoa/no-arc (3.0.0):
    - Result (~> 0.4.1)
  - ReactiveCocoa/UI (3.0.0):
    - ReactiveCocoa/Core
    - Result (~> 0.4.1)
  - Result (0.4.4):
    - Box (~> 1.2)
  - RKValueTransformers (1.1.2)
  - RMActionController (1.0.4)
  - RMDateSelectionViewController (2.0.1):
    - RMActionController (~> 1.0.0)
  - RMPickerViewController (2.0.1):
    - RMActionController (~> 1.0.0)
  - RPFloatingPlaceholders (0.3.2)
  - SDiPhoneVersion (1.1.2)
  - SDWebImage (3.5.4):
    - SDWebImage/Core (= 3.5.4)
  - SDWebImage/Core (3.5.4)
  - SSKeychain (1.2.3)
  - SVProgressHUD (1.1.3)
  - SVPullToRefresh (0.4.1)
  - SWTableViewCell (0.3.7)
  - TapkuLibrary (0.3.8)
  - TSAssetsPickerController (1.2)
  - UICountingLabel (1.2.0)
  - UIImage-ResizeMagick (0.0.1)
  - UIScrollSlidingPages (1.3.1)
  - VTAcknowledgementsViewController (0.15)
  - WCFastCell (1.1)

DEPENDENCIES:
  - AAShareBubbles
  - AFNetworking
  - AnalyticsKit/Flurry
  - ASValueTrackingSlider
  - BFNavigationBarDrawer
  - BlockAlertsAnd-ActionSheets (from `https://github.com/pventura1976/BlockAlertsAnd-ActionSheets`,
    commit `ccbfd6464691863bc594fe235906202c751ed39f`)
  - BSKeyboardControls
  - ContextMenu.iOS (from `https://github.com/pventura1976/Context-Menu.iOS`)
  - CRToast
  - Dropbox-iOS-SDK
  - DZNEmptyDataSet (from `https://github.com/dzenbot/DZNEmptyDataSet`, commit `526b54ca6c15e6a3cee3e92cea5c43e13a59f968`)
  - Ensembles
  - Ensembles/Dropbox
  - FLEX
  - FXImageView
  - iCarousel
  - InstagramKit
  - INTULocationManager
  - iPlantLib
  - ISO8601DateFormatterValueTransformer
  - JBChartView
  - KGModal (from `https://github.com/pventura1976/KGModal`, commit `72b40d400d8acbdc9abc1a07aeedf6304db6b173`)
  - LAWalkthrough (from `https://github.com/pventura1976/LAWalkthrough`)
  - LBBlurredImage
  - M13BadgeView
  - M13ContextMenu
  - MagicalRecord
  - Mantle
  - MSDynamicsDrawerViewController
  - MTMigration
  - MWPhotoBrowser (from `https://github.com/SmileBack/MWPhotoBrowser`)
  - Nimbus
  - PAPreferences
  - PBFlatUI
  - PEPhotoCropEditor
  - PNChart
  - pop
  - pventuraLib
  - RateLimit
  - ReactiveCocoa
  - RMDateSelectionViewController
  - RMPickerViewController
  - RPFloatingPlaceholders
  - SDiPhoneVersion
  - SSKeychain
  - SVProgressHUD
  - SVPullToRefresh
  - SWTableViewCell
  - TapkuLibrary
  - TSAssetsPickerController
  - UIImage-ResizeMagick
  - UIScrollSlidingPages (from `https://github.com/iEdward/UIScrollSlidingPages`)
  - VTAcknowledgementsViewController
  - WCFastCell

EXTERNAL SOURCES:
  BlockAlertsAnd-ActionSheets:
    :commit: ccbfd6464691863bc594fe235906202c751ed39f
    :git: https://github.com/pventura1976/BlockAlertsAnd-ActionSheets
  ContextMenu.iOS:
    :git: https://github.com/pventura1976/Context-Menu.iOS
  DZNEmptyDataSet:
    :commit: 526b54ca6c15e6a3cee3e92cea5c43e13a59f968
    :git: https://github.com/dzenbot/DZNEmptyDataSet
  KGModal:
    :commit: 72b40d400d8acbdc9abc1a07aeedf6304db6b173
    :git: https://github.com/pventura1976/KGModal
  LAWalkthrough:
    :git: https://github.com/pventura1976/LAWalkthrough
  MWPhotoBrowser:
    :git: https://github.com/SmileBack/MWPhotoBrowser
  UIScrollSlidingPages:
    :git: https://github.com/iEdward/UIScrollSlidingPages

CHECKOUT OPTIONS:
  BlockAlertsAnd-ActionSheets:
    :commit: ccbfd6464691863bc594fe235906202c751ed39f
    :git: https://github.com/pventura1976/BlockAlertsAnd-ActionSheets
  ContextMenu.iOS:
    :commit: 59db45dc57b8e884c2e6732a3c061e2a4bd8aa93
    :git: https://github.com/pventura1976/Context-Menu.iOS
  DZNEmptyDataSet:
    :commit: 526b54ca6c15e6a3cee3e92cea5c43e13a59f968
    :git: https://github.com/dzenbot/DZNEmptyDataSet
  KGModal:
    :commit: 72b40d400d8acbdc9abc1a07aeedf6304db6b173
    :git: https://github.com/pventura1976/KGModal
  LAWalkthrough:
    :commit: c41a503a91b999cb4098480b89981ba931007c69
    :git: https://github.com/pventura1976/LAWalkthrough
  MWPhotoBrowser:
    :commit: 990d22356ac01b1449d84590e39548b485dd7150
    :git: https://github.com/SmileBack/MWPhotoBrowser
  UIScrollSlidingPages:
    :commit: 1197f1d71357f21b7eca8a2627457a764e7f63a2
    :git: https://github.com/iEdward/UIScrollSlidingPages

SPEC CHECKSUMS:
  AAShareBubbles: 960610d6a3c4da57d7cd295f4bec68790307bce8
  AFNetworking: 79f7eb1a0fcfa7beb409332b2ca49afe9ce53b05
  AnalyticsKit: d5abc65807aaeb1842f0ce16b11f745d904b5b29
  ASValueTrackingSlider: 45c9f78252da60de01d8f2afe869aaf90dd978d9
  BFNavigationBarDrawer: 7114305b2eb64f796aeee63029a037e30bf37a93
  BlockAlertsAnd-ActionSheets: 15be37bd381afaae85c2d4229db102c2cac742fa
  Box: a92e8aa4c099e6bc0733829665caf9e668ef53b8
  BSKeyboardControls: b701935e789961102e3f20063bba7185800a2d3f
  CMPopTipView: a0a88404b9f46a5cfc16ce54bdb1b9bf9acb9aff
  ContextMenu.iOS: 7da78b3f99e604669b75e55146c6c33147f64f99
  CRToast: b087127369b4c603726ef6249d74d0d737629ab8
  DACircularProgress: 4dd437c0fc3da5161cb289e07ac449493d41db71
  Dropbox-iOS-SDK: e0c9b08d1604b39cb78c1d0333251de0f6bdec60
  DZNEmptyDataSet: 741da409081a4bf707c949c964623a6ad1799772
  Ensembles: 90013c435ff874a7a9ccb7a334b74b93ac53dc12
  FLEX: 3c390976e788d3d447b614ea1714ffc8fc914cf3
  FlurrySDK: ea03fd78ffb32886e26c9b7634ff0d8cb18dcd55
  FXImageView: 7d84722b37f0afea9a64f12fdd4a6c7f9ecc4b16
  iCarousel: 67c8a43da5a46795b56aadfc96cd36a16f6149b2
  InstagramKit: 2dc81dd8a9b534bbf918fbf8c4bc11eef11040a3
  INTULocationManager: 754f2800415378b7bb2c07be103449e1f6a2cc70
  iPlantLib: 1faaa266785a71a44b34a7716a1c1534d0d18467
  ISO8601DateFormatter: ab926648eebe497f4d167c0fd083992f959f1274
  ISO8601DateFormatterValueTransformer: f9ffeb6841f2a56d01b0a47b4cf1becf20954147
  JBChartView: d77d6a713a32547b24ccfaeba90958e7274f0c9d
  KGModal: 9ee82fda738880de3cad8ccec416f0195db7b098
  LAWalkthrough: e97a16a0384bde1e714b0ec4eeafe0c76270ef15
  LBBlurredImage: 700634c17922bc2d22343118e7deb6a3ca12db43
  M13BadgeView: 700dd0714fdc837c0cf1c8c004454963ec22441f
  M13ContextMenu: 49b6eb55e92b3adcdb2f8f5bdef876508cecb606
  MagicalRecord: 89eb7d7ead39fb37f01c3d010665ee94d17f8dba
  Mantle: 1912395033f601de5adc8ee91e48f46e4c7051ad
  MBProgressHUD: c47f2c166c126cf2ce36498d80f33e754d4e93ad
  MSDynamicsDrawerViewController: 2874df90f5e9453dc7d4e32f8038b50615d4baa7
  MTMigration: 725315e6469c8fd7d13966887f59e65eb8aecb2e
  MWPhotoBrowser: 02c13159c8cc89740a53a2e59b368593b2495715
  Nimbus: 3d6dfdeabf548ba4eb43be24e74fd202fb8c4e22
  PAPreferences: 9f0ffb1e67174a0df001af9d3320166ceb9ee6f5
  PBFlatUI: d797c6de1d28245287d695d74178dc75895d0bd9
  PEPhotoCropEditor: 613292fce009efd085e7aed975f1ebb3fec8bb7b
  PNChart: c1755716bbd45386d2035b2bf2ce73e6d3f8cb22
  pop: bb773ae2c791ca2629de13b347e7a8b450fa6a57
  PSTCollectionView: 6749df92885353521f55279a7ce2b293762e2be4
  pventuraLib: 63293b7c53a485469b73e657a6dd85c92732c7ca
  RateLimit: fd0afab3943f7b97b374d0a24b68dcc71daa4638
  ReactiveCocoa: 5c4710e2f00f69f39a7f135d1f3ab48f8dace034
  Result: b44f6bc8762bbffaf2c5df58f2c7d12c3496ced8
  RKValueTransformers: 66ac5e4f077fdbe3496e792d89eeff4c3eb67701
  RMActionController: 19423654600d40ca15132a4e548d005042d68f09
  RMDateSelectionViewController: 027bdeeaacb78b2b528808ed21efd697490d2b4e
  RMPickerViewController: b94b078e1ef531a0b9dbc2e0c3004f91de50d978
  RPFloatingPlaceholders: 4687b57f7965e6a2bacfc1642f7f2981491b146e
  SDiPhoneVersion: c52245ccaab8142701e2e7fb8f0391ba3f255b76
  SDWebImage: b7546bef8a1a7d7f4995b2e43f7644ac04ceb186
  SSKeychain: 3f42991739c6c60a9cf1bbd4dff6c0d3694bcf3d
  SVProgressHUD: 748080e4f36e603f6c02aec292664239df5279c1
  SVPullToRefresh: ba2e718695a43253d8bea6852d2960097dc15d8c
  SWTableViewCell: 2a94aadc9d47b2b611fa064566bf57948b95b579
  TapkuLibrary: 7a406dac46eff8595e191557eba88959f97f69b7
  TSAssetsPickerController: c5ff3e518cc51605b1d925182f1e8f0b1edf8c89
  UICountingLabel: 1db4e7d023e1762171eb226d6dff47a7a84f27aa
  UIImage-ResizeMagick: f08c2d14d1e8a5f0b402185408785540562f2fe7
  UIScrollSlidingPages: d75e0f718993ef0481a6adf8251bfc52cabeb3ff
  VTAcknowledgementsViewController: 575f5841fb47b7d9c852ccb406104ea68de07b21
  WCFastCell: 3e20a0c711d27307584bdbd359a44a714e991151

COCOAPODS: 0.39.0.beta.4

Any idea or extra info I could give?
Thanks.
Edit: I have finally downgraded all the pods using swift to the objective c version and  I've generated the workspace with Cocoapods v0.35.0. Now it's working.

A: I've faced similar issue after upgrading cocoapods/using use_frameworks! and it wouldn't work for one of the build targets.
The difference between the two was the second target was missing  Embed Pods Frameworks script in Target > Build Phases.


text:
Q: rails order by field and get 10 items from the middle I have build a page that displays a list of ratings in an desc order.
I want to display only 10 items at a time. how do I select only, say the 11-20 rows
from the ordered array.
Is it possible to handle this in the query itself, or do i have to fetch the whole table and screen the relevant items?
@pics = Rating.order('rating desc').limit(10)

A: In this specific case, use .offset(10) in your current query.
In general, search for "rails pagination" on google or here on SO.


text:
Q: Adding parameters to URLs from HTML file I'm creating a local php script to manipulate a HTML file exported from Photoshop. I need to add some parameters to every url . This is what I've tried:
$newHtmlFile = 'exported.html'; //HTML file exported from photoshop
$htmlContent = file_get_contents($newHtmlFile);

$randomQuery = 'utm_source=onlinenewsletter&utm_medium=email&utm_content=random&utm_campaign=test';

$dom = new DOMDocument;
@$dom->loadHTML($htmlContent);
foreach($dom->getElementsByTagName('a') as $thisLink){
    $thisUrl = $thisLink->getAttribute('href');
    $parsedUrl = parse_url($thisUrl);
    if($parsedUrl['path'] == null){ $thisUrl .= '/'; }
    $separator = ($parsedUrl['query'] == NULL) ? '?' : '&';
    $newUrl = $thisUrl . $separator . $query;

    file_put_contents($newHtmlFile, preg_replace('~\b' .$thisUrl. '\b~u', $newUrl, file_get_contents($newHtmlFile)));
}

Example HTML exported from photoshop:

    <title>Some Page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

This throws no errors and it does not replace urls.

A: As I see you have same url in your html file,
its better to save them in their place instead of using preg_replace. you can use this:
$newHtmlFile = 'exported.html'; //HTML file exported from photoshop
$htmlContent = file_get_contents($newHtmlFile);

$randomQuery = 'utm_source=onlinenewsletter&utm_medium=email&utm_content=random&utm_campaign=test';

$dom = new DOMDocument;

@$dom->loadHTML($htmlContent);

foreach($dom->getElementsByTagName('a') as $thisLink){
    $thisUrl = $thisLink->getAttribute('href');
    $parsedUrl = parse_url($thisUrl);
    if($parsedUrl['path'] == null){ $thisUrl .= '/'; echo "here";}
    $separator = !isset($parsedUrl['query']) ? '?' : '&';
    $newUrl = $thisUrl . $separator . $randomQuery;

    //echo "$thisUrl - $newUrl
";
    //file_put_contents($newHtmlFile, preg_replace('@' .$thisUrl. '@', $newUrl, file_get_contents($newHtmlFile)));
    $thisLink->setAttribute('href', $newUrl);
}

file_put_contents($newHtmlFile, $dom->saveHTML());


text:
Q: Promises.all() tracking invidual tasks completion I'm using Promise.all(tasks) to track the overall completion of my tasks executed in no particular order (which is my main aim). I also want to track individual tasks completion, how do I do that?

A: Nothing keeps you from attaching individual handlers as well awaiting them together:
let tasks = …;
for ([t, i] of tasks.entries())
    t.then(res => {
        console.log("task "+i+" completed with", res);
    }, err => {
        console.log("task "+i+" failed because", err);
    });
Promise.all(tasks).then(all => {
    console.log("all tasks completed");
}, err => {
    console.log("something failed");
});

A: Try using Array.prototype.map() to pass promises to Promise.all()

var promises = [Promise.resolve("a"), Promise.resolve("b")];

Promise.all(promises.map(function(p, index) {
  return p.then(function(data) {
    console.log("inside .map()", data, "index", index)
    return data
  }, function(err) {
    console.log(err);
    return err
  })
}))
.then(function(complete) {
  console.log("all promises after .map()", complete)
}, function(err) {
  console.log("err", err)
})


text:
Q: How to get the values of span tag in html using beautiful soup? My span tag consists of:
What I want to do is convert that into
Basically, I want to get the check if span has an id value to it, and then remove it completely. I'm completely confused how to go about this. Should it be regex or beautiful soup?
The problem with regex is that I'm not sure how to replace a substring once it matches.
Maybe do a combination of beautiful soup and regex? (Not sure if that is a good and efficient idea.)

A: Simply delete the attribute from the attrib mapping; assuming you have a reference to the  tag in a local variable span:
if span.has_key('id'):
    del span['id']

Demo:
>>> soup = BeautifulSoup('')
>>> span = soup.find('span')
>>> span

>>> if span.has_key('id'):
...     del span['id']
...
>>> span


text:
Q: Is light dispersed over distance by flat mirrors? Hello and thank you for your time: Let's assume I have a 100 squared meter circular flat mirror placed 1 AU from the sun, and let's assume my intention is to shine light on a circular area on another planet located at 3 AU's (it could be 2 AU's, this is totally arbitrary). Would this circular area still be a 100 squared meters patch on the ground of this hypothetical planet, or will the light rays diverge to cover a circular area of more than 100 meters and how much larger ?
Please disregard orbits. The sun and the planet are flat, the mirror and everyhting is perfectly aligned, assume an ideal situation, also a perfect mirror; the answer I search for is if the light reflected form this flat mirror will behave like my laser pointer lighted surface does over distance (on earth inside the atmosphere) and grow in surface and lose intensity, in space with no atmosphere. Thank you very much for your answer if you choose to provide one.

A: If the sun were a point source viewed from 1 AU, then it would be spatially coherent. (See Van Cittert-Zernike.) In that case, the light from the sun can be treated as a single plane wave illuminating the mirror. One can simply compute the Fourier transform of the circular aperture represented by the mirror to get the far field diffraction pattern that would illuminate the other planet, because far-field diffraction is given by Fraunhofer diffraction, which comes down to a Fourier transform. The result in this case is called an Airy pattern.
How big would this diffraction pattern be on the surface of the other planet? For this one can use a simple formula. The beam divergence angle produced by a circular aperture of radius $R$ is roughly proportional to $\theta=\lambda/R$, where $\lambda$ is the wavelength of the light. This gives you a tiny angle, but over distances of a few AU this can still imply a significant increase in size. The increase in size would be roughly given by $D=\lambda L/R$, where $L$ is the distance to the other planet.
Now, we know that the sun is not a point source at 1 AU, but a disc extending over about half a degree. This means we need to add the intensity patterns (because they are mutually incoherent) of all the plane waves whose propagation vectors fall within half a degree. The result is a convolution of the diffraction pattern's intensity with a disc. So it will smeer out the diffraction pattern.
Moreover, the radiation from the sun consists of a spectrum of wavelength. As a result the different wavelengths would produce diffration patterns of slightly different sizes. So we need to add the intensity patterns of all the different wavelengths in the spectrum. This also causes a smeering effect.

A: Point sources obey the inverse square law:

and at astronomical distances  the energy dispersion of the incoherent light from a sun can be approximated by this formula.
So by your mirror, you are generating a secondary (reflecting) point source there. The energy it reflects will be at astronomical distances also a point source, depending on  the energy content the area of the mirror caught, which depends on geometry and the inverse square law to be calculated.
Note the term incoherent. Laser light is coherent, i.e. the phase relationships are stable for a certain distance and do not obey the inverse square law. Even for lasers there is a distance , which when exceeded the beam starts diverging, the power loss again obeying the inverse square law.  See  the answer here .

$1.96×10^7$   Compared to the point source multiplier ($0.25$), it is easy to see why a laser spot is much more intense for the same amount of power. It is not because lasers don't follow the inverse square law. It is because the beam's directionality gives it a huge initial boost in intensity, after which it proceeds to fall off as the inverse of distance squared.

Laser light disperses much less, dependent on the laser  and can be used for lunar communications.

A: It depends upon whether rays are parallel while falling upon the mirror.
If they are perfectly parallel, they will remain undeflected for long distances.
Even if sun is taken to be a flat plate of infinite area, it consists of several point sources. If you consider an area element dA it should emit light rays not only along the normal to its plane but also along lines making different angles with it. Thus, the light rays from such source cannot be perfectly parallel as far as my imagination proceeds.
Well, if you use some other optical instruments, in theory, you may get it happen.

A: Since the sun sends scattered light towards earth and not parallel light, each beam of light will reflect at slightly different angels and the beam of light on the other planet will not be the same size.


text:
Q: sql scripting to fetch only few rows that matches given condition I have table.
id       dept         Person
1        ece            p1
2        ece            p1
3        ece            null
4        ece            null
6        eee            null
5        eee            p2
6        Civil          P3
7        Civil          P4
8        Civil          null

Replace null values with their respective person values based on department.In this case We have to ignore Civil as Civil as 2 person P3 and P4. We need to care only dept that have unique persons that is (ece and eee).
1 ) Output should be like
id       dept         Person
1        ece            p1
2        ece            p1
**3        ece            p1
4        ece            p1**
**6        eee            p2**
5        eee            p2
6        Civil          P3
7        Civil          P4

I have question how to fetch only rows,  whose dept has more than distinct person.
2)   id dept Person
4        Civil          P3
5        Civil          P4

Q3)
id      dept         Person       Rating
1       ece            p1           R1
2**     ece            p2           Null**
6       eee            P6           R1
5**     eee            p2           Null**
6       Civil          P7           Null
7       Civil          P3           Null
8       Civil          P8           R5
9       Mech           p7           R2
10      Mech           P3           Null

For Q3). I need only rows whose person's Ratings are null and their respective persons in different team, ratings are same. Because P2 is in different teams ece and eee their respective person's ratings is same that is R1
Output for Q3
id      dept         Person       Rating
2       ece            p2           Null
5       eee            p2           Null

It should not contain following rows, because P3 is in both Civil and Mech but person's ratings are different that is R5 and R2
Output should not include these below records.
    id      dept         Person       Rating
    7       Civil          P3           Null
    10      Mech           P3           Null

A: You can try to use COUNT with window function, get the number by dept column the get cnt > 1 data.
SELECT *
FROM (
   SELECT *,COUNT(*) OVER (PARTITION BY dept ORDER BY dept) cnt
   FROM T
)t1
where cnt > 1

A: Q1:
You can use a subquery that finds all depts with more than one distinct person and then find all records where the dept is in that list:
SELECT *
FROM Ihavetable
WHERE dept IN (
  SELECT dept
  FROM Ihavetable
  GROUP BY dept
  HAVING COUNT(DISTINCT Person) > 1
  );

Q2:
To return all records but for depts with exactly one distinct Person replace the NULL values in the Person column with exactly that unique Person, you could use something like this:
WITH
    calculation (dept, num, pMax) AS (
        SELECT dept, COUNT(DISTINCT Person), MAX(Person)
        FROM Ihavetable
        GROUP BY dept
    )
SELECT t.id, t.dept,
    CASE c.num
        WHEN 1 THEN ISNULL(t.Person, c.pMax)
        ELSE t.person
    END AS Person
FROM Ihavetable t
  LEFT JOIN calculation c ON t.dept = c.dept

If you don't want to see the NULL values that are not replaceable, add this WHERE clause in the end:
WHERE c.num = 1 OR t.Person IS NOT NULL;

Q3:
This query will return all persons that have a null-rating in at least 2 teams and where all his "respective persons" (colleagues) in these teams that have a non-null-rating have the same non-null-rating (where the person itself can be its own colleague having a non-null-rating in a third team):
WITH
    calculation AS (
        SELECT t1.Person
        FROM Ihavetable t1
            INNER JOIN Ihavetable t2 ON t1.dept = t2.dept
        WHERE t1.Rating IS NULL
        GROUP BY t1.Person
        HAVING COUNT(DISTINCT t2.Rating) = 1
           AND COUNT(DISTINCT t2.dept) >= 2
    )
SELECT id, dept, Person, Rating
FROM Ihavetable
WHERE Rating IS NULL
  AND Person IN (SELECT Person FROM calculation);


text:
Q: No Executable output when running 'dotnet run' after installing .NET core I installed .NET Core following the instructions at the link below
http://dotnet.github.io/getting-started/
and I was able to get my 'hello world' working using 'dotnet run'. However, I couldn't see an exe file that all the documentation around the internet seems to indicate it would generate.
Running 'dotnet publish' pretty much copies those files into a different folder with 2 less files (removes the pdb file and the extra dev configs).
What am I missing?
Update 1
Here is the project.json file I have
{
  "version": "1.0.0-*",
  "compilationOptions": {
    "emitEntryPoint": true
  },
  "dependencies": {
    "Microsoft.NETCore.App": {
      "type": "platform",
      "version": "1.0.0-rc2-23930"
    }
  },
  "frameworks": {
    "netstandard1.5": {}
  }
}

A: You will only get a binary executable (exe file on Windows) when publishing a "self-contained" application (See Types of portability in .NET Core).  Note: I'm using the current preview1 build version (1.0.0-rc2-3002702) for all Microsoft.NetCore.App references, but the same changes apply to other versions.
Basically, your project.json file should have the following changes:
1.
Add a new section called runtimes:
"runtimes": {
  "win7-x64": {}
}

2.
Remove the platform part of the Microsoft.NETCore.App dependency:
"Microsoft.NETCore.App": {
  "type": "platform",
  "version": "1.0.0-rc2-3002702"
}

Changes to:
"Microsoft.NETCore.App": "1.0.0-rc2-3002702"

3.
Ensure that you are targetting netcoreapp1.0 and not netstandard1.*, netstandard1.* indicates that you are compiling a class library and not a standalone executable program.  Your frameworks section should then look like:
"frameworks": {
  "netcoreapp1.0": {}
}

Once these changes are made, you can then publish your app as a binary executable ("self-contained") application with this command:
dotnet publish -r win7-x64

A: The exe should be under the bin\Debug folder. However, you'll only get an exe if you add emitEntryPoint:true in project.json like here


text:
Q: Accumulated methods invocation order in RequestContext#fire()? Javadoc for RequestContext#fire() says only:

Send the accumulated changes and method invocations associated with the RequestContext.

GWT Moving Parts wiki entry under Flow section says only:

*

*All accumulated operations will be applied to the domain objects by traversing properties of the proxies.

*All method invocations in the payload are executed.

But will these methods be executed on the server side in the same order they were "executed" (accumulated) on ReqestContext instance on client side?
For my situation, if I execute on client side:
context.persist().using(proxy)
context.find(proxy.stableId().to(updatingReceiver))
context.fire()

Then may I be sure that on server side find() will be invoked after persist() so my updatingReceiver will get proxy of updated (persist()'ed) entity as an argument?
EDIT:
Going further, may I be sure that back on client after response Recievers will be invoked in exactly the same order in which their corresponding methods were accumulated?
Finally, is there a way to add some action that will be invoked at the end of response handling, after all Receivers' actions?
I thought something like this may work:
requestContext.fire(new Receiver<Void>() {
    @Override
    public void onSuccess(Void response) {
        //Things to do after all receivers
    });

And it really seems to work as I expected but because all that Javadoc is telling me about RequestContext.fire(Receiver) method is:

For receiving errors or validation failures only.

I'm not 100% sure whether my assumption is correct.

A: Yes, order of method invocations is preserved, both on the server-side and then back on the client side when calling Recievers.
The queue is a simple ArrayList in which invocation objects are appended. On the server-side, they're processed in the order they're received.
The Request-Context-level Receiver is always called after the ones for invocations. Its onSuccess is always called, whatever the result of the invocations (even if they all fail), to signal that the batch of invocations was processed successfully. Its onFailure is only called in case of a general failure, i.e. a network error, or an error when (de)serializing requests/responses on the server-side.
See http://code.google.com/p/google-web-toolkit/source/browse/trunk/user/src/com/google/web/bindery/requestfactory/shared/impl/AbstractRequestContext.java?r=10835#345


text:
Q: IPython: Configure Base Url Path for All Request I am trying to figure out how to configure the base url of and IPython notebook server running.  So instead of the default:
#request# GET http://localhost:8888/static/tree/js/main.min.js?v=04a28c5e21950738efb217191f08ac33
#request# GET http://localhost:8888/api/terminals?_=1441754529652
#request# GET http://localhost:8888/custom/custom.js?v=20150908160654
#request# GET http://localhost:8888/notebooks/Untitled1.ipynb?kernel_name=python3#

I want to configure all requests so that the go through ipython, as in:
#request# GET http://localhost:8888/ipython/static/tree/js/main.min.js?v=04a28c5e21950738efb217191f08ac33
#request# GET http://localhost:8888/ipython/api/terminals?_=1441754529652
#request# GET http://localhost:8888/ipython/custom/custom.js?v=20150908160654
#request# GET http://localhost:8888/ipython/notebooks/Untitled1.ipynb?kernel_name=python3#

Is this possible?

A: To change the base url for the files that are being served up from iPython, edit the ipython_notebook_config.py file in your ~/.ipython/[profile-name]/ directory.
In particular, assuming that your config file starts with the line c = get_config(), you will want to add the following lines to your configuration:
c.NotebookApp.base_project_url = '/ipython/'
c.NotebookApp.base_kernel_url = '/ipython/'
c.NotebookApp.webapp_settings = {'static_url_prefix':'/ipython/static/'}

This will make it so that your project is served up from http://localhost:8888/ipython/ instead of http://localhost:8888/.
For more information please see this page of the ipython docs.


text:
Q: How can I append a div in jquery right after some text? I have a jquery script:
$(document).ready(function() {
    $("#timezone").html("sssssss");
});

and html:

lorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsum

So far the result of that is:
lorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsum

sssssss

but I want to have it:
lorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsum sssssss

how can I do it?
here's my fiddle:
http://jsfiddle.net/mwfpLqm7/1/

A: Use a span instead of a div. You can't use divs inside a p element.

lorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsum

Fiddle
Your browser outputs the html with the div outside of the p element because it is invalid HTML markup and anyway div is block element.


text:
Q: Will the Probe in "The Inner Light" Work for Others? In The Inner Light, at the end of the story, the probe that was communicating with Captain Picard (and showing him the way of life for a now dead civilization).  The intent of the probe was to say to someone else, "We were here and this is what life was like for us.  Don't forget us."
But the probe only reached out to one person and once it finished the program, it stopped communicating with Picard.
Was the experience Picard went through a one time thing?  Is there anything (even in the Expanded Universe) to indicate that others could experience the same program, or was the probe only capable of sending the message and running the program once?

A: No, the probe stopped working at the end of the transmission to Picard. Riker visits Picard at the end of the episode, bringing the only one thing of value they found on the probe: the flute. He mentions during his report that the probe seemed to have destroyed its "electronics" and they could not find out how it did what it did to Picard. Thus it would not work for others again.
While experiencing the memories stored in the probe Picard witnesses the start of the (one) rocket carrying the probe into space. This means there are no other probes in the universe to carry the message.


text:
Q: 403 (Forbidden) while calling one azure function from another I need to call an azure function; fn(b), from another azure function; fn(a).
fn(a) -> fn(b)
Both these functions are in same function app. The problem is whenever I try to call (b), I get 403-Forbidden "data at the root level is invalid".
Is it possible to call an azure function from another azure function within same function app?
Function 1
public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
            HttpRequestMessage req, TraceWriter log)
        {
            log.Info("---- C# HTTP trigger function 1 processed a request.");

            UploadToF2(log);
            return null;
        }

        private static IRestResponse UploadToF2(TraceWriter log)
        {
            SomeObject payload = new SomeObject();
            payload.One = "One";
            payload.Two = 2;
            payload.Three = false;
            payload.Four = 4.4;

            var Fn2Url = Convert.ToString(ConfigurationManager.AppSettings["F2Url"]);
            log.Info("Hitting F2 at " + Fn2Url);
            var method = Method.POST;
            var client = new RestClient(Fn2Url);
            var body = JsonConvert.SerializeObject(payload);

            var request = new RestRequest(method);
            request.RequestFormat = DataFormat.Json;
            request.AddHeader("Content-Type", "application/json");

            request.AddBody(payload); // uses JsonSerializer

            IRestResponse response = client.Execute(request);
            return response;
        }
    }

    class SomeObject
    {
        public string One { get; set; }
        public int Two { get; set; }
        public bool Three { get; set; }
        public double Four { get; set; }
    }

Function 2
public static class Function2
    {
        [FunctionName("Function2")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
        {
            log.Info("---- C# HTTP trigger function 2 processed a request.");
            string payload = await req.Content.ReadAsStringAsync();
            log.Info("payload == "+payload);

            return null;
        }
    }

Additional Information:

*

*F2Url is a fully qualified url coming from config.

*I tried running both functions in localhost. It works. I.e. fn(a) can call fn(b) in localhost. However when I host both of them in Azure, fn(b) is not callable from fn(a).

*I tried a hybrid test too. I.e. I kept one function in local and another one in Azure. It works this way too. I.e. I kept fn(a) in local and fn(b) in Azure, fn(b) is callable.

*I tried calling fn(b) directly from Postman and again it works.

*authLevel is anonymous for both functions

*I have IP restrictions (Platform features > Networking > IP restrictions) applied to the Function app. When I remove IP restrictions, Function1 is able to call Function2. However keeping IP restrictions, the call is not allowed.

The only condition when fn(a) cannot call fn(b) is when both these functions are hosted in Azure.

A:
403 (Forbidden) while calling one azure function from another

If don't add the  client Ip  in the IP restrictions, then you test it in you client will get 403 error. Not only call on azure function from another ,but also all functions are restricted if you don't add  the client IP in the IP restrictions.
In your case, you need to add your test client Ip in the IP restrictions, then it will work.

Update:
Add the test result.

A: Works locally through a GET to Function1 when using:
var Fn2Url = "http://localhost:7071/api/Function2";

What value are you using in your configuration?

A: *

*Call Function #2 by its full URL, since there's a front end layer that gets hit first before the request makes it to your function app. This is true even for functions calling each other within the same function app.
GET https://{func-app-name}.azurewebsites.net/api/function2

*If the authLevel is not anonymous in function.json, pass in the API key as ?code= —
https://{func-app-name}.azurewebsites.net/api/function2?code={API-key}

or as a header —
GET https://{func-app-name}.azurewebsites.net/api/function2
x-functions-key: {API-key}

When running locally (Visual Studio/func host start), the value of authLevel is ignored. Looking at your decorator, AuthorizationLevel.Anonymous is present so most probably that's not it.
More on authorization keys here.
On top of that, you could do better that returning null in Function #2: 200 OK, 202 Accepted, 204 No Content, all valid choices depending on what's supposed to happen next (async/sync processing).


text:
Q: jQuery .submit() is submitting form in new tab once but not submitting second time I am creating a form and I have to submit it using jQuery and I am using jQuery v1.12.4. The web application I am working on is using lots of other scripts other than jQuery. Following is my html code
<form enctype="multipart/form-data" id="report-form" method="post">

        <input type="text" class="form-control" name="startDate" id="from" value="2019-09-30" readonly="">
         to
        <input type="text" class="form-control" name="endDate" id="to" value="2019-09-30" readonly="">

</form>

I have some other input fields in the form also. Following is my jQuery code to submit form on click of any of the links in above code
$(document).on('click','.singleReport', function(e){
    e.preventDefault();
    var from = $('#from').val();
    var to = $('#to').val();

    if(from == '') {
        alert('Select from date!');
    }
    else if(to == '') {
        alert('Select to date!');
    }
    else{
        if($(this).attr('data-type') == 'html')
        {
            $('#report-form').attr('action', '/html');
            $('#report-form').attr('target', '_blank');
            $('#report-form').submit();
        }
        else if($(this).attr('data-type') == 'pdf')
        {
            $('#report-form').attr('action', '/pdf');
            $('#report-form').attr('target', '_blank');
            $('#report-form').submit();
        }
        else if($(this).attr('data-type') == 'excel')
        {
            $('#report-form').attr('action', '/excel');
            $('#report-form').attr('target', '_blank');
            $('#report-form').submit();
        }
    }
});

This code successfully submit the form in new tab on first click on any link but it does not submit after that if I click again on the same link or any other link. Any suggestions are appreciated.
Thanks :)


text:
Q: Keras LSTM has different output for single input I came to a weird problem when using Keras LSTM model. I build a single layer LSTM and try to play with it. I found the output of the model is different between one input and multiple inputs, as shown in the following code.
def lstmTest(training, latent_dim=10):
        _, time_dim, input_dim = training.shape

        # Define an input sequence and process it.
        encoder_inputs = Input(shape=(time_dim, input_dim), name='input')
        encoder = LSTM(latent_dim, return_state=False, name='lstm')
        encoder_outputs = encoder(encoder_inputs)

        model = Model(encoder_inputs, encoder_outputs)

        return model

def trainingTest(model, training, nb_epoch=10, batch_size=300):
        model.compile(optimizer='adam', loss='mse', metrics=['acc'])
        history = model.fit(training, training[:, -1, :10],
                            epochs=nb_epoch,
                            batch_size=batch_size,
                            shuffle=True,
                            verbose=1,
                            ).history
        return history

myVector = [[[i]*20]*8 for i in range(100)]
myVector = np.array(myVector)

lstmTest = lstmTest(myVector)
history = trainingTest(lstmTest, myVector)

vector = myVector[:2]
res1 = lstmTest.predict(vector)

vector = myVector[:1]
res2 = lstmTest.predict(vector)

res2[0] - res1[0]

I got the following result
array([0.0000000e+00, 0.0000000e+00, 0.0000000e+00, 5.8207661e-11,
       0.0000000e+00, 2.3283064e-10, 0.0000000e+00, 0.0000000e+00,
       0.0000000e+00, 0.0000000e+00], dtype=float32)

But If I change res2 to the same as res1 I got the expected result
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32)

Anyone came to this problem before?

A: There is no difference, it´s just the limit of IEEE double values:
print(0.003f - 0.001f - 0.002f)
-2.3283064E-10

If you are using the gpu you can take a look at this


text:
Q: Cognos 10 Authentication and Styling I'm creating reports for my client, I'm asked to create 41 report for 12 departments, each department have a head and users (employees)
Authentication
All employees are supposed to access Cognos using a webpage example(localhost/reports), I've created this page that redirects automatically to a blank report so the user can authenticate since I use Active Directory for authentication, this page is supposed to have links to reports but as a user login in I want to hide reports between departments where each department can only track their reports not all of them as well as regular users are supposed to view specific reports not all of them as department heads can see all the reports, I was able to fetch the user GUID with CAMIDList I want to handle what to show on the reports page using javascript but these groups are dynamic so I'm keeping them in a json file where each group has its own GUID, I'm not sure what's the best way to create a webpage having all links to reports and depending on the user group we can show/hide these links and please note that we need SSO enabled so what's better to use Cognos Authentication or Websphere Authentication (j security check)
Styling
Regarding styles, I'm supposed to customize the native look and feel of the reports to a custom one for the client, by styling the lists, crosstabs, footers and headers with css how is it possible
Wrapping Up
Here are my questions
1: How can I create a webpage that show report links depending on logged in user?
2: What's the best way to style cognos reports with css?
Software Installed:
1- IBM Cognos BI 10.2.2
2- IBM HTTP Server
3- IBM Websphere
Thanks in advance and sorry for my weak English writing structure

A: perhaps you can use IBM Cognos BI 10.2.2 level itself as you are using active directory.You can add permissions at folder level/each report report level so that one can restrict based on the user id to view reports.


text:
Q: lookup field not working on mobile in community I have a custom object on the community which has lookup with contact it's working fine in a desktop or if looked from F12 on the laptop. However, when I open the community[Customer community plus] on my mobile this lookup field is not showing any option to create a new contact. Screenshot attached. Please suggest.

Thank you in Advance!


text:
Q: VB.Net: Is there something to be gained by using the Function itself to hold the return value instead of declaring a local variable? What's best practice (in VB.Net):
Function GetSomething() as String
    GetSomething = "Here's your string"
End Function

or
Function GetSomething() as String
    Dim returnString as String = "Here's your string"
    Return returnString
End Function

Obviously, neither of these implementations make any sense, but they're just meant to illustrate my point. Is there anything to be gained by using GetSomething itself to store the return value instead of declaring returnString locally and then returning that (does it avoid having an extra string allocated/instantiated - and if so, are there any performance/memory benefits)?

A: Interesting question. I ran this:
Function GetSomething1() As String
    GetSomething1 = "Here's your string"
End Function

Function GetSomething2() As String
    Dim returnString As String = "Here's your string"
    Return returnString
End Function

through IL DASM and here are the results:
Debug build:
.method public instance string  GetSomething1() cil managed
{
  // Code size       9 (0x9)
  .maxstack  1
  .locals init ([0] string GetSomething1)
  IL_0000:  nop
  IL_0001:  ldstr      "Here's your string"
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  ret
} // end of method Form1::GetSomething1

.method public instance string  GetSomething2() cil managed
{
  // Code size       13 (0xd)
  .maxstack  1
  .locals init ([0] string GetSomething2,
           [1] string returnString)
  IL_0000:  nop
  IL_0001:  ldstr      "Here's your string"
  IL_0006:  stloc.1
  IL_0007:  ldloc.1
  IL_0008:  stloc.0
  IL_0009:  br.s       IL_000b
  IL_000b:  ldloc.0
  IL_000c:  ret
} // end of method Form1::GetSomething2

Release build:
.method public instance string  GetSomething1() cil managed
{
  // Code size       8 (0x8)
  .maxstack  1
  .locals init ([0] string GetSomething1)
  IL_0000:  ldstr      "Here's your string"
  IL_0005:  stloc.0
  IL_0006:  ldloc.0
  IL_0007:  ret
} // end of method Form1::GetSomething1

.method public instance string  GetSomething2() cil managed
{
  // Code size       8 (0x8)
  .maxstack  1
  .locals init ([0] string GetSomething2,
           [1] string returnString)
  IL_0000:  ldstr      "Here's your string"
  IL_0005:  stloc.1
  IL_0006:  ldloc.1
  IL_0007:  ret
} // end of method Form1::GetSomething2

You'll note that there are more operations in the debug build but not in the release build.
So to answer your question, it seems that declaring the variable costs a little bit extra in debug builds, which is often the case (optimization not turned on or is not as much optimized). But in the release build (as expected) the optimizer removes this unnecessary operation.

A: Try it both ways then use .Net Reflector to see if the generated IL is different.

A: I prefer having explicit exit points so I always use Return. Furthermore, I don't like VB's decision to use the function name as the name of the return variable (why not Result, like in Pascal?) because this makes it inconsistent when the function returns an array:
Function Foo() As Integer()
    Foo = New Integer(2) { }
    Dim a = Foo(1) ''// Recursive call or access to return value element?
End Function

Of course that's a recursive call (otherwise those wouldn't be possible any longer). But I'm very annoyed by such inconsistencies so I don't use the syntax.
On the other hand, there's the advantage of a standardized name for the return value holder, and that's definitely an advantage over the Return method.
Either way, VB generates the same code.

A: You could use reflector to check out out, but, in all honesty, whatever performance penalty there might be for something like this would fall squarely under the heading of "Premature optimization" .
From a syntactic perspective, the {Return "a value"} syntax tends to encourage multiple exit points from the method, which is often seen as a bad practice. But if the method is small, then I don't see that code readability would suffer from it.
OTOH, the {var = value; Return Var} syntax tends to promote a single exit point at the end of the function.

A: The execution difference is essential nil, so it would depend on which is easier to understand and maintain. I personally assign a variable to the function name before an exit or use the return statement, rather than using the function name as a variable throughout the function. It seems a little odd or ambiguous to me if I use the function name as a variable throughout the function.
If I remember right, return() was added as the return statement to a function between VB6 and VB.Net, probably to make it more like other languages. This would explain why there are the two ways to do the same thing.

A: As mentioned in this answer and in my comments to this answer, one feature of the function name as return variable is that it can be accessed (and changed) in a Finally after a Return has been used.


text:
Q: Time spent in kernel mode I'm new to OS and am learning FreeBSD. I have a question that why ktr uses an offline strategy to generate event logs, by saving events first and providing ktrdump  to format and dump them later.
My reasoning is : Since ktr is logging events as the kernel executes, if the task of formatting is also included, that will slow down the kernel and increase the amount of time spent in kernel mode rather than user mode. By using the 2 step process, kernel saves some time, and the task of formatting is done later when the user wants to read the log file.
I want to know if this reason is logical, and if not, why ?
Thanks.

A: Certainly, formatting strings takes time. If you want to log events that happen frequently enough, you could seriously hamper your system performance.
Similarly, binary logs will take less space than a formatted log. This will both improve performance and allow more data to fit in the ring buffer.


text:
Q: iOS Apps Use Regular Lightning Cable: How? The latest update to Touchable app uses the regular USB-lightning cable to send and receive MIDI data (see here). How is this possible? Does this mean they are an MFi developer?
(I have read through the MFi FAQ but this case seems to not be covered)

A: Yes, they are a MFi certified company. To develop an accessory that uses either the official Apple 30-pin connector or Lightning connector you have to be a part of the MFi program.


text:
Q: JMS Queues that require a selector I want to implement a JMS Queue to ensure that each message is only delivered to one consumer. There will be many different types of consumers on listening to the queue. Messages should have properties set which identify the type of work required and these are used by the consumers selector to ensure that they only get sent work which they can handle.
My question is how can I make sure that when a consumer registers with the Queue as a consumer that they implement a selector to avoid the following scenario.
If I have 3 message types (A, B and C) and 3 consumers (a, b and c) which each consume only 1 message type as follows: a->A b->B c->C then all messages of type A will be sent to 1, all messages of type B will be sent to 2 etc.
I want to prevent someone registering a new consumer (d) which has no selector because this consumer would mean that messages of type A,B,C would now either go to their intended consumer or possibly consumer d.
Alternatively I would like the queue to give preference to consumers which have a selector that matches over a consumer with no selector.
Ps. The list of possible consumers and message types is dynamic and not in my control which I why I don't have a queue for each message type.

A: You cannot achieve it on the JMS API implementation level. I think your best bet is to impose security restrictions on the queue in the broker, like a user/password that your application has to supply to read the queue, and that only your application will know. Consult your JMS provider docs how to do it, it is a standard feature for any serious JMS provider.
I have a feeling you don't want it for security reasons, but for stability, your own peace of mind, or "just in case". You'll probably have to convince whoever-administers-the-queues in your company this is justified.


text:
Q: can not understand the error while using auto in c++ i am making a functions that takes in a vector, sorts it and then uses unique to remove the duplicates but there is an error while writing unique that "end_unique" variable has no data type. I don't know what should I do. please help!!!
   #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void elidup(vector<string> &w)
{
     // sort function is used to place words alphabetically so that after that we can find duplicates
     sort(w.begin(), w.end());
     // unique helps rearrange the input to "eliminate" adjacent duplicate entries
     auto end_unique = unique(w.begin(), w.end());
     // erase is used to eliminate unused elements
     w.erase(end_unique, w.end());
}
int main()
{
    string inp;
    cout<<" Enter the vector in which duplicates are to be found. Input * to indicate that it is the end of the string"<<endl;
    vector<string> word;
    while(inp != "*")
    // loop to enter the information in the vector
        {
            cin>>inp;
            word.push_back(inp);
        }
    if(inp == "*")
    // for erasing the duplicates and then print the vector
    {
        elidup(word);
        for(int i = 0 ; i<(word.size() -1);i++)
            cout<<word[i]<<" " ;
    }
    return 0;
}

This is what compile screen tells
||=== Build file: "no target" in "no project" (compiler: unknown) ===|
C:\Users\admin\Desktop\Dhairya\522031-10-9E.cpp||In function `void elidup(std::vector<std::string, std::allocator<std::string> >&)':|
C:\Users\admin\Desktop\Dhairya\522031-10-9E.cpp|11|error: ISO C++ forbids declaration of `end_unique' with no type|
C:\Users\admin\Desktop\Dhairya\522031-10-9E.cpp|11|error: cannot convert `__gnu_cxx::__normal_iterator<std::string*, std::vector<std::string, std::allocator<std::string> > >' to `int' in initialization|
C:\Users\admin\Desktop\Dhairya\522031-10-9E.cpp|13|error: no matching function for call to `std::vector<std::string, std::allocator<std::string> >::erase(int&, __gnu_cxx::__normal_iterator<std::string*, std::vector<std::string, std::allocator<std::string> > >)'|
C:\Dev-Cpp\bin\..\lib\gcc\mingw32\3.4.2\..\..\..\..\include\c++\3.4.2\bits\vector.tcc|108|note: candidates are: typename std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::erase(__gnu_cxx::__normal_iterator<typename _Alloc::pointer, std::vector<_Tp, _Alloc> >) [with _Tp = std::string, _Alloc = std::allocator<std::string>]|
C:\Dev-Cpp\bin\..\lib\gcc\mingw32\3.4.2\..\..\..\..\include\c++\3.4.2\bits\vector.tcc|120|note:                 typename std::vector<_Tp, _Alloc>::iterator std::vector<_Tp, _Alloc>::erase(__gnu_cxx::__normal_iterator<typename _Alloc::pointer, std::vector<_Tp, _Alloc> >, __gnu_cxx::__normal_iterator<typename _Alloc::pointer, std::vector<_Tp, _Alloc> >) [with _Tp = std::string, _Alloc = std::allocator<std::string>]|
||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

A: I just checked your code - simplified version in here, a web version of C++ compiler. It just worked using C++14! So what is your problem actually? Also you could replace these two lines
// unique helps rearrange the input to "eliminate" adjacent duplicate entries
auto end_unique = unique(w.begin(), w.end());
// erase is used to eliminate unused elements
w.erase(end_unique, w.end());

by this single line:
w.erase(unique(w.begin(), w.end()), w.end());

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void elidup(vector<string> &words)
{
     // sort function is used to place words alphabetically so that after that we can find duplicates
     sort(words.begin(), words.end());
     // unique helps rearrange the input to "eliminate" adjacent duplicate entries
     auto end_unique = unique(words.begin(), words.end());
     // erase is used to eliminate unused elements
     words.erase(end_unique, words.end());
}
int main()
{
    vector<string> words{"ab", "cd", "ab", "cd"};
    elidup(words);
    for(auto w: words) cout<<w<<endl;
    return 0;
}


text:
Q: Adding a Computed column with After clause I am trying to create a computed column after a specified column.
But the SQL gives syntax error for the query below. Please help me with the correct syntax/way to do this.
ALTER TABLE service_ServiceClass
  ADD LichenClassName AS ([dbo].[UfnGetServiceClassName]([Id])) AFTER Description

A: You get an error because "AFTER" is MySQL syntax.
There is no direct way to alter column order in SQL Server currently.
In MS SQL Server Management Studio, you'd have to use the SSMS Table Designer (rightclick yourTable->Design) to arrange your columns, which can then generate a script which drops and recreates the table.

A: There is no after clause in sql server's alter table statement.
The order of the columns in the table (as well is the order of the rows, btw) is completely insignificant from a user's point of view.
It's significant from the server point of view, as it may effect performance when using clustered indexes.
The only time the order of the columns matters is when you are using select * ..., but you shouldn't use that anyway. Always specify the column names directly.


text:
Q: What justify the division of power series? It is sometimes seen that people divide power series of two functions $f$ and $g$ to get the power series representation of $\frac{f}{g}$.
For example, $\tan x=\frac{\sin x}{\cos x}$, so compute $\frac{x-\frac{1}{3!}x^3+\frac{1}{5!}x^5-\cdots}{1-\frac{1}{2!}x^2+\frac{1}{4!}x^4-\cdots}$ as if it were two finite polynomials by long division, and get the quotient of first few terms, and see the pattern of what this whole power series are.
However, I haven't read any analysis books which mentioned the division of power series.  What justifies doing so? Why is it valid? Is there something we should be careful when doing this? Why we can do the traditional long divison on infinite terms polynomials?


text:
Q: React.js moving on to the next list I'm making a movie search page. When I search something, it goes through the data base and find the very first match and display on the page. However, I want to create a function, so when I click next, page displays next movie in the data base. My code follows:
import React, { Component, PropTypes } from 'react';
import SearchBar from './Bar/index.js';
import SearchResult from './Result/index.js';
import axios from 'axios';

import './index.css';

class SearchArea extends Component {
    constructor(props) {
        super(props);
        this.state = {
            searchText: '',
            searchResult: {},
            result: false,
            count: 0
        };
    }

    handleSearchBarChange(event) {
        this.setState({searchText: event.target.value});
    }

    handleSearchBarSubmit(event) {
        event.preventDefault();

        const movie = this.state.searchText;
        axios.get(`https://api.themoviedb.org/3/search/movie?api_key=c6cd73ec4677bc1d7b6560505cf4f453&language=en-US&query=${movie}&page=1&include_adult=false`)
        .then(response => {
            if(response.data.results.length >= 0) {
                const i = 0;
                const {
                    title,
                    overview,
                    release_date: releaseDate
                } = response.data.results[this.state.count];

                const posterPath = 'https://image.tmdb.org/t/p/w154' + response.data.results[this.state.count].poster_path;

                this.setState({
                    searchResult: {
                        title,
                        posterPath,
                        overview,
                        releaseDate
                    },
                    result: true
                });
            }
            else {
                this.setState({
                    searchResult: {
                        title: 'No Result',
                        overview: 'No Overview Available',
                        posterPath: ''
                    },
                    result: true
                });
            }
        })
    }

    handleSearchNext(event) {
        this.handelSearchBarSubmit.overview = response.data.results[1];
    }

    handleResultClose() {
        this.setState({
            searchResult: {},
            result: false
        });
    }

    render() {
        return (

                <SearchBar
                value = {this.state.searchText}
                onChange = {this.handleSearchBarChange.bind(this)}
                onSubmit = {this.handleSearchBarSubmit.bind(this)}
                onNext = {this.handleSearchNext.bind(this)}
                />
                {this.state.result &&
                <SearchResult
                 searchResult = {this.state.searchResult}
                 onClose = {this.handleResultClose.bind(this)}
                 onAdd = {this.props.onAdd}
                />
                }

        );
    }
}

SearchArea.propTypes = {
    onAdd: PropTypes.func.isRequired
};

export default SearchArea;

I can't seem to figure out how to make handleSearchNext. Please help
EDIT
Following is the SearchBar code
import React, { PropTypes } from 'react';
import { Button } from 'semantic-ui-react';
import styles from './index.css';

const SearchBar = (props) => {
    return (

            <form onSubmit={(event) => props.onSubmit(event)}>
                <input
                    className="searchBar"
                    type="text"
                    placeholder="Search Here"
                    value={props.value}this
                    onChange={(event) => props.onChange(event)}
                    onNext={(event) => props.onChange(event)}
                    onBack={(event) => props.onChange(event)}
                />
                <Button className="button" type="submit">Sumbit</Button>
            </form>
            <Button className={styles.button} type="previous">Back</Button>
            <Button className="button" type="next">Next</Button>

    );
};

SearchBar.propTypes = {
    value: PropTypes.string.isRequired,
    onChange: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    onBack: PropTypes.func.isRequired,
    onNext: PropTypes.func.isRequired
};

export default SearchBar;

A: You could have your server respond with not only the requested title, but also the next one. That way, when you click on Next, you can immediately display the next movie without waiting for a response, while still querying it in the background by name or id (so that you have the next after it, etc.).
Edit: If I misunderstood what you meant and you already have this (it looks like you are actually querying a whole page of movies at once), you probably simply want something like
handleSearchNext(event) {
    this.setState({ searchResult: response.data.results[1], result: true });
}

and handle specially the case when you hit the last item on the page.


text:
Q: GdxRuntimeException: File not found I'm following this tutorial on libgdx and I've hit a bit of a snag. I just finished the 'loading the assets' section. When I tried to run it, instead of getting the rain sound and a pink background, like the tutorial claims, I get errors up the wazoo. Here's my Drop.java:
package com.badlogic.drop;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;

public class Drop implements ApplicationListener {

    Texture dropImage;
    Texture bucketImage;
    Sound dropSound;
    Music rainMusic;

    @Override
    public void create() {
        // load the images for the droplet and the bucket, 64x64 pixels each
          dropImage = new Texture(Gdx.files.internal("droplet.png"));
          bucketImage = new Texture(Gdx.files.internal("bucket.png"));

          // load the drop sound effect and the rain background "music"
          dropSound = Gdx.audio.newSound(Gdx.files.internal("drop.wav"));
          rainMusic = Gdx.audio.newMusic(Gdx.files.internal("rain.mp3"));

          // start the playback of the background music immediately
          rainMusic.setLooping(true);
          rainMusic.play();

    }

    @Override
    public void dispose() {
    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }
}

and here are my errors. (Ones I think are important are bolded)
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load file: droplet.PNG
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:113)
Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load file: droplet.PNG
    at com.badlogic.gdx.graphics.Pixmap.(Pixmap.java:140)
    at com.badlogic.gdx.graphics.glutils.FileTextureData.prepare(FileTextureData.java:64)
    at com.badlogic.gdx.graphics.Texture.load(Texture.java:175)
    at com.badlogic.gdx.graphics.Texture.create(Texture.java:159)
    at com.badlogic.gdx.graphics.Texture.(Texture.java:133)
    at com.badlogic.gdx.graphics.Texture.(Texture.java:122)
    at com.badlogic.drop.Drop.create(Drop.java:21)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:127)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:110)
Caused by: com.badlogic.gdx.utils.GdxRuntimeException: File not found: droplet.PNG (Internal)
    at com.badlogic.gdx.files.FileHandle.read(FileHandle.java:127)
    at com.badlogic.gdx.files.FileHandle.length(FileHandle.java:580)
    at com.badlogic.gdx.files.FileHandle.readBytes(FileHandle.java:215)
    at com.badlogic.gdx.graphics.Pixmap.(Pixmap.java:137)
    ... 8 more
The weird thing is, I have all of the pngs and music files in my assets/data folders. They're all there, but the code isn't seeing them. Any idea what's causing this?

A: when you are using
Gdx.files.internal  <- This only gets you to the assets folder. You have to direct it into any sub-directories you are wanting files from also.
and your files are in assets/data use
Gdx.files.internal("data/droplet.png")
Be sure to change all your other references also to the correct location.


text:
Q: How to get html element's class tags I'm using a custom modernizer config which has selected the features I employ in my page (and only those features).
So, I'd like to simply grab the className of the <html> of the page so I can check to see how many no- prefixed classes are present (maybe checking classlist.match(/no-/g).length) and determine if my javascript should just give up.
It's not clear whether I should use
document.getElementsByTagName('html').className

or
$('html').attr('class')

or
document.documentElement.className

A: you can use jQuery hasClass` method:

Determine whether any of the matched elements are assigned the given class.

if ( $('html').hasClass('no-something')) {
  // do something here
}

A: I will go for:
document.documentElement.className;

Because doesn't involve any function's call, neither an additional layer like jquery. Ideally this one is the cleanest and the fastest.

A: If using plain JS, the equivalent would be:
document.getElementsByTagName('html')[0].className

A: If you are using jquery in your project why to not use this one:
var classList = $("html").attr('class').split(/\s+/);
var prefix = 'no-';

$.each( classList, function(index, item){
  if (item.substring(0, 2) === prefix) {
    //do something
  }
});

?

A:  var allClasses = [];
 var allElements = document.querySelectorAll('*');

 for (var i = 0; i < allElements.length; i++) {
     if (allElements[i].hasAttribute("class")) {
        var classes = allElements[i].className.toString().split(/\s+/);
        for (var j = 0; j < classes.length; j++) {
             var cls = classes[j];
             if (cls && allClasses.indexOf(cls) === -1)
                allClasses.push(cls);
        }
     }
 }

 console.log(allClasses);


text:
Q: Как в C# спарсить из строки число с плавающей точкой, разделенное символом "."? Метод double.Parse() корректно парсит числа, разделенные символом ",". Можно ли каким-нибудь стандартным способом получить число из его строкового представления, но разделенного символом "."? Есть ли способ задать разделитель целой и дробной части числа?

A: Все эти символы содержатся в культуре CultureInfo в свойстве NumberFormat. В инвариантной культуре (специальной "общей и универсальной" культуре) используется английское написание через точку, в русской — через запятую.
Console.WriteLine(double.Parse("1.9", CultureInfo.InvariantCulture));
Console.WriteLine(double.Parse("1.9", new CultureInfo("en-us")));
Console.WriteLine(double.Parse("1,9", new CultureInfo("ru-ru")));

Также можно использовать напрямую NumberFormatInfo:
Console.WriteLine(double.Parse("1#9", new NumberFormatInfo {
    NumberDecimalSeparator = "#"
}));

Логика такая:

*

*Если вы обрабатываете конфиги и прочие "системные" данные, следует использовать InvariantCulture.

*Если обрабатываете текст, введённый пользователем, следует задавать конкретную культуру.

*По умолчанию используется системная культура, которая зависит от настроек пользователя. Обычно полагаться на это не стоит.

A: double.Parse парсит число в соответствии с текущей локалью. У вас, судя по всему, текущая локаль — русская.
Если строка, которая есть у вас, не в текущей локали, воспользуйтесь перегрузкой с локалью:
var englishCulture = CultureInfo.GetCultureInfo("en-US");
var russianCulture = CultureInfo.GetCultureInfo("ru-RU");
var d1 = double.Parse("1.2", englishCulture);
var d2 = double.Parse("1,2", russianCulture);

Обычно ваша программа не знает, какая будет текущая системная локаль, поэтому если вы знаете, что данные будут в «английском» формате (через точку), то лучше читать их с явным указанием локали.
Если же вы читаете данные от пользователя, имеет смысл ожидать их в системной локали. (Но в случае данных от пользователя вам нужно, наверное, не double.Parse, а double.TryParse.)

A: Так же можно задать CultureInfo для всего потока, тогда выполненные в нем методы double.Parse будут использовать ее:
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("ru-RU");
Console.WriteLine(double.Parse("9,99"));
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
Console.WriteLine(double.Parse("9.99"));

Чтобы CultureInfo поменялась для всех потоков можно использовать CultureInfo.DefaultThreadCurrentCulture
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.GetCultureInfo("ru-RU");

Изменение этого свойства приведет к тому, что CultureInfo поменяется у всех существующих потоков в текущем домене, если их CultureInfo не была задана явно.


text:
Q: Avoid some unexpected results from Association Rules I'm trying to extract some association rules from this dataset:
49
70
27,66
6
27
66,8,64
32
82
66
71
44
1
33
17
31,83
50,29
22
72
8
8,16
56
83,61
85,63,37
50,57
2
50
96,6
73
57
12
62
96
3
47,50,73
35
85,45
25,96,22,17
85
24
17,57
34,4
60,96,45
25
85,66,73
30
14
73,85
64
48
5
37
13,55
37,17

I've this code:
val transactions = sc.textFile("/user/cloudera/dataset1")

import org.apache.spark.mllib.fpm.AssociationRules
import org.apache.spark.mllib.fpm.FPGrowth.FreqItemset

val freqItemsets = transactions.flatMap(xs =>
    (xs.combinations(1) ++ xs.combinations(2) ++ xs.combinations(3) ++ xs.combinations(4) ++ xs.combinations(5)).map(x => (x.toList, 1L))
  ).reduceByKey(_ + _).map{case (xs, cnt) => new FreqItemset(xs.toArray, cnt)}

val ar = new AssociationRules().setMinConfidence(0.4)

val results = ar.run(freqItemsets)

results.collect().foreach { rule =>
  println("[" + rule.antecedent.mkString(",")
    + "=>"
    + rule.consequent.mkString(",") + "]," + rule.confidence)
    }

But I'm getting some unexpected lines in my output:
[2,9=>5],0.5
[8,5,,,3=>6],1.0
[8,5,,,3=>7],0.5
[8,5,,,3=>7],0.5
[,,,=>6],0.5
[,,,=>7],0.5
[,,,=>5],0.5
[,,,=>3],0.5
[4,3=>7],1.0
[4,3=>,,,],1.0
[4,3=>,,,],1.0
[4,3=>5],1.0
[4,3=>7,7],1.0
[4,3=>7,7],1.0
[4,3=>0],1.0

Why I'm getting outputs like this:
[,,,=>3],0.5

I'm not understanding the issue... Anyone knows how to solve this problem?
Many Thanks!

A: All of these results should be unexpected, because you have a bug in your code!
You need to create combinations of the items. As it stands, your code is creating combinations of characters in the string (like "25,96,22,17"), which of course won't give the right result (and that's why you see the "," as an element).
To fix, add: val freqItemsets = transactions.map(_.split(",")).
So instead of
val freqItemsets = transactions.flatMap(xs =>
    (xs.combinations(1) ++ xs.combinations(2) ++ xs.combinations(3) ++ xs.combinations(4) ++ xs.combinations(5)).map(x => (x.toList, 1L))
  ).reduceByKey(_ + _).map{case (xs, cnt) => new FreqItemset(xs.toArray, cnt)}

You have:
val freqItemsets = transactions.map(_.split(",")).flatMap(xs =>
    (xs.combinations(1) ++ xs.combinations(2) ++ xs.combinations(3) ++ xs.combinations(4) ++ xs.combinations(5)).filter(_.nonEmpty).map(x => (x.toList, 1L))   ).reduceByKey(_ + _).map{case (xs, cnt) => new FreqItemset(xs.toArray, cnt)}

Which will give the expected:
[96,17=>22],1.0
[96,17=>25],1.0
[85,37=>63],1.0
[47,73=>50],1.0
[31=>83],1.0
[60,45=>96],1.0
[60=>45],1.0
[60=>96],1.0
[96,45=>60],1.0
[22,17=>25],1.0
[22,17=>96],1.0
[66,8=>64],1.0
[63,37=>85],1.0
[66,64=>8],1.0
[25,22,17=>96],1.0
[27=>66],0.5
[96,22,17=>25],1.0
[61=>83],1.0
[64=>66],0.5
[64=>8],0.5
[45=>60],0.5
[45=>96],0.5
[45=>85],0.5
[6=>96],0.5
[47=>73],1.0
[47=>50],1.0
[50,73=>47],1.0
[96,22=>17],1.0
[96,22=>25],1.0
[66,73=>85],1.0
[8,64=>66],1.0
[29=>50],1.0
[83=>31],0.5
[83=>61],0.5
[25,96,17=>22],1.0
[85,66=>73],1.0
[25,96,22=>17],1.0
[25,96=>17],1.0
[25,96=>22],1.0
[22=>17],0.5
[22=>96],0.5
[22=>25],0.5
[85,73=>66],1.0
[55=>13],1.0
[60,96=>45],1.0
[63=>37],1.0
[63=>85],1.0
[25,22=>17],1.0
[25,22=>96],1.0
[16=>8],1.0
[25=>96],0.5
[25=>22],0.5
[25=>17],0.5
[34=>4],1.0
[85,63=>37],1.0
[47,50=>73],1.0
[13=>55],1.0
[4=>34],1.0
[25,17=>22],1.0
[25,17=>96],1.0


text:
Q: How to run different methods in parallel and obtain the outputs for further processing? I would like to understand how to run two core intensive functions in parelle. The functions require the same input and produce different outputs.
Last time I used the multiprocessing library, I saved the results to a file and did not need further processing.
Below is a simple example of the type of code. How to parallelize the functions so that both outputs a and b can be used for further processing?
I am using Python 2.7.
input_dict = {'key1':'value1','key2':'value2','key3':'value3'}

def func1(dictionary):
    # do some work
    return np.array()

def func2(dictionary):
    # do different work
    return np.array()

a = func1(input_dict)
b = func2(input_dict)

result = np.dot(a, b)

Is the code below the correct way to run both functions together and collect their output?
from multiprocessing import Process, Queue

input_dict = {'key1':'value1','key2':'value2','key3':'value3'}

def func1(dictionary):
    # do some work
    return q.put(np.array())

def func2(dictionary):
    # do different work
    return q.put(np.array())

if __name__ == '__main__':
    q1 = Queue()
    q2 = Queue()
    p1 = Process(target=func1, args=(input_dict,))
    p2 = Process(target=func2, args=(input_dict,))
    p1.start()
    p2.start()

    a = q1.get()
    b = q2.get()
    p1.join()
    p2.join()
    result = np.dot(a, b)

A: It's mostly correct, but you have to to pass q1 and q2 when initializing the processes.
Also, replace return q.put(np.array()) with q.put(np.array())
When getting the results queue like a = q1.get() remember that you are only getting a single item from the queue, not a list.
If you need to extract a list, you can do something like this:
from multiprocessing import Process, Queue
import numpy as np

input_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

def func1(dictionary, q):
    # do some work
    for x in xrange(5):
        q.put(
            np.random.randint(2, size=20)
        )
    q.put('STOP')

def func2(dictionary, q):
    # do different work
    q.put(
        np.array([1, 1, 1, 1, 0, 1, 1, 0, 1, 0,
                  1, 0, 1, 0, 1, 0, 0, 1, 1, 1])
    )

if __name__ == '__main__':
    q1 = Queue()
    q2 = Queue()
    p1 = Process(target=func1, args=(input_dict, q1))
    p2 = Process(target=func2, args=(input_dict, q2))
    p1.start()
    p2.start()

    f1_results = []
    # Keep adding items from func1 to the results list, until it sees a 'STOP' item
    for array in iter(q1.get, 'STOP'):
        f1_results.append(array)

    b = q2.get()
    p1.join()
    p2.join()

    for a in f1_results:
        result = np.dot(a, b)
        print result