text:
Q: Is it possible to get values from RxJS without a .subscribe method? I'm looking for a way to use RxJS's pipeline operators to improve my existing code.
Instead of this:
export const initialState = {}

export const createReducerActions = (
    actionType => ({
        [actionType]: (
            (prevState, { data }) => (
                data
            )
        ),
    })
)

const createDataStorageReducer = (
    actionType => (
        createReducer(
            (
                createReducerActions(
                    actionType,
                )
            ),
            (
                initialState
            ),
        )
    )
)

I'm looking to see if some sort of executeImmediately function exists in RxJS like so:
export const initialState = {}

export const createReducerActions = (
    actionType => ({
        [actionType]: (
            (prevState, { data }) => (
                data
            )
        ),
    })
)

const createDataStorageReducer = (
    actionType => (
        of(actionType)
        .pipe(
            map(createReducerActions),
            map(reducerActions => (
                createReducer(
                    reducerActions,
                    initialState,
                )
            ))
        )
        .executeImmediately()
    )
)

A: You don't get the value of an Observable synchronously.  The closest that you can get is to create a BehaviorSubject, subscribe that to an Observable.  You can then get the value of a BehaviorSubject synchronously.

console.log(typeof(rxjs.BehaviorSubject));

const o = rxjs.interval(1000);
const bs = new rxjs.BehaviorSubject("hello");

bs.subscribe(v => console.log(v));
o.subscribe(bs);

bs.next("world");

// You can get the current value of a BS with getValue()
console.log(`bs value right now is: ${bs.getValue()}`);

setTimeout(() => {
  console.log(`bs value after 3 seconds is: ${bs.getValue()}`);
}, 3000);
<script src="https://unpkg.com/rxjs@6.2.2/bundles/rxjs.umd.min.js"></script>


text:
Q: Is it Possible to use Server Sent event (SSE) in JAX RS (RestEasy) with JBOSS 7? Good night!
The version of RestEasy present on Jboss 7 is possible to be change it for a new one that supports SSE ( like 3.5.1) ?
Any help will be really apreciate!

A: Unfortunately NO. Read https://developer.jboss.org/wiki/AS710FinalReleaseNotes
JBOSS AS 7.1 is Java EE 6 compliant
The SSE was only introduced in Java EE 8 via the support for JAX-RS 2.1.
RestEasy supports it in https://docs.jboss.org/resteasy/docs/3.5.0.Final/userguide/html_single/index.html#JAX-RS_2.1_additions
Try moving to a newer version of JBOSS/Wildfly, the minimum is Wildfly 12
https://wildfly.org/news/2018/02/28/WildFly12-Final-Released/
In Wildfly 12, enable support for ee8 explicitly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use GridFS to store images using Node.js and Mongoose I am new to Node.js. Can anyone provide me an example of how to use GridFS for storing and retrieving binary data, such as images, using Node.js and Mongoose? Do I need to directly access GridFS?

A: I suggest taking a look at this question: Problem with MongoDB GridFS Saving Files with Node.JS
Copied example from the answer (credit goes to christkv):
// You can use an object id as well as filename now
var gs = new mongodb.GridStore(this.db, filename, "w", {
  "chunk_size": 1024*4,
  metadata: {
    hashpath:gridfs_name,
    hash:hash,
    name: name
  }
});

gs.open(function(err,store) {
  // Write data and automatically close on finished write
  gs.writeBuffer(data, true, function(err,chunk) {
    // Each file has an md5 in the file structure
    cb(err,hash,chunk);
  });
});

A: It looks like the writeBuffer has since been deprecated.
/Users/kmandrup/private/repos/node-mongodb-native/HISTORY:
   82  * Fixed dereference method on Db class to correctly dereference Db reference objects.
   83  * Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility.
   84: * Removed writeBuffer method from gridstore, write handles switching automatically now.
   85  * Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore.

A: I was not satisfied with the highest rated answer here and so I'm providing a new one:
I ended up using the node module  'gridfs-stream' (great documentation there!) which can be installed via npm.
With it, and in combination with mongoose, it could look like this:
var fs = require('fs');
var mongoose = require("mongoose");
var Grid = require('gridfs-stream');
var GridFS = Grid(mongoose.connection.db, mongoose.mongo);

function putFile(path, name, callback) {
    var writestream = GridFS.createWriteStream({
        filename: name
    });
    writestream.on('close', function (file) {
      callback(null, file);
    });
    fs.createReadStream(path).pipe(writestream);
}

Note that path is the path of the file on the local system.
As for my read function of the file, for my case I just need to stream the file to the browser (using express):
try {
    var readstream = GridFS.createReadStream({_id: id});
    readstream.pipe(res);
} catch (err) {
    log.error(err);
    return next(errors.create(404, "File not found."));
}

A: Answers so far are good, however, I believe it would be beneficial to document here how to do this using the official mongodb nodejs driver instead of relying on further abstractions such as "gridfs-stream".
One previous answer has indeed utilized the official mongodb driver, however they use the Gridstore API; which has since been deprecated, see here. My example will be using the new GridFSBucket API.
The question is quite broad as such my answer will be an entire nodejs program. This will include setting up the express server, mongodb driver, defining the routes and handling the GET and POST routes.
Npm Packages Used

*

*express (nodejs web application framework to simplify this snippet)

*multer (for handling multipart/form-data requests)

*mongodb (official mongodb nodejs driver)

The GET photo route takes a Mongo ObjectID as a parameter to retrieve the image.
I configure multer to keep the uploaded file in memory. This means the photo file will not be written to the file system at anytime, and instead be streamed straight from memory into GridFS.

/**
 * NPM Module dependencies.
 */
const express = require('express');
const photoRoute = express.Router();

const multer = require('multer');
var storage = multer.memoryStorage()
var upload = multer({ storage: storage, limits: { fields: 1, fileSize: 6000000, files: 1, parts: 2 }});

const mongodb = require('mongodb');
const MongoClient = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectID;
let db;

/**
 * NodeJS Module dependencies.
 */
const { Readable } = require('stream');

/**
 * Create Express server && Routes configuration.
 */
const app = express();
app.use('/photos', photoRoute);

/**
 * Connect Mongo Driver to MongoDB.
 */
MongoClient.connect('mongodb://localhost/photoDB', (err, database) => {
  if (err) {
    console.log('MongoDB Connection Error. Please make sure that MongoDB is running.');
    process.exit(1);
  }
  db = database;
});

/**
 * GET photo by ID Route
 */
photoRoute.get('/:photoID', (req, res) => {
  try {
    var photoID = new ObjectID(req.params.photoID);
  } catch(err) {
    return res.status(400).json({ message: "Invalid PhotoID in URL parameter. Must be a single String of 12 bytes or a string of 24 hex characters" });
  }

  let bucket = new mongodb.GridFSBucket(db, {
    bucketName: 'photos'
  });

  let downloadStream = bucket.openDownloadStream(photoID);

  downloadStream.on('data', (chunk) => {
    res.write(chunk);
  });

  downloadStream.on('error', () => {
    res.sendStatus(404);
  });

  downloadStream.on('end', () => {
    res.end();
  });
});

/**
 * POST photo Route
 */
photoRoute.post('/', (req, res) => {
  upload.single('photo')(req, res, (err) => {
    if (err) {
      return res.status(400).json({ message: "Upload Request Validation Failed" });
    } else if(!req.body.name) {
      return res.status(400).json({ message: "No photo name in request body" });
    }

    let photoName = req.body.name;

    // Covert buffer to Readable Stream
    const readablePhotoStream = new Readable();
    readablePhotoStream.push(req.file.buffer);
    readablePhotoStream.push(null);

    let bucket = new mongodb.GridFSBucket(db, {
      bucketName: 'photos'
    });

    let uploadStream = bucket.openUploadStream(photoName);
    let id = uploadStream.id;
    readablePhotoStream.pipe(uploadStream);

    uploadStream.on('error', () => {
      return res.status(500).json({ message: "Error uploading file" });
    });

    uploadStream.on('finish', () => {
      return res.status(201).json({ message: "File uploaded successfully, stored under Mongo ObjectID: " + id });
    });
  });
});

app.listen(3005, () => {
  console.log("App listening on port 3005!");
});

I wrote a blog post on this subject; is is an elaboration of my answer. Available here
Further Reading/Inspiration:

*

*NodeJs Streams: Everything you need to know

*Multer NPM docs

*Nodejs MongoDB Driver

A: remove the fileupload library
and if it is giving some multi-part header related error than remove the content-type from the headers


text:
Q: How do i display the Array List without [], and next lines instead of displaying on [1,2,3] Here is my code
 private List[] split(ArrayList aList) {

    ArrayList first = new ArrayList();
    ArrayList second = new ArrayList();

    int size = aList.size();

    for (int i = 0; i < size / 2; i++)
             first.add(aList.get(i));

    for (int i = size / 2; i < size; i++)
            second.add(aList.get(i));

    return new List[] { first, second };

}

Collections.shuffle(list);

List[] lists = split(list);

jTextArea2.append(lists[0].toString());
jTextArea3.append(lists[1].toString());

This is how it looks like now... i want the list in Team A and Team B to be displayed list in Uploaded list

A: Add each element separately:
for (int i = 0; i < lists[0].size(); i++) {
    jTextArea2.append(lists[0].get(i).toString());
    jTextArea2.append("\n");
}

A: You can use joining collector from Streams api.
jTextArea2.append(lists[0].stream()
                      .map(Object::toString)
                      .collect(Collectors.joining("\n")));


text:
Q: Android throw DeadObjectException: Transaction failed on small parcel; remote process probably died just in HUAWEI Android 8.0.0 1804-11 09:43:24.482 22968 22968 E CrashHandler: In thread: Thread[main,5,main]
1904-11 09:43:24.482 22968 22968 E CrashHandler: UncaughtException detected: java.lang.IllegalStateException: Failure reading AssistStructure data: android.os.DeadObjectException: Transaction failed on small parcel; remote process probably died
2004-11 09:43:24.482 22968 22968 E CrashHandler: at android.os.Parcel.readException(Parcel.java:1953)
2104-11 09:43:24.482 22968 22968 E CrashHandler: at android.os.Parcel.readException(Parcel.java:1891)
2204-11 09:43:24.482 22968 22968 E CrashHandler: at android.app.IActivityManager$Stub$Proxy.reportAssistContextExtras(IActivityManager.java:7637)
2304-11 09:43:24.482 22968 22968 E CrashHandler: at android.app.ActivityThread.handleRequestAssistContextExtras(ActivityThread.java:3483)
2404-11 09:43:24.482 22968 22968 E CrashHandler: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2125)
2504-11 09:43:24.482 22968 22968 E CrashHandler: at android.os.Handler.dispatchMessage(Handler.java:108)
2604-11 09:43:24.482 22968 22968 E CrashHandler: at android.os.Looper.loop(Looper.java:166)
2704-11 09:43:24.482 22968 22968 E CrashHandler: at android.app.ActivityThread.main(ActivityThread.java:7406)
2804-11 09:43:24.482 22968 22968 E CrashHandler: at java.lang.reflect.Method.invoke(Native Method)
2904-11 09:43:24.482 22968 22968 E CrashHandler: at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
3004-11 09:43:24.482 22968 22968 E CrashHandler: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:926)

There is many same Log before the crash.
06-09 16:14:11.765 22033 22033 I AssistStructure: Flattened final assist data: 18020 bytes, containing 1 windows, 90 views
206-09 16:14:11.780 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
306-09 16:14:11.783 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
406-09 16:14:11.789 22033 22033 I AssistStructure: Flattened final assist data: 18020 bytes, containing 1 windows, 90 views
506-09 16:14:11.794 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
606-09 16:14:11.796 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
706-09 16:14:11.799 22033 22033 I AssistStructure: Flattened final assist data: 18020 bytes, containing 1 windows, 90 views
806-09 16:14:11.809 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
906-09 16:14:11.811 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
1006-09 16:14:11.815 22033 22033 I AssistStructure: Flattened final assist data: 18020 bytes, containing 1 windows, 90 views
1106-09 16:14:11.824 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
1206-09 16:14:11.826 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
1306-09 16:14:11.830 22033 22033 I AssistStructure: Flattened final assist data: 18020 bytes, containing 1 windows, 90 views
1406-09 16:14:11.840 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
1506-09 16:14:11.842 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
1606-09 16:14:11.845 22033 22033 I AssistStructure: Flattened final assist data: 18020 bytes, containing 1 windows, 90 views
1706-09 16:14:11.855 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
1806-09 16:14:11.856 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
1906-09 16:14:11.857 22033 22033 I AssistStructure: Flattened final assist data: 18020 bytes, containing 1 windows, 90 views
2006-09 16:14:11.871 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
2106-09 16:14:11.873 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
2206-09 16:14:11.876 22033 22033 I AssistStructure: Flattened final assist data: 18020 bytes, containing 1 windows, 90 views
2306-09 16:14:11.890 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
2406-09 16:14:11.891 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
2506-09 16:14:11.894 22033 22033 I AssistStructure: Flattened final assist data: 18020 bytes, containing 1 windows, 90 views
2606-09 16:14:11.906 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
2706-09 16:14:11.908 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
2806-09 16:14:11.910 22033 22033 I AssistStructure: Flattened final assist data: 18020 bytes, containing 1 windows, 90 views
2906-09 16:14:11.923 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
3006-09 16:14:11.925 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
3106-09 16:14:11.929 22033 22033 I AssistStructure: Flattened final assist data: 18020 bytes, containing 1 windows, 90 views
3206-09 16:14:11.941 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
3306-09 16:14:11.943 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
3406-09 16:14:11.946 22033 22033 I AssistStructure: Flattened final assist data: 18020 bytes, containing 1 windows, 90 views
3506-09 16:14:11.959 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
3606-09 16:14:11.961 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
3706-09 16:14:11.966 22033 22033 I AssistStructure: Flattened final assist data: 18020 bytes, containing 1 windows, 90 views
3806-09 16:14:11.977 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
3906-09 16:14:11.979 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
4006-09 16:14:11.983 22033 22033 I AssistStructure: Flattened final assist data: 18020 bytes, containing 1 windows, 90 views
4106-09 16:14:11.993 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
4206-09 16:14:11.994 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
4306-09 16:14:11.995 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
4406-09 16:14:11.996 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring
4506-09 16:14:11.996 22033 22033 W View : dispatchProvideAutofillStructure(): not laid out, ignoring

There is a ActivityB in app,and anyone Activity jumped to this ActivityB will throw this exception in some case,just happened when jumping to this ActivityB,and just in HUAWEI Android 8.0.0.
I have find a question which is similar,but it doesn't work for me.
I try to use EventBus to transport the bundle between the Activity,but it still throw the exception in some case,just happened in HUAWEI Android 8.0.0
and I can't recurrent this exception by test.How could I solve this question?

A: Finally,I set the hardwareAccelerated to false,this solution can avoid the crash,but I still don't know the reason of the crash.
<activity
        android:hardwareAccelerated="false"
</activity>


text:
Q: Gradle sync failed: Could not find method defaultConfig() In the first instance my problem was Cause 1: org.gradle.workers.internal.DefaultWorkerExecutor$WorkExecutionException: A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
but this has escalated since then and now my gradle is broken.
this is the error I am getting:
FAILURE: Build failed with an exception.

* Where:
Build file 'D:\stackstorage\android projecten\Converter\build.gradle' line: 26

* What went wrong:
A problem occurred evaluating root project 'Converter'.
> Could not find method defaultConfig() for arguments [build_7komq7i2k7pl5720grjx3kada$_run_closure2@b894d83] on root project 'Converter' of type org.gradle.api.Project.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

CONFIGURE FAILED in 0s
Could not find method defaultConfig() for arguments [build_7komq7i2k7pl5720grjx3kada$_run_closure2@b894d83] on root project 'Converter' of type org.gradle.api.Project.
Open File

event log:
12:13   Gradle sync started with IDEA sync

12:13   Gradle sync failed: Could not find method defaultConfig() for arguments [build_7komq7i2k7pl5720grjx3kada$_run_closure2@55d7744a] on root project 'Converter' of type org.gradle.api.Project.
            Consult IDE log for more details (Help | Show Log) (287 ms)

12:13   NDK Resolution Outcome: Project settings: Gradle model version=5.4.1, NDK version is UNKNOWN

12:13   Gradle sync started with IDEA sync

12:13   Gradle sync failed: Could not find method defaultConfig() for arguments [build_7komq7i2k7pl5720grjx3kada$_run_closure2@b894d83] on root project 'Converter' of type org.gradle.api.Project.
            Consult IDE log for more details (Help | Show Log) (230 ms)

12:13   NDK Resolution Outcome: Project settings: Gradle model version=5.4.1, NDK version is UNKNOWN

I am unsure what code I need to post for this to get helped but I've seen people posting their build.gradle and gradle.properties, so i'll post mine.
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.3.61'
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}

defaultConfig {
    minSdkVersion 15
    targetSdkVersion 28
    multiDexEnabled true
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx4608m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official

Thanks in advance to anyone willing to help. I kinda messed up here.

A: Check your app> build.gradle file. there will be defaultConfig() tag like this
 defaultConfig {
    applicationId "com.example.myApp"// your appId
    minSdkVersion 17
    targetSdkVersion 29
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

   }

A: Move defaultConfig{} from gradle project to build.gradle's app module inside android tag.
Should be similar to this
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

repositories {
    mavenCentral()

}

android {
    compileSdkVersion 28
    buildToolsVersion "28.0.3"

    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

A: In android studio, go to your project. Make sure you are in the view mode "Android". Just like this image:
Should be like this in android studio
Go to Gradle-Scripts -> build.gradle (module:app) and make sure it is composed similarly to this:
    apply plugin: 'com.android.application'

    apply plugin: 'kotlin-android'

    apply plugin: 'kotlin-android-extensions'

    android {

        compileSdkVersion 29
        buildToolsVersion "29.0.2"
        defaultConfig {
            applicationId "your app id"
            minSdkVersion 23
            targetSdkVersion 29
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        }

        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }

        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            }
        }
    }

    dependencies {
    //your dependencies
    }


text:
Q: Why does an Admob banner ad doesn't show to me? [Android, libGDX] I have a problem:
I've installed an Admob ad banner in my app and when I'm using this command to builder:
builder.addTestDevice(
            "0277F42DBB49E3FD56F9EFFE3C4380B4"
)

Everything works (I mean, I see banner with similar text "congrats, bla-bla-bla, etc".
But.
In published game, which of course has disabled this line (addTestDevice) it doesn't show.
Manifest
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hypeofpipe.westernshooter"
    android:versionCode="12"
    android:versionName="1.02">
    <uses-sdk android:minSdkVersion="18" android:targetSdkVersion="25" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/GdxTheme" >
        <meta-data android:name="com.google.android.gms.games.APP_ID" android:value="@string/app_id"/>
        <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
        <activity
            android:name="com.hypeofpipe.westernshooter.AndroidLauncher"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
            android:theme="@android:style/Theme.Translucent" />
    </application>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>

</manifest>

AndroidLauncher.java
    public class AndroidLauncher extends AndroidApplication
            implements UrlOpener, AdHandler {

    protected AdView adView;
    private final int SHOW_ADS = 1;
    private final int HIDE_ADS = 0;

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case SHOW_ADS:
                    adView.setVisibility(View.VISIBLE);
                    break;
                case HIDE_ADS:
                    adView.setVisibility(View.GONE);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();

        adView = new AdView(this);
        RelativeLayout layout = new RelativeLayout(this);

        View gameView = initializeForView(new MainClass(this, this), config);

        adView.setAdListener(new AdListener(){
            @Override
            public void onAdLoaded() {
                int visibility = adView.getVisibility();
                adView.setVisibility(AdView.GONE);
                adView.setVisibility(visibility);
                AudioManager.getInstance().playSound(
                        AudioManager.getInstance().shot_missed
                );
            }
        });
        adView.setAdSize(AdSize.SMART_BANNER);
        adView.setAdUnitId(*here goes my unitid from admob*);

        AdRequest.Builder builder = new AdRequest.Builder();
        RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT
        );
        layout.addView(gameView);
        layout.addView(adView, adParams);
        adView.loadAd(builder.build());

        setContentView(layout);
    }

    public void openURL(String url) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        this.startActivity(intent);
    }

    @Override
    public void showAds(boolean show) {
        handler.sendEmptyMessage(show ? SHOW_ADS : HIDE_ADS);
    }
    }

MainClass.java
    public class MainClass extends Game {

    public static UrlOpener urlOpener;
    public static AdHandler adHandler;

    public MainClass(UrlOpener urlOpener,
                     AdHandler adHandler)
    {
        this.urlOpener = urlOpener;
        this.adHandler = adHandler;
        adHandler.showAds(false);
    }

    @Override
    public void create() {
        Assets.getInstance().load();
        Assets.getInstance().assetManager.finishLoading();
        setScreen(new ScreenModified(this));
    }

}

Some fragment from code, where ads are called to show.
MainClass.adHandler.showAds(true);

Also, I have 0 requests from mine app.

A:
Ads working fine with addTestDevice(XXX) but not getting live Ads.

Follow these steps :

*

*Wait for some times/hours or a day.

*If you're able to load/get test ads but not live ads, It sounds like an issue with your AdMob account.

*After waiting still having problem then you need to cross check Ad unit Id and AppId from AdMob account.

*Make sure that you properly set up a payment system and/or verified your PIN? If they are not done, then live ads would not be served from your account.

*Still problem now you need to post your problem in this group for assistance.


text:
Q: Okclient in Okclient cannot be applied to (okhttp3.okhttpclient) I am trying to use Retrofit in one of me projects.
I am facing an error with (new OkClient(new OkHttpClient()))
 RestAdapter adapter = new RestAdapter.Builder()
                 .setEndpoint(Constants.GET_API_URL_BASE)
                 .setLogLevel(RestAdapter.LogLevel.FULL)
                 .setClient(new OkClient(new OkHttpClient()))
                 .build();
         apiGet = adapter.create(ApiCalls.class);

The error, underline in red, is on

(new OkHttpClient())
* OkClient(com.squareup.okhttp.OkhttpClient) in OkClient  cannot be applied to (okhttp3.OkhttpClient)*

These are my dependences:
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.google.android.gms:play-services:8.4.0'
compile 'net.danlew:android.joda:2.7.1'
compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.squareup.okhttp3:okhttp:3.0.1'

Any idea?.
Thanks

A: You can use OkHttp3 with Retrofit 1.9 thanks to Jake Wharton and his retrofit1-okhttp3-client
With this library you just need to modify the setClient() in your RestAdapter.Builder to use Ok3Client instead of OkClient.
The code should be like this:
RestAdapter adapter = new RestAdapter.Builder()
             .setEndpoint(Constants.GET_API_URL_BASE)
             .setLogLevel(RestAdapter.LogLevel.FULL)
             .setClient(new Ok3Client(new OkHttpClient()))
             .build();

Here you can find more information about how to use it.

A: For Retrofit versions prior to 2.0.0-beta3 you have to use OkHttp 2. Change your OkHttp dependency to compile 'com.squareup.okhttp:okhttp:2.7.2' or update to Retrofit 2.


text:
Q: Implementing section indexer in list view android I want to add section headers in the list view in android like the attached image. Can some one help me with the code. I don't want to implement the side section indexer like in contacts.image
This is the custim list adapter that I have created-
public class CustomListAdapter extends BaseAdapter {

    private Activity mContext;
    private List<String> mList;
    private LayoutInflater mLayoutInflater = null;

    public CustomListAdapter(Activity context, List<String> list){
        mContext = context;
        mList = list;
        mLayoutInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int pos) {
        return mList.get(pos);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        return super.getDropDownView(position, convertView, parent);
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        final ListViewHolder viewHolder;

        if (convertView == null) {
            LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.players_name_with_options, parent, false);
            viewHolder = new ListViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ListViewHolder) convertView.getTag();
        }

        // Setting the name of the player on the text view
        viewHolder.textView.setText(mList.get(position));
        return convertView;
    }

    // Class that contains the views as the variables
    private class ListViewHolder {

        TextView textView;

        // Constructor of the class
        public ListViewHolder(View item) {

            // Initialising the text view and the spinner
            textView = (TextView) item.findViewById(R.id.list_textView);
        }
     }
}

I am initializing this ArrayAdapter and then adding the names of the players. I want that when ever the name is added then the section header be created and the player's name should be set below the header like the image that I had attached.

A: There are many library available for this. Hope the below link will help you to figure out, what you need.

*

*pinned-section-listview

*Example 1

*Example 2


text:
Q: Folder name change in Finder but not changed in Terminal iMac running Mojave 10.14.6
I changed a folder name in Finder but I can't see the change in Terminal.
old folder name: A.B
new folder name: A
in Terminal ls still shows A.B
cd . or cd .. then cd back won't change the ls outcome.
in Finder using Go to Folder can go to the new folder name, however the Path bar at the bottom shows the new name but Copy as Pathname or New Terminal at Folder are using the old name.
Restarting the iMac won't fix.
What kind of bug is this? I can fix this by mv in Terminal but I'd prefer the syncing between Finder and Terminal automated.

A: You probably have "Hide extension" set for that folder or have globally disabled "Show all filename extensions" in Finder Advanced preferences.


text:
Q: How to show fragments randomly? I am creating a quiz app with Android Studio. I have an activity and PagerAdapter in it. PagerAdapter has three fragments in it. When I launch the application the fragments appear in order: fragment1, fragment2, fragment3.
I want them to appear randomly in different positions each time I launch the application. For example: fragment3, fragment1, fragment2...
The activity which has PagerAdapter in it:
public class testActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pager_adapter);
        initialisePaging();
    }

    private  void initialisePaging() {
        List<Fragment> fragments = new Vector<Fragment>();
        fragments.add(Fragment.instantiate(this,fragment1.class.getName()));
        fragments.add(Fragment.instantiate(this,fragment2.class.getName()));
        fragments.add(Fragment.instantiate(this,fragment3.class.getName()));
        PagerAdapter mPagerAdapter = new PagerAdapter(this.getSupportFragmentManager(), fragments);

        ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
        pager.setAdapter(mPagerAdapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_test, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

PagerAdapter.java
public class PagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragments;

    public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        this.fragments = fragments;
    }

    @Override
    public Fragment getItem(int arg0) {
        return this.fragments.get(arg0);
    }

    @Override
    public int getCount() {
        return this.fragments.size();
    }

    public void setFragments(List<Fragment> fragments) {
        this.fragments = fragments;
    }
}

A: Just shuffle the List of fragments before passing it to the adapter.
private  void initialisePaging() {
    List<Fragment> fragments = new Vector<Fragment>();
    fragments.add(Fragment.instantiate(this,fragment1.class.getName()));
    fragments.add(Fragment.instantiate(this,fragment2.class.getName()));
    fragments.add(Fragment.instantiate(this,fragment3.class.getName()));

    //add this line
    Collections.shuffle(fragments , new Random(System.nanoTime()));

    PagerAdapter mPagerAdapter = new PagerAdapter(this.getSupportFragmentManager(), fragments);

    ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
    pager.setAdapter(mPagerAdapter);

}

A: public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        this.fragments = fragments;
        long seed = System.nanoTime();
        //shuffle the fragment list
        Collections.shuffle(fragments , new Random(seed));
}

A: Not sure if this could help but try something like this
Random rand = new Random();

int  n = rand.nextInt(50) + 1;
\\50 is the maximum and the 1 is our minimum

You can then use the int to either get/generate a name that you would like to access, maybe even put your fragments into an array and access the array by using the int(n) as an index


text:
Q: How to sum many INDEX/MATCH values given criteria? I'm working on a dataset (30,000 rows x 1,000 columns) that looks like:
    Alpha  Beta  Gamma
A     3      4     3
B     4      5     7
C     9      2     4
D     6      9     3

I need to add multiple selected values in this format:
Selected Values      Total Gamma     Total Alpha    ...etc.
B  C  D  A               17               22        ...etc.
C  A                      7               12        ...etc.
A  D  C                  10               18        ...etc.

I could add INDEX/MATCH results one by one and drag down:
= IFERROR((INDEX($A$1:$D$6, MATCH($A10, $A$1:$A$6, 0), MATCH(F$9, $A$1:$D$1, 0))), 0)
+ IFERROR((INDEX($A$1:$D$6, MATCH($B10, $A$1:$A$6, 0), MATCH(F$9, $A$1:$D$1, 0))), 0)
+ so on for each selected value...

But as some rows have 500+ selected values (A, B, C ... ZZ), is there a simpler way to add all this?
Any help would be much appreciated!

A: It will likely take some time to calculate all the results because of the multiple criteria and size of the data, but I'd suggest SUMPRODUCT, the formula I'm using in H2 is:
=SUMPRODUCT($B$2:$D$5*($B$1:$D$1=H$1)*ISNUMBER(SEARCH($A$2:$A$5,$G2)))


text:
Q: Error System.NotSupportedException was unhandled by user code I try to get automatic click on a button on a page on my website
I have try multiple things and i can not get out of this exception
This is My code
Well wen i press the button1 its come an error
I describe below code
Public Class Form5
    Dim CheckButton, skip_ad_button As HtmlElement
    Sub New()
        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        WebBrowser1.ObjectForScripting = True
        WebBrowser1.ScriptErrorsSuppressed = True
    End Sub
    Private Sub Form5_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub

    Private Sub WebBrowser1_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        skip_ad_button = WebBrowser1.Document.GetElementById("skip_ad_button")
        CheckButton = WebBrowser1.Document.GetElementById("skip_ad_button")

        If Not skip_ad_button Is Nothing Then
            skip_ad_button.InnerText = "skip_ad_button" 'Replace testID by the ID you want
        End If

        If Not CheckButton Is Nothing Then
            'some code here
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        WebBrowser1.Navigate("http:\\mediaads.eu/proxy")

    End Sub
End Class

This is the error

System.NotSupportedException was unhandled by user code
  HResult=-2146233067
  Message=Property is not supported on this type of HtmlElement.
  Source=System.Windows.Forms
  StackTrace:
  at System.Windows.Forms.HtmlElement.set_InnerText(String value)
  at WindowsApplication1.Form5.WebBrowser1_DocumentCompleted(Object sender,
WebBrowserDocumentCompletedEventArgs e) in \Documents\Visual Studio
      2012\Projects\WindowsApplication1\WindowsApplication1\Form5.vb:line 23


text:
Q: Replace black with white in uiview ios How can I replace all black in a UIView.
Is there a layer filter or something I can do to replace any black in a UIView with another color such as white?
I am trying to make a  jailbreak tweak that changes text in the widgets to white. But I found that it is a UIRemoteView and I can't see inside to hook the labels. So I was thinking if I could add a filter or something to that RemoteView to replace the black with white.
This is a jailbreak tweak so normal restrictions do not apply.

A: In case you want to change color of layer background use the following code:
Objective C:
myView.layer.backgroundColor = [UIColor whiteColor].CGColor;

Swift:
myView.layer.backgroundColor = UIColor.whiteColor().CGColor


text:
Q: SettingWithCopyWarning Python3 I am finding the max of df2 by row, and setting the max value to new col on df1.
df1['max'] = df2[df2.keys().tolist()].max(axis=1)

This line is throwing a SettingWithCopyWarning. Not sure how to re-write it to make the warning go away. How to re-write it?

A: The warning typically is a result of chained assignments and you can read more about it in this answer and this blog post also goes into great detail.
If you wish to turn it off, you can use:
pd.options.mode.chained_assignment = None


text:
Q: Assign value to EditorFor using javascript I have this code in my view :
    <div class="drop-down-list">
        <%: Html.EditorFor(model => model.StageId,new { id="hiddenStageID"}) %>
        <%: Html.ValidationMessageFor(model => model.StageId) %>
    </div>

And this is my javascript code to set value of EditorFor. But it does not work :
<script>
           var e = document.getElementById("stageTwoView");
           var listIndex = e.selectedIndex;
           var stageIdVal = list[listIndex].valueOf();
           document.getElementById('hiddenStageID').value = stageIdVal;
</script>

for example stageIdVal get this value : "1003". But the last line does not work! Why?

A: EditorFor doesn't accept htmlAttributes as a parameter (which is what I think you're anticipating); that would be TextBoxFor.
What you're doing is passing additionalViewData to the editor template, so unless you're using that in your EditorTemplate, you won't actually be assigning an ID to the element (and therefore can't retrieve it with JS).
If you wanted to give the text field an ID, either customize your editor template, or use TextBoxFor instead so you can pass it additional attributes:
@Html.TextBoxfor(x => x.StageId, new { id = "hiddenStageID" })

Unless I'm wrong (which I may be because I don't have the template visible in front of me. You may have customized it, in which case I'm just making an inaccurate assumption and I can update my answer).


text:
Q: Postgres from Python: can I fetch N rows per time in a loop? I have the following case:
conn=ps.connect("dbname='xxxx' user='xxxx' password='xxxx'")
crs = conn.cursor()
statement= """ SELECT *FROM aaaa;
"""
crs.execute(statement)
# get the name of the cars
var = crs.fetchall()

But given the large size of the table, Ubuntu kills the process because of memory issues.
How can I fetch N rows per time in a loop? For instance something like this:
N=1000
for i in range(0,10):
   var = crs.fetchmany(0:N)
   N+=1000

A: fetchmany returns up to n next rows and None when there are none left.
rows = crs.fetchmany(1000)
while(rows):
    # do stuff
    rows = crs.fetchmany(1000)
else:
    # done

A: If you are using psycopg2:
cur.fetchmany(2)

the cursor class will allow you to fetchone or fetchmany.

A: I solved it in the following way:
query = """SELECT COUNT(*) FROM xxxxx;
"""
crs.execute(query)
N = crs.fetchall()
N = N[0][0]
for i in range(0,N):
    if n1 == N: continue
    n1 = n + 1000
    print n,n1
    if n1 > N:
        n1 == N
    statement = """ SELECT * FROM xxxxx limit %d offset %d;
    """%(n1,n)
    crs.execute(statement)
    var  = crs.fetchall()


text:
Q: Unpivot with column name as date I have the following data in a crosstable format:
prod_codigo  esps_fecini  day1    day2    day3    day4    day5  day6  day7
1077         2018-11-12   200.00  200.00  250.00  250.00  0.00  0.00  0.00
...

I need to convert the data to something like this:
prod_codigo  esps_fecini   Bins
1077         2018-11-12    200.00
1077         2018-11-13    200.00
1077         2018-11-14    250.00
1077         2018-11-15    250.00
1077         2018-11-16    0.00
1077         2018-11-17    0.00
1077         2018-11-18    0.00
...

How can I achieve this?
I'm using the following query, but I can't find a way to sum the dates. I'm using SQL Server 2008
select prod_codigo,esps_fecini,U.Bins
from dba.estimprodsemana
unpivot
(
Bins
for datos in (esps_cadia1,esps_cadia2,esps_cadia3,esps_cadia4,esps_cadia5,esps_cadia6,esps_cadia7)
) U

A: If you do want to unpivot for this query, you can do it like this:
declare @t table (prod_codigo int,esps_fecini date,day1 decimal(5,2),day2 decimal(5,2),
                  day3 decimal(5,2),day4 decimal(5,2),day5 decimal(5,2),day6 decimal(5,2),
                  day7 decimal(5,2))
insert into @t(prod_codigo,esps_fecini,day1,day2,day3,day4,day5,day6,day7) values
(1077,'20181112',200.00,200.00,250.00,250.00,0.00,0.00,0.00)

select
    prod_codigo,
    newDay,
    Value
from
    @t
        unpivot
    (Value for Offset in (day1,day2,day3,day4,day5,day6,day7)) u
        cross apply
    (select DATEADD(day,CONVERT(int,SUBSTRING(Offset,4,1))-1,esps_fecini) as newDay) v

Where we unpivot first and then work out how to extract a usable number from the resulting data (rather than metadata - the column names) to adjust the date value.
Result:
prod_codigo newDay     Value
----------- ---------- ---------------------------------------
1077        2018-11-12 200.00
1077        2018-11-13 200.00
1077        2018-11-14 250.00
1077        2018-11-15 250.00
1077        2018-11-16 0.00
1077        2018-11-17 0.00
1077        2018-11-18 0.00

A: You can use APPLY instead :
select e.prod_codigo, ee.*
from dba.estimprodsemana e cross apply
     ( values (esps_fecini, day1),
              (dateadd(day, 1, esps_fecini), day2),
              (dateadd(day, 2, esps_fecini), day3),
              (dateadd(day, 3, esps_fecini), day3),
              (dateadd(day, 4, esps_fecini), day4),
              (dateadd(day, 5, esps_fecini), day5),
              (dateadd(day, 6, esps_fecini), day6),
              (dateadd(day, 7, esps_fecini), day7)
     ) ee (esps_fecini, Bins);

A: You had the answer in your question, just a little formatting :)
Also, you need to derive the offset using ROW_NUMBER(), based on natural order, in this case. You can then calculate the date based on the applying th derived field based on column order D1..D7.
DECLARE @T TABLE(ID INT, Date DATETIME, D1 INT, D2 INT, D3 INT, D4 INT, D5 INT, D6 INT, D7 INT)
INSERT @T VALUES(1077,'11/12/2018',200,200,250,250,0,0,0)

SELECT
    ID,
    Date = DATEADD(DAY,DayNumber,Date),
    Bins
FROM
(
    SELECT
        ID,
        Date,
        Bins,
        DayNumber = ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID) - 1
    FROM @T
    UNPIVOT
    (
        Bins FOR Dates in (D1,D2,D3,D4,D5,D6,D7)
    ) AS X
)AS Y

A: If you have more day columns than you care to code or specify, or if the number of day columns is variable, the following will "dynamically" unpivot your data without actually using dynamic SQL.
Clearly UNPIVOT would be more performant
Example
declare @YourTable table (prod_codigo int,esps_fecini date,day1 decimal(5,2),day2 decimal(5,2),day3 decimal(5,2),day4 decimal(5,2),day5 decimal(5,2),day6 decimal(5,2),day7 decimal(5,2))
insert into @YourTable values
(1077,'20181112',200.00,200.00,250.00,250.00,0.00,0.00,0.00)

Select A.prod_codigo
      ,esps_fecini = dateadd(day,-1+replace(Item,'day',''),esps_fecini)
      ,Bins=C.Value
 From @YourTable A
 Cross Apply ( values (cast((Select A.* for XML RAW) as xml))) B(XMLData)
 Cross Apply (
                Select Item = a.value('local-name(.)','varchar(100)')
                      ,Value = a.value('.','decimal(5,2)')
                 From  B.XMLData.nodes('/row')  as C1(n)
                 Cross Apply C1.n.nodes('./@*') as C2(a)
                 Where a.value('local-name(.)','varchar(100)') like  'day%'
             ) C

Returns
prod_codigo esps_fecini Bins
1077        2018-11-12  200.00
1077        2018-11-13  200.00
1077        2018-11-14  250.00
1077        2018-11-15  250.00
1077        2018-11-16  0.00
1077        2018-11-17  0.00
1077        2018-11-18  0.00


text:
Q: How can I trigger an event on an element that is dynamically created? I'm working on an Etch-A-Sketch project. I've dynamically created a 16x16 grid, the squares change colour on mouseover. When the reset button is clicked, I want the squares to turn back to white again, however I keep getting the error "Cannot set property 'backgroundColor' of undefined". Any hints are appreciated.
/*****Create grid *****/
for (i = 0; i < 16; i++) {
const grid = document.querySelector(".grid");
const row = document.createElement("div");
grid.appendChild(row);
for (j = 0; j < 16; j++) {
    const column = document.createElement("div");

    column.style.height = "20px";
    column.style.width = "20px";
    column.style.border = "solid black 2px";
    column.classList.add("row");

    grid.appendChild(column);
};
};

/*****Random color picker for grid square*****/
let gridSquare = document.querySelectorAll(".row");

gridSquare.forEach(function (item) {
item.addEventListener("mouseover", function () {
    const hex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];
    let hexColour = "#";
    for (i = 0; i < 6; i++) {
        hexColour += hex[Math.floor(Math.random() * hex.length)];
    };
    item.style.backgroundColor = hexColour;
});
});

/*****Reset button******/
const resetButton = document.querySelector(".reset");

resetButton.addEventListener("click", function() {
gridSquare.style.backgroundColor = "white";
});

A: You could loop through your grid squares when reset is clicked.
/*****Reset button******/
const resetButton = document.querySelector(".reset");

resetButton.addEventListener("click", function() {
   gridSquare.forEach( function(item) {
     item.style.backgroundColor = "white";
   }
});

A: It's probably because the gridSquare contains multiple document elements as you specified querySelectorAll when defining the variable gridSquare.The style.backgroundColor only works for one element so what you could do is iterate through the gridSquare variable and change the style just like below:
resetButton.addEventListener("click", function() {
    gridSquare.forEach(function(square) {
        square.style.backgroundColor = "white";
    })
});

A: You need to iterate through each square created.. the document.querySelectorAll(".row"); return an array so basically you tried to set the background to an array, which is not possible

/*****Create grid *****/
for (i = 0; i < 16; i++) {
  const grid = document.querySelector(".grid");
  const row = document.createElement("div");
  grid.appendChild(row);
  for (j = 0; j < 16; j++) {
    const column = document.createElement("div");

    column.style.height = "20px";
    column.style.width = "20px";
    column.style.border = "solid black 2px";
    column.classList.add("row");

    grid.appendChild(column);
  };
};

/*****Random color picker for grid square*****/
let gridSquare = document.querySelectorAll(".row");

gridSquare.forEach(function(item) {
  item.addEventListener("mouseover", function() {
    const hex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];
    let hexColour = "#";
    for (i = 0; i < 6; i++) {
      hexColour += hex[Math.floor(Math.random() * hex.length)];
    };
    item.style.backgroundColor = hexColour;
  });
});

/*****Reset button******/
const resetButton = document.querySelector(".reset");

resetButton.addEventListener("click", function() {
  gridSquare.forEach(function(item) {
    item.style.backgroundColor = "white";
  })

});
<button class="reset"> reset </button>


text:
Q: Node server: Loading module was blocked because of a disallowed MIME type ("text/html") I get the following error message when I try to run a local node server with a very simple application (see coding below).
Loading module from "http://localhost:8080/importing.js" was blocked because of a disallowed MIME type ("text/html").
I am new to node and ES6 Modules so I dont really understand the details of the problem. According to this URL the mime-type 'application/javascript' has to be served explicitly for modules. But how do I achieve this in my example below?
index.html
<!DOCTYPE html>
<html>
  <head>
    <script src="./importing.js" type="module"></script>
    <meta charset="utf-8">
  </head>
  <body>
  </body>
</html>

server.js
var http = require('http');
var fs = require('fs');

const PORT=8080;

fs.readFile('./index.html', function (err, html) {

    if (err) throw err;

    http.createServer(function(request, response) {
        response.writeHeader(200, {"Content-Type": "text/html"});
        response.write(html);
        response.end();
    }).listen(PORT);
});

importing.js
import {a} from './exporting.js';

console.log(a);

exporting.js
export const a = 'Constant a';

I start the server in CMD with
node server.js

A: Essentially you have a server that for any given request, serves the content of your index.html file - regardless of what that request might look like. A browser therefore receives the HTML and begins to interpret it making another request for the src of your script tag and since the server only serves your index.html file, the browser receives your HTML file a second time when it expected javascript.
Typically you'd create a server first then construct responses based on the request as input. A primitive example of serving your static files how you intended might look like the following:
const http = require('http')
const fs = require('fs')

const PORT = 8080

http
    .createServer((request, response) => {
        fs.readFile(`.${request.url}`, (err, data) => {
            if (err) {
                response.writeHeader(404, {
                    'Content-Type': 'text/plain'
                })
                response.write('404 Not Found')
                response.end()
                return
            }

            if (request.url.endsWith('.html')) {
                response.writeHeader(200, {
                    'Content-Type': 'text/html'
                })
            }

            if (request.url.endsWith('.js')) {
                response.writeHeader(200, {
                    'Content-Type': 'application/javascript'
                })
            }

            response.write(data)
            response.end()
        })
    })
    .listen(PORT)

Do note that this example is too trusting of the client and you would normally want to sanitise the request in some way. I kept to vanilla javascript but once you're comfortable with how it works, it's worth checking out Express as it will simplify the routing / mime-type boilerplate etc.

A: I know that you're importing just the command, but I'll let you know my solution for this and see if you're interested. This error, for me, came from the import statement in your module. I was trying to import the entire file, with all functions and imports it had, while essentially using the same server and HTML.
my importing.js:
import * as Spotify from "./spotify-web-api.js";

window.basicAlert = function basicAlert() {
    alert("this is a test to see if basicAlert runs properly");
}

console.log("Should print to console with no error on imports");

I don't know the logic behind the import * as, but it worked to successfully import my file without throwing a MIME type error. As for the window.basicAlert =, Javascript apparently doesn't like to give any file that imports it access to its functions or variables unless it's manually attached to the window. You don't have this error now, but after the file imports successfully it will tell you that a isn't defined. While I have it attached to my function in importing.js, you'll need to put it in exporting.js like this:
const a = 'Constant a';
windows.a = a;

I didn't test that ^ but it makes sense to me. I hope this can help you out, or get closer, cause it solved my problem.


text:
Q: I am trying to host a WCF Service over two endpoints, http and https I am trying to host a WCF Service over http and https and using the below config:
<system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_ITestService">
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None"
                realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
        <binding name="BasicHttpsBinding_ITestService">
          <security mode="Transport">
            <transport clientCredentialType="None" proxyCredentialType="None" />
            <message />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
      <service name="TestService" behaviorConfiguration="TestServiceBehaviour">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8081/"/>
            <add baseAddress="https://localhost:8083/"/>
          </baseAddresses>
        </host>
        <endpoint address=""
             binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ITestService"
             contract="ITestService" name="BasicHttpsBinding_ITestService" />
        <endpoint address=""
             binding="basicHttpBinding" bindingConfiguration="BasicHttpsBinding_ITestService"
             contract="ITestService" name="BasicHttpsBinding_ITestService" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="TestServiceBehaviour">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

But I am getting the following error:
Could not find a base address that matches scheme https for the endpoint with binding BasicHttpBinding. Registered base address schemes are [http].
Need a solution for this as I've defined both base address and binding for both http and https.
Thanks.

A: try this
<endpoint address=""
          binding="basicHttpBinding"
          bindingConfiguration="BasicHttpBinding_ITestService"
          contract="ITestService" name="BasicHttpsBinding_ITestService"/>
<endpoint address=""
          binding="basicHttpBinding"
          bindingConfiguration="BasicHttpsBinding_ITestService"
          contract="ITestService" name="BasicHttpsBinding_ITestService"/>
 <endpoint address="mex"
         binding="mexHttpsBinding"
         contract="IMetadataExchange" />

A: I did not enable the https binding on the IIS Server and was trying to host a service using https protocol. Creating a certificate and enabling the https binding on the IIS Server resolved the issue. :)


text:
Q: Vertices of quadrilaterals I came across an interesting question online that was about vertices of quadrilaterals.  I am still stumped as to how to find the answer of this solution.
The question I found was:
Is it possible to find 4 points that are the vertices of 2 different convex quadrilaterals?  If so, what is the maximum number of convex quadrilaterals that can have the same set of vertices?
I do not think that it is possible to find 4 points that are the vertices of 2 different convex quadrilaterals, but I am not sure if what I think is wrong or right?  If my conclusion is right, could someone explain why please?
Thank you very much.
Michael Silva

A: The only convex quadrilateral with this vertices may be defined as intersection of all convex sets containing them. So the answer is 1.


text:
Q: Relation between a representative of a conjugacy class and corresponding irreducible character value Is there a relation between the representative order of a conjugacy class and the corresponding irreducible character value?
Thanks in advance.

A: If I understand your question correctly, you are taking an element $x \in G$, and an irreducible character $\chi$, and asking what influence does the order $n = \lvert x \rvert$ of $x$ have on $\chi(x)$.
In this generality, I do not think you can say much more than the fact that $\chi(x)$ is the sum of some $n$-th roots of unity.
This is because, if $\rho$ is a representation corresponding to $\chi$, then $\rho(x)^n = \rho(x^n) = \rho(1) = I$, where $I$ is an appropriate unit matrix, so the minimal polynomial of $\rho(x)$ divides $x^{n} - 1$, and all eigenvalues of $\rho(x)$ are $n$-th roots of unity.


text:
Q: copy paste tab delimited results into excel file I created a script to obtain data from a LDAP database and wrote it to a file with each value in a row separated by tabs. I then tried to copy and paste the contents of that file to excel, but it places all the tab delimited contents of each "column" within a row in the first column for that row, instead of placing each column of data in its own row within the excel file. Rows paste fine.
For example lets take this mock first row
12121212 [] lastname,  firstname [] title [] phone [] manager

[] = where i tried to programmatically insert a tab in my data output
This puzzles me because I deliberately mad a function that removes the new line from my ldap search result, and adds a tab to the end of the data return for that column.  Here is the addTab function:
function addTab {
    res='           ' # res = "\t\tx"
    echo $1 | tr -d '\n'
    echo "$res" | tr -d '\n'

}
This is how I am calling the function (note $i is from the array of UIDs I use to search against via loop iteration):
addTab `getattrVal $i employeeNumber`
addTab `getattrVal $i employeeType`
addTab `getattrVal $i ou`
addTab `getattrVal $i managerEmployeeNumber`

And here is the code for the getattrVal function
function getattrVale {
    /opt/bin/ldapsearch -QLLLZZH ldap://${VIP}:389/ -b $1 $2 | grep "$2:" |awk '{ print $2 }'

}
I've even tried using the column command to generate nice and even outputted columns (i.e. column -t bashCreatedTabFile.txt) and I still can not paste the contents as desired within the Excel spread sheet.
I realize there are better ways to probably do this, but I think understanding why this is not working is important to my progress.

A: I had the same problem. This isn't the best solution, but it does work.
Change your delimiter to a comma (,). Copy the text as you would normally and paste into Excel. It will probably still be one column. Highlight the column, go to Data > Text to Columns in Excel.
Make sure the data type is "delimited," and select "comma" as the delimiter. I'm not sure why, but the same things doesn't seem to work with tabs.
http://www.wikihow.com/Copy-Paste-Tab-Delimited-Text-Into-Excel

A: Try do it with html output of table.
Like using
print(tabulate(table, headers, tablefmt="html"))

item  	  qty

spam  	   42

eggs  	  451

bacon 	    0


text:
Q: Angular 4 unit test service calling http service I have a service that is calling a http function:
processLogin(info) {
    return this._call.post('login', info).subscribe(response => {
        if (response.status === 'success') {
            this._auth.login(response.object);
            return true;
        }

        return false;
    }, error => {
        return false;
    });
}

And this is the test I'm trying to make:
describe('Facebook Login', () => {
    let service: FacebookLoginService;
    let call: CallService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
                FacebookLoginService,
                { provide: CallService, useClass: CallServiceMock },
            ]
        });

        service = TestBed.get(FacebookLoginService);
        call = TestBed.get(CallService);
    });

    it('should process the login when the post method return success', () => {
        spyOn(call, 'post').and.returnValue(Observable.of({status: 'success'}));

        service.processLogin('any').subscribe(response => {
            console.log(response);
        });
    });
});

However, when I run the test I keep getting the error message

processLogin().subscribe( ... ) is not a function

And if I change the type of response mocked to anything but Observable.of, I get the error message

call.post.subscribe( ... ) is not a function

Why is it not wokirng? I have a very similar test on another service that also calls call.post() and it's working.

A: processLogin returns not an observable but a subscription, so there will be no subscribe method on it. Returned values in subscribe callbacks are ignored, so processLogin won't work as expected.
It likely should be changed to return an observable instead:
return this._call.post('login', info).map(response => { ... });

Then it can be tested like:
spyOn(_call, 'post').and.returnValue(Observable.of({ status: 'success' }));

const login$ = service.processLogin('any');
expect(_call).toHaveBeenCalledWith('login', 'any');

login$.subscribe(response => {
  expect(response).toBe(...);
}, err => { throw err });

It will also need to mock _auth.


text:
Q: What is the meaning of "large performance overhead " in cloud computing? What is the meaning of "large performance overhead " in cloud computing?
What is the meaning of "large performance overhead " in cloud computing?


text:
Q: Can't find the Unexpected T_STRING Normally the T_String error is when there is an extra quote, or atleast I thought. Tonight I got this error
Parse error: syntax error, unexpected T_STRING in /var/www/html/registerBackend.php on line 118

and here is the code for line 118+119
$query = "INSERT INTO User (Name,Email,Password,Port) VALUES ('$name', '$email','$password','$port')";
mysql_query($query) or die('Error, insert query failed');

Here is some more code if it helps
 $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');

 $dbname ='hidden';
mysql_select_db($dbname);

//Check if Username has been used before
$query = "SELECT * FROM User where Name='$name'";
$result=mysql_query($query) or die('Error, insert query failed');
$countName=mysql_num_rows($result);

//Check if email has been used before
$query = "SELECT * FROM User where Email='$email'";
$result=mysql_query($query) or die('Error, insert query failed');
$countEmail=mysql_num_rows($result);

if($countName < 1 && $countEmail < 1){

//Assign their port number
$query  = "SELECT *  FROM login;
$countPort=mysql_num_rows($result);
$port = 20000 + $countPort;

$query = "INSERT INTO User (Name,Email,Password,Port) VALUES ('$name', '$email','$password','$port')";
mysql_query($query) or die('Error, insert query failed');

$query  = "SELECT username, password FROM login WHERE username = '$username' AND password = '$password'";
$result = mysql_query($query);

print "
You have been signed up!
";
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
  echo "Minecraft Username:{$row['Name']}
" .
       "Email:{$row['Email']}
" .
       "Password:{$row['Password']}
".
       "Port:{$row['Port']}
";

}
} elseif ($countName > 1) {
print "Someone has already used this Minecraft IGN! E-mail Stolen@freeminecrafthost.com   to prove it is yours!";
} elseif ($countEmail > 1) {
print "Email has been used before!";
}

A: Try
$query = "INSERT INTO User (Name,Email,Password,Port) VALUES ('" . mysql_real_escape_string($name) . "', '" . mysql_real_escape_string($email) . "','" . mysql_real_escape_string($password) . "','" . mysql_real_escape_string($port) . "')";
mysql_query($query) or die('Error, insert query failed');

Update
This line
$query  = "SELECT *  FROM login;

should be
$query  = "SELECT *  FROM login";

A: //Assign their port number
$query  = "SELECT *  FROM login;
$countPort=mysql_num_rows($result);
$port = 20000 + $countPort;

You're missing a quote after login.
$query  = "SELECT *  FROM login";

Praise be, syntax highlighting!

A: On line:
$query  = "SELECT *  FROM login;

you need to have:
$query  = "SELECT *  FROM login";

But definitely need to give those queries some lovin, too.


text:
Q: Is there an efficient way to find all ordered arrangements of elements in the set S that add up to N? Here's what I mean. Suppose S = {1, 4} and N = 5. The ordered arrangements of elements in the set S would be like
{1}, {4}, {1,1}, {1,4}, {4,1}, {4,4}, {1,1,1}, ....
and the ones that sum up to N are
{1,4}, {4, 1}, {1,1,1,1,1}
I want an algorithm that finds those efficiently.
My "brute force" way would be like
static IEnumerable<IEnumerable<int>> OrderedArrangements(IEnumerable<int> nums, int k)
{
    var singles = nums.Select(i => new int[] {i} );
    var cumulative = singles;
    for(int j = 2; j <= k; ++j)
    {
        var last = cumulative.Where(list => list.Count() == (j - 1));
        var next = from x in singles
                   from y in last
                   select x.Concat(y);
        cumulative = cumulative.Concat(next);
    }
    return cumulative;
}

and then
int sumToN = OrderedArrangements(new int[] {1, 4}, N)
                .Where(x => x.Sum() == N);

but I'm wondering if there's an obvious and more efficient way to do this.

A: Just in case the above answer isn't clear enough, you could try straight forward recursion e.g.
     ...
    /       \
   (1)     (4)
  /  \     /  \
 (1)(4)   (1)(4)

static void f(int sum, int n, String str, int[] arr){
    if (n == sum){
        Console.WriteLine(str);
        return;
    }
    if (n > sum) return;
    for (int i = 0; i < arr.Length; i++){
        f(sum, n + arr[i], str + arr[i].ToString(), arr);
    }
}

static void Main(string[] args){
    int[] arr =  { 1, 4 };
    f(5, 0, "", arr);
}

Where sum is N in your question, n is initialized to 0, str is initialized to "" and arr is S in your question.
output:
11111
14
41

A: This works for me:
static IEnumerable<IEnumerable<int>> OrderedArrangements(IEnumerable<int> nums, int k)
{
    return
        k <= 0
            ? new [] { Enumerable.Empty<int>() }
            : nums
                .SelectMany(
                    n => OrderedArrangements(nums, k - n),
                    (n, ns) => new [] { n }.Concat(ns))
                .Where(ns => ns.Sum() == k);
}

The result of OrderedArrangements(new [] { 1, 4 }, 5) is:

I ran this performance testing code:
Func<Func<IEnumerable<IEnumerable<int>>>, double> measure = f =>
{
    var sw = Stopwatch.StartNew();
    var result = f();
    sw.Stop();
    return sw.Elapsed.TotalMilliseconds;
};

var n = 200;
var a = 0.0;
var b = 0.0;
for (var i = 0; i < n; i++)
{
    a += measure(() => OrderedArrangements_A(new [] { 1, 4, 9, 13 }, 50000));
    b += measure(() => OrderedArrangements_B(new [] { 1, 4, 9, 13 }, 50000));
}

OrderedArrangements_A is the OP's code and OrderedArrangements_B is mine.
I got an average of 15.6ms for "A" and 0.004ms for "B". My code run about 3,895 times faster for this test.


text:
Q: MySQL using JOIN and reports So, I've got a mysql query that looks like this:
SELECT rewards.name, redemptions.points, redemptions.value
FROM rewards
INNER JOIN redemptions ON rewards.id = redemptions.reward_id;

The problem is that it spits out a table like this:
-----------------------------
| Reward 1 |  500   |  30   |
-----------------------------
| Reward 1 |  500   |  30   |
-----------------------------
| Reward 1 |  500   |  30   |
-----------------------------
| Reward 2 |  100   |  10   |
-----------------------------
| Reward 2 |  100   |  10   |
-----------------------------
| Reward 3 |  250   |  20   |
-----------------------------

and so on. Ideally, what I would actually like it to do is to only list each one once, but sum certain columns. So for example, it would look something like this:
-----------------------------
| Reward 1 |  500   |  90   |
-----------------------------
| Reward 2 |  100   |  20   |
-----------------------------
| Reward 3 |  250   |  20   |
-----------------------------

Where it is summing the third column, but listing the first two columns just once. I thought maybe a union would do it because I know it ignores duplicates, but I don't think it works while using unions as well.

A: Use SUM, and remember to add GROUP BY:
SELECT rewards.name, redemptions.points, SUM(redemptions.value)
FROM rewards
INNER JOIN redemptions ON rewards.id = redemptions.reward_id
GROUP BY rewards.name;

A: SELECT  a.name, b.points, SUM(b.value)
FROM    rewards a
        INNER JOIN redemptions b
            ON a.id = b.reward_id
GROUP   BY a.name, b.points


text:
Q: filtrar en django mediante una expresión Tengo un modelo con un campo "fecha" y necesito hacer un filtro de esa fecha restandole 30 días, es decir:
fecha-timedelta(days=30)<=data.today()

Se trata de filtrar por una expresión en SQL sería algo como:
select * from mitable where fecha-30<=now()

¿cómo se realiza este filtro en django?
mimodelo = Mimodelo.objects.filter(?)

A: Esta es una posible forma de hacerlo.
En lugar de restar 30 días a fecha (el campo de la base de datos) es más práctico operar sobre la fecha fija que conocemos data.today(). Para calcular la diferencia de fechas usamos un timedelta.
from datetime import timedelta
highest_day = data.today() + timedelta(days=30)

En caso de que en lugar de usar data.today() quisieras hacerlo sobre "hoy", la fecha actual podría obtener datetime.datetime.now() pero puede ser interesante utilizar django.utils.timezone dependiendo de tu caso de uso concreto (generalmente si querrás usarlo)
from datetime import timedelta
from django.utils import timezone
now = timezone.now()
highest_day = now + timedelta(days=30)

Luego pedimos todos las filas cuyo campo fecha sea anterior (más antiguo) que la máxima fecha deseada (highest_day). Para hacer hacer el field lookup usamos lte. Si quisieramos comprobar que sea posterior más actual usaríamos gte.
mimodelo = Mimodelo.objects.filter(fecha__lte=highest_day)

El código completo sería:
from datetime import timedelta
highest_day = data.today() + timedelta(days=30)
mimodelo = Mimodelo.objects.filter(fecha__lte=highest_day)


text:
Q: Dynamically change width to adjust div inside another div with CSS I am trying to create a custom div with input text and two buttons inside it as shown below.

But when i resize the screen it becomes like this

Is there a way to avoid the two buttons to come down ? Instead it should remain inside the original div.
Here's the code i tried:

.searchBar {
 background: #DDDDDD;
 width:100%;
 height:50px;
 padding: 10px;
 position: relative;
}

.search_field {
 display: inline-block;
 border-radius:4px ;
 background: #FFFFFF;
 width: 70%;height: 32px;
 position: relative;
 left: 60px;
 overflow: inherit;
}

.search_field input {
 width: 89%;
 padding: 0;
 border-top-left-radius: 4px;
 padding-left: 10px;
 padding-top: 5px;
 padding-bottom: 5px;
 border:1px inset red;
}

.search_field input:focus {
 outline-color: transparent;
 outline-style: none;
}

.search_field button {
 border: none;
 background: none;
}

  <input type="text" id="searchInput" placeholder="Search" oninput="showSearchButtons()"/>
  <button id="btn1"  hidden="true" onclick="alert()"></button>
  <button id="btn2" hidden="true" onclick="alert()"></button>

Any help is appreciated. Thanks

A: You can use calc to calculate the width of your input element relative to your buttons:
width: calc(100% - 100px);

Just make sure the width of your buttons is taken of the 100%. In SASS it could look like this:
$buttons: 50px;
width: calc(100% - #{$buttons * 2});

Below is a simplified implementation. I still have the % values as a fallback for older browsers - but that's more a habit than necessity as every major browser supports calc, even IE9 and onward.

input, button {
    float: left;
    height: 50px;
    display: block;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    border: none;
}
input {
    width: 70%;
    width: calc(100% - 100px);
    padding: 10px;
}
button {
    /* Note that this width is equal to 100%
    /* minus the percentage width of the input
    /* divided by the amount of buttons. */
    width: 15%;
    width: 50px;
    line-height: 50px;
}
/* This rule is just to make sure your images don't decide the buttons width */
button img {
    max-width: 100%;
    display: inline-block;
}
<input type='text' placeholder='search' />
<button></button>
<button></button>

A:

Please try this instead of your styles:

.searchBar{
 background: #DDDDDD;
 width:100%;
 height:50px;
 padding: 10px;
 position: relative;
}
.search_field {
 border-radius:4px ;
 background: #FFFFFF;
 position: relative;
 padding-right: 100px; /* You can change as button width */
}
.search_field input {
 width: 100%;
 padding: 0;
 padding-left: 10px;
 padding-top: 5px;
 padding-bottom: 5px;
 border: solid 1px #FF0000;
 -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
  -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;
}
.search_field button {
 border: none;
 background: none;
 position: absolute;
 top: 0;
}
.search_field button#btn1 {
 right: 50px; /* Change as your requirement */
}
.search_field button#btn2 {
 right: 0; /* Change as your requirement */
}


text:
Q: NSView leaves artifacts on another NSView when the first is moved across the second I have an NSView subclass that can be dragged around in its superview. I move the views by calling NSView's setFrameOrigin and setFrameRotation methods in my mouseDragged event handler. The views are both moved and rotated with each call.
I have multiple instances of these views contained by a single superview. The problem I'm having is that, as one view is dragged over another, it leaves artifacts behind on the view it's eclipsing. I recorded a short video of this in action. Unfortunately, due to the video compression the artifacts aren't very visible.
I strongly suspect that this is related to the simultaneous translation and rotation. Quartz Debug reveals that a rectangle of the occluding (or occluded) view is updated as another view is dragged across it (video here); somehow this rectangle is getting miscalculated by the drawing engine, so part of the view that should be redrawn isn't.
The kicker is I have no idea how to fix this. I can't find any way to manually specify the update rect in the docs, nor am I sure that's what needs to happen. Any ideas? Thanks!

A: You might also consider using CALayers instead of views. Unlike views, layers are intended to be stacked with their siblings.
For a possible least-effort solution, try making the views layer-backed; it may or may not solve this problem, but it's worth a try.

A: Views aren't really designed to be stacked in an interactive fashion.  Can be done, but edge cases abound.
Generally, for this kind of thing you would use a Cell like infrastructure if you want to do in-view dragging (See the Sketch example) and you would use the drag-n-drop infrastructure if you want to drag between views or windows (or apps).
If you really want to drag a transformed view over the top, you'll need to invalidate a rectangle of the view underneath the view being dragged.   The rectangle will need to be bigger by a few pixels than the total area (unrotated/untransformed) that is obscured by the view being dragged.  The artifacts are, effectively, caused by rounding error;  diagonal lines are just an estimate on a raster drawing system.
See the method:
- (void)setNeedsDisplayInRect:(NSRect)invalidRect;


text:
Q: Google billing library cancelled all subscriptions I'm using Google's Billing library to make subscriptions inside my app.
After ~~ 3 days google play has refund every subscription of my users, why did it was?
Some code with activity, which make subscriptions:
    private var billingClient: BillingClient? = null
    private val purchasesUpdateListener = PurchasesUpdatedListener { billingResult, purchases ->
        val isSuccessResult = billingResult.responseCode == BillingClient.BillingResponseCode.OK
        val hasPurchases = !purchases.isNullOrEmpty()
        if (isSuccessResult && hasPurchases) {
            purchases?.forEach(::confirmPurchase)
            viewModel.hasSubscription.value = true
        }
    }

    private fun confirmPurchase(purchase: Purchase) {
        val consumeParams = ConsumeParams.newBuilder()
            .setPurchaseToken(purchase.purchaseToken)
            .build()
        billingClient?.consumeAsync(consumeParams) { billingResult, _ ->
            if (billingResult.responseCode != BillingClient.BillingResponseCode.OK) {
                //all done
            }
        }
    }
 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        billingClient = BillingClient.newBuilder(this)
            .setListener(purchasesUpdateListener)
            .enablePendingPurchases()
            .build()

        connectToBillingService()
    }

    private fun connectToBillingService() {
        billingClient?.startConnection(this)
    }

    private fun getPurchases(): List<Purchase> {
        val purchasesResult = billingClient?.queryPurchases(BillingClient.SkuType.SUBS)
        return purchasesResult?.purchasesList.orEmpty()
    }

    override fun onBillingSetupFinished(result: BillingResult) {
        if (result.responseCode == BillingClient.BillingResponseCode.OK) {
            updateSkuMap()
        }
    }
}

A: Because you're using Play Billing Library 2.0 or above. Starting from Play Billing Library 2.0, all purchases must be acknowledged within three days. Failure to properly acknowledge purchases will result in purchases being refunded.
Checking Play Billing Library v2.0 release notes and Processing Purchases for more details.

A: Inside your code, you are using consumeAsync() to confirm a purchase,
which is the correct way for one time consumable product , because consumeAsync() will acknowledge for you automatically.
But for subscriptions, you should use client.acknowledgePurchase() method rather than consumeAsync()
Here is the sample for Kotlin
val client: BillingClient = ...
val acknowledgePurchaseResponseListener: AcknowledgePurchaseResponseListener = ...

suspend fun handlePurchase() {
    if (purchase.purchaseState === PurchaseState.PURCHASED) {
        if (!purchase.isAcknowledged) {
            val acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()
                    .setPurchaseToken(purchase.purchaseToken)
            val ackPurchaseResult = withContext(Dispatchers.IO) {
               client.acknowledgePurchase(acknowledgePurchaseParams.build())
            }
        }
     }
}

A: May be I am too late to answer, but may be reference for other members.
Yes, refund happens in 3 days, when purchase is not acknowledged. And in this case it seems to be a consumable in-app purchase, where purchase is acknowledged locally. I can see in code, that purchase is getting consumed(acknowledged), but consume might be getting fail in ConsumeResponseListener. I would suggest to consume purchase only when purchase object is in 'PURCHASED' state. Which means to apply a check before going to consume it.
purchaseItem.getPurchaseState() == com.android.billingclient.api.Purchase.PurchaseState.PURCHASED


text:
Q: Wix app.config Application and User Scope I have a number of userSettings and applicationSettings defined in my projects app.config, the idea being a user can amend the userSettings in the UI, and we can amend the applicationSettings when necessary.
What I plan to do is have the applicationSettings alongside the exe in the APPDIR C:\Program Files{Company}{Application} folder (which means users cannot edit the file) and have the userSettings in the LocalAppDataFolder C:\Users\\AppData\Local{Company}{Application} so that the app can write to the file.
I'd appreciate some pointers on how best to achieve this with Wix, or even if this is the correct way to achieve what I'm looking to do.
I currently have:

  <!--main installation location-->
  <Directory Id="ProgramFilesFolder">
    <Directory Id="fooFolder" Name="foo">
      <Directory Id="INSTALLFOLDER" Name="Application Name" />
    </Directory>
  </Directory>

  <!-- users appdata folder-->
  <Directory Id="LocalAppDataFolder" Name="AppData">
    <Directory Id="AppRootDirectory" Name="Application Name" />
  </Directory>

</Directory>

 <Fragment>
<ComponentGroup Id="ProductComponents" Directory="INSTALLFOLDER">
  <Component Id="ProductComponent" Guid="{GUID}">

    <File Id="app.config.programfiles" Source="$(var.{ProjectName}.TargetDir)/{TargetName}.exe.config" />

  </Component>
</ComponentGroup>

<Fragment>

<DirectoryRef Id="ApplicationProgramsFolder">
  <Component Id="ApplicationShortcut" Guid="{GUID}">
    <Shortcut Id="ApplicationStartMenuShortcut"
         Name="My App"
       Description="My App description"
        Target="[INSTALLFOLDER]$(var.{App}.TargetFileName)"
              WorkingDirectory="INSTALLFOLDER"/>
    <RemoveFolder Id="ApplicationProgramsFolder" On="uninstall"/>
    <RegistryValue Root="HKCU" Key="Software\{Company}\{Application}" Name="installed" Type="integer" Value="1" KeyPath="yes"/>
  </Component>
</DirectoryRef>

This works fine and places the config file in the APPDIR, but I don't know what to do with the LocalAppDataFolder.
Am I approaching this the right way?

A: OK, so this is taken care of for you the first time that any of the userSettings are amended using the Save() method of the autogenerated Settings class:
Settings.Default.MyProperty = "foo";
Settings.Default.Save();

which results in the creation a user.config file in LocalAppDataFolder\{Company}\{Application}\{ProductName_xxx}\{Version} containing only the contents of the userSettings section of the app.config.


text: Q: Connectors do not appear automatically in easy custom labelling I'm using the easy custom labelling plugin in QGIS 3. When I move a label away from its associated polygon a connector does not automatically appear as in QGIS 2.18. How do I get connectors to appear in QGIS 3?


text:
Q: Como manipular coordenadas de uma página html livremente Como posso pegar as coordenadas de uma página HTML e partir dessas coordenadas setar um target/delimite(quadrado vermelho) de forma dinâmica (onde eu só altero as posições)
No caso deste contexto seria NÃO usar as medidas de uma DIV, mas sim, ter a liberdade de manipular onde eu quiser.
Exemplo:
Setar um target nessas coordenadas:

bottom: 575 height: 525 left: 8 right: 512 top: 50 width: 504 x: 8 y:
  50

no exemplo abaixo eu pego pelas dimensões da DIV, mas gostaria de passar as coordenadas desse target de forma 'livre'

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

A: Opa! não sei se entendi bem a pergunta, mas no seu caso criei a função changeSquare e chamei dentro do onload:

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

Dessa forma tu trata via jquery aplicando um css, só chamar a função changeSquare(200,200,200,200) por exemplo, acho que parece bem simples e auto-explicativo.


text:
Q: Adding the total number of distinct customers to a cte table in Microsoft SQL Server I am using Microsoft SQL Server and am trying to achieve the following

Date
Distinct Customers last 30Days

2020-12-01
20000

2020-12-02
23000

What I am trying to get is that between 2020-11-01 and 2020-12-01 I had 20000 distinct customers.
I have created a cte table with the List of Dates as can be seen below:
WITH listdate AS
(
  SELECT CAST('2020-11-01' AS datetime) DateValue
  UNION ALL
  SELECT  DateValue + 1
  FROM    listdate
  WHERE   DateValue + 1 < getdate()
)

SELECT
    cast(DateValue as date) as DateValue

FROM    listdate d

Now I am trying to join the customer and usage table with the list of dates table, however, I am not getting the correct end result. The following is what I have tried doing:

WITH listdate AS
(
  SELECT CAST('2020-11-01' AS datetime) DateValue
  UNION ALL
  SELECT  DateValue + 1
  FROM    listdate
  WHERE   DateValue + 1 < getdate()
)

SELECT
    cast(DateValue as date) as DateValue
    ,count(distinct case when m.CallDate between dateadd(dd,-30,cast(d.datevalue as date)) and cast(d.datevalue as date) then m.Customerid end) as Distinct_CID

FROM    listdate d

join Usage m on d.DateValue=m.CallDate

left join Customer c on c.CustomerID=m.Customer

where c.customertype = 'type A'

group by d.DateValue

OPTION (MAXRECURSION 0)

Can someone maybe suggest a different way of how to solve such a query?
Thanks

A: I would go for a lateral join to bring the count of distinct customers for the last 30 days:
with listdate as (
   select cast('20201101' as date) as datevalue
  union all
  select dateadd(day, 1, datevalue) from listdate where datevalue < cast(getdate() as date)
)
select ld.datevalue, x.cnt
from listdate ld
cross apply (
    select count(distinct c.customerid) as cnt
    from usage u
    inner join customer c on c.customerid = u.customerid
    where
        c.customertype = 'type A'
        and c.calldate >= dateadd(day, -29, datevalue)
        and c.calldate <  dateadd(day,   1, datevalue)
) x
option (maxrecursion 0)

Note that I simplified the parts related to dates: this uses proper literal dates and date arithmetics in the recursive query; the where clause of the subquery implements what I understand as the last 30 days (today + the preceding 29 days), and properly handles the time portion of calldate, if any.


text:
Q: Scrollview only Works in Listview I have the following layout defined in my app:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/disco_photo"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:scaleType="centerCrop" />

        <TextView
            android:id="@+id/disco_name"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_below="@id/disco_photo"
            android:layout_alignParentLeft="true"
            android:layout_gravity="left"
            android:layout_margin="8dp"
            android:gravity="end"
            android:textSize="20sp"
            android:textStyle="italic" />

        <TextView
            android:id="@+id/disco_times"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_below="@id/disco_name"
            android:layout_alignParentLeft="true"
            android:layout_gravity="left"
            android:layout_margin="8dp"
            android:gravity="end"
            android:textSize="20sp"
            android:textStyle="italic"
            android:visibility="gone" />

        <ListView
            android:id="@+id/disco_parties"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/disco_times"
            android:layout_alignParentLeft="true"
            android:layout_gravity="left"
            android:layout_margin="8dp"
            android:text="@string/map_view"
            android:gravity="end"
            android:textSize="20sp"
            android:textStyle="italic" />

        <RatingBar
            android:id="@+id/disco_rating"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_below="@id/disco_parties"
            android:numStars="5"
            android:stepSize="1.0"
            android:rating="3.0"
            android:visibility="gone" />

        <TextView
            android:id="@+id/disco_map"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_below="@id/disco_rating"
            android:layout_alignParentLeft="true"
            android:layout_gravity="left"
            android:layout_margin="8dp"
            android:text="@string/map_view"
            android:gravity="end"
            android:textSize="20sp"
            android:textStyle="italic" />

    </RelativeLayout>
</ScrollView>

I want to get scroll in the whole layout but the problems comes when only ListView is getting the scrollbar, so you can only scroll this list. The rest of the layour is fixed to the screen height.
How can I make the whole layout be scrollable? Thanks in advance.

A: I am going through your problem. You can not use list view inside the scroll-view directly. If you want to use it, then you have to give height pragmatically to list view and it work for me.
public class test1 extends Activity {
...
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test1);
...

//here 1st set your list view than call  set_List_View_Height_Based_On_Children...

set_List_View_Height_Based_On_Children(your_Listview_name);
...
}
///method set_List_View_Height_Based_On_Children
public static void set_List_View_Height_Based_On_Children(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null)
        return;

    int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
    int totalHeight = 0;
    View view = null;
    for (int i = 0; i < listAdapter.getCount(); i++) {
        view = listAdapter.getView(i, view, listView);
        if (i == 0)
            view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, ViewGroup.LayoutParams.WRAP_CONTENT));

        view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
        totalHeight += view.getMeasuredHeight();
    }
    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    listView.setLayoutParams(params);
    listView.requestLayout();
}
}

A: ListView can't be placed inside a ScrollView unless you define that your ListView isn't scrollable. If you wanna do this you should create a custom ListView like the following
    public class NonScrollListView extends ListViewCompat {

//Define a public constructor
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightMeasureSpec_custom = View.MeasureSpec.makeMeasureSpec(
                Integer.MAX_VALUE >> 2, View.MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
        ViewGroup.LayoutParams params = getLayoutParams();
        params.height = getMeasuredHeight();
    }
}

A: You should not use a ListView in a ScroolView, it has it's own scroll and they interfere with each-other.
I would recommend creating a list adapter that creates all of your different views from an array using a switch statement:
    class MyAdapter extends ArrayAdapter{

    public MyAdapter(Context context, int resource, List objects) {
        super(context, resource, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
         ViewItem viewType = getItem(position);

        switch(viewType.type){
            case TEXTVIEW: convertView = LayoutInflater.from(getContext()).inflate(R.layout.textView1, parent, false);

                break;
            case LISTITEM: convertView = LayoutInflater.from(getContext()).inflate(R.layout.listItem, parent, false);

                break;
        }

        return convertView;
    }

}