text:
Q: How to resolve "Execution failed for task':flutter_keyboard_visibility:compileDebugJavaWithJavac'" error? I'm getting

"Execution failed for task':flutter_keyboard_visibility:compileDebugJavaWithJavac'"

error while building the project. I've been working on this project for a while without a problem. The only thing I've done was a flutter upgrade. I did not add, delete a dependency or anything. I'm experiencing this issue on every single Flutter project now. When I try to build and run a native Android application, everything works as expected. I'm suspecting that Flutter cannot find Android SDK or similar to this but I can see that the path to Android SDK is as it should be. Below is the full version of errors Android Studio is giving me.
Running Gradle task 'assembleDebug'...
error: error reading /Users/sametsahin/.gradle/caches/modules-2/files-2.1/io.flutter/flutter_embedding_debug/1.0.0-2994f7e1e682039464cb25e31a78b86a3c59b695/469d369e7a7ea2b0f6b2822cfc8a6ec0cc99e962/flutter_embedding_debug-1.0.0-2994f7e1e682039464cb25e31a78b86a3c59b695.jar; error in opening zip file
error: error reading /Users/sametsahin/.gradle/caches/modules-2/files-2.1/io.flutter/flutter_embedding_debug/1.0.0-2994f7e1e682039464cb25e31a78b86a3c59b695/469d369e7a7ea2b0f6b2822cfc8a6ec0cc99e962/flutter_embedding_debug-1.0.0-2994f7e1e682039464cb25e31a78b86a3c59b695.jar; error in opening zip file
/Users/sametsahin/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-0.7.0/android/src/main/java/com/flutter/keyboardvisibility/KeyboardVisibilityPlugin.java:11: error: package io.flutter.app does not exist
import io.flutter.app.FlutterActivity;
                     ^
/Users/sametsahin/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-0.7.0/android/src/main/java/com/flutter/keyboardvisibility/KeyboardVisibilityPlugin.java:12: error: package io.flutter.plugin.common does not exist
import io.flutter.plugin.common.EventChannel;
                               ^
/Users/sametsahin/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-0.7.0/android/src/main/java/com/flutter/keyboardvisibility/KeyboardVisibilityPlugin.java:13: error: package io.flutter.plugin.common.EventChannel does not exist
import io.flutter.plugin.common.EventChannel.EventSink;
                                            ^
/Users/sametsahin/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-0.7.0/android/src/main/java/com/flutter/keyboardvisibility/KeyboardVisibilityPlugin.java:14: error: package io.flutter.plugin.common.EventChannel does not exist
import io.flutter.plugin.common.EventChannel.StreamHandler;
                                            ^
/Users/sametsahin/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-0.7.0/android/src/main/java/com/flutter/keyboardvisibility/KeyboardVisibilityPlugin.java:15: error: package io.flutter.plugin.common.PluginRegistry does not exist
import io.flutter.plugin.common.PluginRegistry.Registrar;
                                              ^
/Users/sametsahin/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-0.7.0/android/src/main/java/com/flutter/keyboardvisibility/KeyboardVisibilityPlugin.java:18: error: cannot find symbol
public class KeyboardVisibilityPlugin implements StreamHandler, Application.ActivityLifecycleCallbacks, ViewTreeObserver.OnGlobalLayoutListener {
                                                 ^
  symbol: class StreamHandler
/Users/sametsahin/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-0.7.0/android/src/main/java/com/flutter/keyboardvisibility/KeyboardVisibilityPlugin.java:21: error: cannot find symbol
    EventSink eventsSink;
    ^
  symbol:   class EventSink
  location: class KeyboardVisibilityPlugin
/Users/sametsahin/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-0.7.0/android/src/main/java/com/flutter/keyboardvisibility/KeyboardVisibilityPlugin.java:22: error: cannot find symbol
    Registrar registrar;
    ^
  symbol:   class Registrar
  location: class KeyboardVisibilityPlugin
/Users/sametsahin/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-0.7.0/android/src/main/java/com/flutter/keyboardvisibility/KeyboardVisibilityPlugin.java:26: error: cannot find symbol
    KeyboardVisibilityPlugin(Registrar registrar) {
                             ^
  symbol:   class Registrar
  location: class KeyboardVisibilityPlugin
/Users/sametsahin/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-0.7.0/android/src/main/java/com/flutter/keyboardvisibility/KeyboardVisibilityPlugin.java:100: error: cannot find symbol
    public static void registerWith(Registrar registrar) {
                                    ^
  symbol:   class Registrar
  location: class KeyboardVisibilityPlugin
/Users/sametsahin/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-0.7.0/android/src/main/java/com/flutter/keyboardvisibility/KeyboardVisibilityPlugin.java:113: error: cannot find symbol
    public void onListen(Object arguments, final EventSink eventsSink) {
                                                 ^
  symbol:   class EventSink
  location: class KeyboardVisibilityPlugin
/Users/sametsahin/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-0.7.0/android/src/main/java/com/flutter/keyboardvisibility/KeyboardVisibilityPlugin.java:57: error: cannot find symbol
        if (activity instanceof FlutterActivity) {
                                ^
  symbol:   class FlutterActivity
  location: class KeyboardVisibilityPlugin
/Users/sametsahin/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-0.7.0/android/src/main/java/com/flutter/keyboardvisibility/KeyboardVisibilityPlugin.java:77: error: cannot find symbol
        if (activity instanceof FlutterActivity) {
                                ^
  symbol:   class FlutterActivity
  location: class KeyboardVisibilityPlugin
/Users/sametsahin/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-0.7.0/android/src/main/java/com/flutter/keyboardvisibility/KeyboardVisibilityPlugin.java:88: error: cannot find symbol
        if (activity instanceof FlutterActivity) {
                                ^
  symbol:   class FlutterActivity
  location: class KeyboardVisibilityPlugin
/Users/sametsahin/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-0.7.0/android/src/main/java/com/flutter/keyboardvisibility/KeyboardVisibilityPlugin.java:102: error: cannot find symbol
        final EventChannel eventChannel = new EventChannel(registrar.messenger(), STREAM_CHANNEL_NAME);
              ^
  symbol:   class EventChannel
  location: class KeyboardVisibilityPlugin
/Users/sametsahin/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-0.7.0/android/src/main/java/com/flutter/keyboardvisibility/KeyboardVisibilityPlugin.java:102: error: cannot find symbol
        final EventChannel eventChannel = new EventChannel(registrar.messenger(), STREAM_CHANNEL_NAME);
                                              ^
  symbol:   class EventChannel
  location: class KeyboardVisibilityPlugin
/Users/sametsahin/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-0.7.0/android/src/main/java/com/flutter/keyboardvisibility/KeyboardVisibilityPlugin.java:112: error: method does not override or implement a method from a supertype
    @Override
    ^
/Users/sametsahin/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_keyboard_visibility-0.7.0/android/src/main/java/com/flutter/keyboardvisibility/KeyboardVisibilityPlugin.java:123: error: method does not override or implement a method from a supertype
    @Override
    ^
18 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':flutter_keyboard_visibility:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* 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

BUILD FAILED in 6s
Finished with error: Gradle task assembleDebug failed with exit code 1

Also when I check the build.gradle file found in danef_dictionary/android/app/build.gradle
I realize that GradleException is red and says

Cannot resolve symbol 'GradleException'

when I hover over it.
What do I need to do?

A: I solved my problem by making following changes:
In Android build.gradle
Changed
classpath 'com.android.tools.build:gradle:3.2.1'
to
classpath 'com.android.tools.build:gradle:3.5.3'
Changed
ext.kotlin_version = '1.2.71'

to
ext.kotlin_version = '1.3.50'

In android/gradle/wrapper/gradle-wrapper.properties
Changed
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-all.zip

to
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip


text:
Q: The requested resource was not found on this server OR 404 error on server I am trying to create a filesystem upload for my blog news.
I have this code on my controller :
public function store(Request $request)
    {

          ini_set('memory_limit','99999M');
    ini_set('post_max_size','99999M');
    ini_set('upload_max_filesize','99999M');
    ini_set('max_input_time', 36000); // 10 houres
    set_time_limit(36000); // 10 houres
    $file= $request->file('image');
    $filename= date('YmdHi').$file->getClientOriginalName();

        $now = Carbon::now();
        $randomChain = Str::random(12);
        $pic = $randomChain.$file;
        Post::create(['title' => $request->title,
            'body' => $request->body,
            'user_id' => Auth::id(),
            'slug' =>  Str::slug($request->title),
            'meta_description' =>  Str::substr($request->body,0, 147),
            'meta_keywords' => $request->body,
            'excerpt' => Str::substr($request->body,0, 147),
            'active' => 1,
            'image' => $filename,
            'created_at' => $now,
            'updated_at' => NULL,
            'seo_title' => '',]
        );

        Storage::disk('public')->put($filename,  $file);

It seems to work fine, data are correctly insered in table, and the file (an image) is uploaded on my localhost server and on production server too. But in the two cases, I can't access on the image via 127.0.0.1:8000/img/image.jpg or server.com/img/image.jpg
It returns to me an erreur from Apache (I guess) "The requested resource was not found on this server" on localhost. And on my server it returns a 404 error. But the file image.jpg is on the 2 servers, I can show it by doing ls -ila and I correctyly type the URL by doing copy and paste.
Also there is the code for the upload view :

<form method="POST" enctype="multipart/form-data" action="{{ route('posts.store') }}">
    @csrf
    <input type="text" name="title" placeholder="titre">

    <textarea name="body" cols="30" rows="10" placeholder="article"></textarea>
    <input type="file" name="image" placeholder="Choose image" id="image">
    <input type="submit" name="Envoyer">

</form>

And maybe me fylesystem.php can help you :
<?php

return [

    'default' => env('FILESYSTEM_DRIVER', 'local'),

    'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

    'links' => [
        public_path('storage') => storage_path('app/public'),
        public_path('mvbimg') => storage_path('app/mvbimg'),

    ],

];

Thank you for helping

redpajama_set_name: RedPajamaStackExchange


text:
Q: ruby regex and grouping I've got following text 'some-text-here' and try to get the 'text' word from it using groups.
If I use that expression /some-(\w+)-here/ all works fine, but if I try to apply grouping to it /some-(?<group_name>\w+)-here/ it's raise an error Undefined (?...) sequence.
What's I doing wrong?
(Ruby 1.9.2)
Upd: shame on me. It's all from my innatention. Yes, I've use RVM and my ruby version turned on 1.9.2. But I've tested that expression at http://rubular.com/ where it is written at the footer Rubular runs on Ruby 1.8.7. Ruby 1.8.7 and Ruby 1.9.2 have a different regular expression engine.
So my expression works on 1.9.2, but does not on 1.8.7

A: For me that looks like you are looking at the wrong Ruby. Do you maybe have RVM installed?
1.9.2
>> RUBY_VERSION
=> "1.9.2"
>> s='some-text-here'
=> "some-text-here"
>> /some-(?<group_name>\w+)-here/ =~ s
=> 0
>> group_name #=> "text"

1.8.7
>> RUBY_VERSION
=> "1.8.7"
>> s='some-text-here'
=> "some-text-here"
>> /some-(?<group_name>\w+)-here/ =~ s
SyntaxError: compile error
(irb):2: undefined (?...) sequence: /some-(?<group_name>\w+)-here/
    from (irb):2

A: These are my results with 1.9.2-p290:
irb(main):004:0> "some-text-here".match(/some-(?<test>\w+)-here/)
=> #<MatchData "some-text-here" test:"text">
irb(main):005:0> RUBY_VERSION
=> "1.9.2"


text:
Q: Some sort of X.org memory leak using nvidia proprietary driver Could please anybody help me identify what is the source of problem? The problem is that after some time or after opening a window of some application in X, it seems like I suddenly lost 2d acceleration.
Because the process /usr/bin/Xand all its operations ( window resizing, scrolling) suddenly eats 60% to 150% of CPUs runtime when scrolling window for instance.
I'm using twinview, but it happens even without it, but not so much. I'm not using any composition in KDE or xfce.
The nvidia driver installation logs looks there was no problem during the installation.
I tried various different kernel versions, 2 different Xorg version, 2 versions of nvidia driver and even different window managers.
It only happens in particular time frames, if I open some specific www page or application in browser or it comes from nowhere.
It is possible that it could be triggered by some flash animation, gif animation, javascript scrolling text or other effects in browser, but it is really hard to say, because it usually appears suddenly (when reading something in browser for instance).
As far as xorg.conf, I have the default one from nvidia-settings. I also tried various possible configurations and modules.
I have glxgears 2.241 FPS and after the problem is gone I have 6267.623 FPS.
Slackware-current - kernel 2.6.35.11 , 2.6.35.10 , 2.6.36.x 2.6.37
X.Org X Server 1.9.4
KDE 4.5.5   or   xfce-4.6.2
NVIDIA-Linux-x86_64-260.19.36  + twinview
Geforce 8400 GS

APPS:
google-chrome-8
XChat 2.8.8
eclipse-3.6


text:
Q: Removing unneccessary p-tags (Not every p) I removed wpautop from my theme:
function disable_linebreaks($content) {
       remove_filter ('the_content','wpautop');
       return $content;
}
add_filter('the_content','disable_linebreaks',1);

But now, when switching between HTML and Editor ALL p-tags disappear, even the ones I coded myself.
What I want is just to prevent Wordpress from adding empty

 - Code. Basically I'm happy with wpautop, it's just that sometimes it's too much (For example around images. There's always an empty p before every image).

A: If what you want is really only

to prevent Wordpress from adding empty

and you'd be happy with removing those after post retrieval from the database, then
function wpse108194_remove_empty_paragraphs( $content ) {
   $content = preg_replace( '#
\s*
#', '', $content );
   return $content;
}
add_filter( 'the_content', 'wpse108194_remove_empty_paragraphs', 11 );

will do.


text:
Q: Grass GIS: ArcGIS' "Raster to polygon" equivalent I've got a small clipped extent of a LANDSAT image and I need to have the single pixels as polygons in order to tell the overlap proportions of overlaying polygons.
In ArcGIS I used "Raster to polygon" without simplyfying polygons and used the "identity" tool then.
What would be a good equivalent in Grass GIS?
For "raster to polygon", I found "r.to.vect", but Grass always complains that the raster is "not properly thinned". I didn't understand what 'r.thin' does and I don't want ANY changes in the raster values.
Can anybody help with a "clean" solution?
EDIT:
According to Micha's answer, here's an illustration of what my final goal is:

A: According to the docs thinning is for line features. Remember to select "area" as the feature type in r.to.vect.

A: I think gdal_polygonize might help you. It will convert a raster to vector format (GML, shapefile, etc). By default it connects the cell that have same values, but from your description, it should not be a problem.
This text comes from the official site:

This utility creates vector polygons for all connected regions of
  pixels in the raster sharing a common pixel value. Each polygon is
  created with an attribute indicating the pixel value of that polygon.
  A raster mask may also be provided to determine which pixels are
  eligible for processing.

Below is a example converting a piece of raster to GML:
$ gdal_polygonize.py srtm_36_02.tif srtm_36_02.gml
Creating output srtm_36_02.shp of format GML.
0...10...20...30...40...50...60...70...80...90...100 - done.

[]

A: It seems that you final goal is to total raster values for each vector polygon. It's worth pointing out that the GRASS module v.rast.stats does just that.


text:
Q: Merging a string to a structured string If I have a string like this:
FOO BAR YY
- foo bar y
- foo bar x
FOO BAR AA
- foo bar z
- foo bar y

And another String like this:
"FOO BAR YY;- foo bar new entry"

I need a generic way to find the string FOO BAR YY or a similar string of the first level and concatenate my substring -foo bar k inside a new line to get this result:
FOO BAR YY
- foo bar new entry
- foo bar y
- foo bar x
FOO BAR AA
- foo bar z
- foo bar y

Is there an elegant way to find and insert instead the substring?

A: An elegant way would be to implement a parser (which parses the original string into convenient data structure) and a generator (which creates the string back). This is the rough sketch how to do it (using Java-7):
public class MyStructure {
    private Map<String, List<String>> map = new LinkedHashMap<>();

    public MyStructure(String src) {
        parse(src);
    }

    private void parse(String src) {
        String curKey = null;
        List<String> curList = null;
        for(String line : src.trim().split("\n")) {
            if(line.startsWith("- ")) {
                if(curList == null) {
                    throw new IllegalStateException("Unexpected line");
                }
                curList.add(line);
            } else {
                if(curKey != null) {
                    map.put(curKey, curList);
                }
                curKey = line;
                curList = new ArrayList<>();
            }
        }
        if(curKey != null)
            map.put(curKey, curList);
    }

    public void add(String key, String value) {
        List<String> list = map.get(key);
        if(list == null) {
            list = new ArrayList<>();
            map.put(key, list);
        }
        list.add(0, value);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for(Entry<String, List<String>> entry : map.entrySet()) {
            sb.append(entry.getKey()).append("\n");
            for(String item : entry.getValue())
                sb.append(item).append("\n");
        }
        return sb.toString();
    }
}

Here's usage example:
public static void main(String[] args) {
    MyStructure ms = new MyStructure("FOO BAR YY\n" +
            "- foo bar y\n" +
            "- foo bar x\n" +
            "FOO BAR AA\n" +
            "- foo bar z\n" +
            "- foo bar y");
    System.out.println("Before: " + ms);
    String toAdd = "FOO BAR YY;- foo bar new entry";
    String[] fields = toAdd.split(";", 2);
    ms.add(fields[0], fields[1]);
    System.out.println("After: " + ms);
}

Output:
Before: FOO BAR YY
- foo bar y
- foo bar x
FOO BAR AA
- foo bar z
- foo bar y

After: FOO BAR YY
- foo bar new entry
- foo bar y
- foo bar x
FOO BAR AA
- foo bar z
- foo bar y

Having data structure is much better as it will allow later to do other operations conveniently. For example, you can easily support items removal or reordering.

A: I would suggest that you use a suitable data structure to store your structured data.  Rather than a String you could store your data as a Multimap (for example Guava Multimap).
So your existing data would be represented like
Multimap<String, String> myData = ArrayListMultimap.create();
myData.put("FOO BAR YY", "- foo bar y");
myData.put("FOO BAR YY", "- foo bar x");
myData.put("FOO BAR AA", "- foo bar z");
myData.put("FOO BAR AA", "- foo bar y");

then adding new data becomes trivial
myData.put("FOO BAR YY", "- foo bar new entry");

or in your case:
String[] entryLine = "FOO BAR YY;- foo bar new entry".split(";", 2);
myData.put(entryLine[0], entryLine[1]);

to pull out all the data for a specific key:
myData.get("FOO BAR YY")

returns
["- foo bar y", "- foo bar x", "- foo bar new entry"]

A: I'm not sure if I understood you correctly, but my answer would be something like this:

String list = "FOO BAR YY\n"
    + "- foo bar y\n"
    + "- foo bar x\n"
    + "FOO BAR AA\n"
    + "- foo bar z\n"
    + "- foo bar y\n";
String entry = "FOO BAR YY;- foo bar new entry";

//The first position will be the term to search and the second the new entry
//The second parameter puts a limit so it only splits the string in two,
//this way it only takes out the first appearence
String[] entrySplit = entry.split(";", 2);
//We split by the search term so we can insert the new line
//We make sure the search term is the only thing in its line
String[] listSplit = list.split("^" + entrySplit[0] + "$", 2);
//We must insert the search term again
list = listSplit[0] + entrySplit[0] + "\n" + entrySplit[1] + listSplit[1];

This solution is arguably elegant. A more elegant solution would be having your list in a Map<String,String[]> or a similar data structure, but if you must work with Strings this is what I would do.

EDIT: I see other answers like @Tagir Valeev 's cover the Map solution. It is, indeed, better and more efficient (and more elegant) to store the list in a data structure.


text: Q: How can I prove an associative ring is commutative? Given an associative ring, $(R, +, \cdot)$, and the bracket operation defined by $[a,b] = ab-ba$ how can I prove $[a,[b,c]] = 0$ for $a,b,c \in R$? I think the ring must be commutative, so $a(bc-cb) = (bc-cb)a$ and thus $=0$, but I do not know how to prove the ring is commutative.


text:
Q: Caret Model how to train the final model using optimized parameters? train_control <- trainControl(method='cv', number=10)
model <- train(Class ~ Age+BMI+DBP+DPF+NumPregnancies+PG2+SI2+TSFT, method ='rf',data=input,trControl=train_control)

pmml(model$finalModel)
#Error in names(field$class) <- var.names : attempt to set an attribute on NULL

When I try to export the caret trained RF model to PMML, It fails. Is there a method to run RF manually using the optimal parameters tuned by caret package so that I can export the model to PMML?

A: Tuned Parameters can be accessed through model$bestTune
> model$bestTune
mtry
3   23

A: The "rf" method in caret make use of the randomForest package and randomForest function. This is if you want to run basic random forest "manually", without caret.


text:
Q: Host key verification failed while npm install in ember project npm install is failing with below error, git clone, npm -v, git pull everything is working fine. This issue I am facing in my cloned repo folder only other places npm install is working fine.
npm ERR! Error while executing:
npm ERR! C:\Program Files\Git\cmd\git.EXE ls-remote -h -t ssh://git@github.com/ember-cli/ember-ajax.git
npm ERR!
npm ERR! Host key verification failed.
npm ERR! fatal: Could not read from remote repository.
npm ERR!
npm ERR! Please make sure you have the correct access rights
npm ERR! and the repository exists.
npm ERR!
npm ERR! exited with error code: 128


text:
Q: Chat Bot from Google Sheets Event - Double Function? I am trying to have a bot send a message to a chat room based on a FALSE check mark in a specific cell on a sheet.
I have the function working for

*

*Timestamp and getEffectiveUser().getEmail - for accountability

*function sendReminder() - which uses a webhook to send a message to a chat room (stole this one from Google Dev)

Here is the code I have and I have tried many, many variations to call the function sendReminder if e.value == "FALSE" (I understand this is not the ideal method and certainly am open to suggestions)
Here is the code as it stands but the only way it works is manually - Again would like for sendReminder to fire off once the cell has "FALSE" in it.

function onEdit(e){

  if(e.value == "TRUE"){
    e.source.getSheetByName("Daily").getRange(e.range.rowStart,e.range.columnStart+1).setValue(Session.getEffectiveUser().getEmail());
    e.source.getSheetByName("Daily").getRange(e.range.rowStart,e.range.columnStart+2).setValue(new Date()).setNumberFormat("MM/dd/yyyy hh:mm");}
return e.value;
}

function sendReminder(){
var data = {
text: "Looks like LCH Temp is open right now - Can someone take over?"
};
var payload = JSON.stringify(data);
var options = {
method: 'POST',
contentType: 'application/json',
payload: payload
};
var url = 'https://chat.googleapis.com/v1/spaces/AAAAuBSsspc/messages?key=AIzaSyDdI0hCZtE6vySjMm-WEfRq3CPzqKqqsHI&token=jqvtFaKqM1a_spMOJFByn29jTEL5iF-JZQ9BEFws9u4%3D'
var rsp = UrlFetchApp.fetch(url, options);
}

A: Answer:
Simple Triggers have restrictions on what type of methods can be run. You will need to change this to an installable trigger.
More Information:
As per the documentation on Simple Triggers:

They cannot access services that require authorization. For example, a simple trigger cannot send an email because the Gmail service requires authorization, but a simple trigger can translate a phrase with the Language service, which is anonymous.

As UrlFetchApp requires authorisation, you will not be able to run this from just a simple trigger.
Fix:
You will need to have your checking code inside you onEdit(e) for "FALSE", something like:
function whenEdited(e) {
  // whatever code you already have
  // change "C5" on the next line to whatever specific cell you want to check:
  if (e.range.getA1Notation() == "C5" && e.value == "FALSE") {
    sendReminder()
  }
}

Then, you will need to set up your whenEdited() function as an installable trigger:
Setting up the Trigger:
Save the script with the save icon, press the run button (►), and confirm the authentication of running the script.
From here, following the Edit > Current project's triggers menu item, you will have a new page open in the G Suite Developer Hub. Click the + Add Trigger button in the bottom right and set up the trigger settings as follows:

*

*Choose which function to run: whenEdited

*Choose which deployment should run: Head

*Select event source: From spreadsheet

*Select type of time based trigger: On edit

And press save. Now, whenever the cell you specified is edited, the sendEmails() function will run, pre-authorised as you.
References:

*

*Simple Triggers | Apps Script | Google Developers

*Installable Triggers | Apps Script | Google Developers


text:
Q: What is better, installing Win8 on an SSD directly or using the SSD for ReadyBoost? For a medium SSD and a large HD, which scenario has a better performance-to-annoyance ratio?

*

*Install Windows on my HD and use ReadyBoost to cache the hottest 32GB of files from my HD. Install some programs manually on the SSD to use all it's speed.

*Install Windows on my SSD and install some programs manually on the HD when I'm concerned about space.

Let's say 90GB SSD and 1TB HD if you want to put solid numbers to it. I want to make this question applicable to more people than my specific hard drive sizes though.

A: I would recommend installing the OS on the SSD.  The biggest benefit you'll notice are faster boot times.  ReadyBoost provides some of the performance improvements, but it won't be across the board like the full OS would.


text:
Q: How to download a file from a url with Javascript? How to download a file from a url with Javascript?
I'm trying to get from a textfield a user enters a url as follows:
new Ext.form.TextField({
                disabled: false,
                        fieldLabel: "file",
                        value:'',
            id:"url"};

and I need the value of this variable is the file contained in the above url I am trying as follows:
var file1 = new OpenLayers.WPS.ComplexPut({
                      identifier: "file1",
                      value: window.location.href = document.getElementById("url")

A: is this done in a browser? If so, you could use Ajax to download plain text or XML. Save yourself a lot of trouble and learn jQuery first, and it'll be quite easy.

A: You can use jQuery to load anything from an URL quite easily with:
<script>
   $("#loadhere").load("http://www.google.com");
</script>


text:
Q: Export only selected and reordered columns to Excel I am using QGIS 3.12. I want to export my attribute table to an exciting EXCEL table but I want to arrange the columns in a different order and also to select which columns to export and which not. Is it possible?

A: I think the best way is to use the "Refactor fields" tool from the processing toolbox.
This tool let you reorder field, drop field, rename field and even using expression to change field value. You can then save the result in many different format including .xlsx
From the tool help :

Refactor fields :
This algorithm allows editing the structure of the attributes table of
  a vector layer. Fields can be modified in their type and name, using a
  fields mapping. The original layer is not modified. A new layer is
  generated, which contains a modified attribute table, according to the
  provided fields mapping.


text:
Q: Get last key from jsonb (postgres) Considering the following content on a jsonb field, and that the keys immediately after "audio" are random (I'll never know which value it'll be returning beforehand): is there any way I can query for the last key inside "audio" ("2814462280" in this example)?
   {
        "test": {
            "audio": {
                "1175828715": {
                    "direction": "outbound",
                },
                "2814462280": {
                    "direction": "inbound",
                }
            }
        }
    }

A: I've wrote a function to dynamically construct jsonb path to get the last key value.
As was previously mentioned in the comments section Postgres can reorder the keys in a jsonb field.
Here is the demo.
do $$
declare
  -- instantiate all the necessary variables
  audio_json jsonb;
  audio_json_keys text[];
  last_key_index integer;
  last_key_pointer text;
  result_json jsonb;
  query text;

begin

audio_json := (select (metadata->>'test')::jsonb->>'audio' from test);
audio_json_keys := (select array_agg(keys) from jsonb_object_keys(audio_json::jsonb) keys);
last_key_index := (select array_length(audio_json_keys, 1));
last_key_pointer := audio_json_keys[last_key_index];

query := 'select (''' || audio_json::text || ''')::jsonb->>''' || last_key_pointer::text || '''';
execute query into result_json;

raise info '%', result_json;

end $$;

A: Object.keys can be useful in this case. If you want to query for the last key. you can try following
const obj =    {
        "test": {
            "audio": {
                "1175828715": {
                    "direction": "outbound",
                },
                "2814462280": {
                    "direction": "inbound",
                }
            }
        }
    }

const audio_obj:any = obj.test.audio
const keys = Object.keys(audio_obj)
const len = keys.length
const lastKey: string = keys[len-1] // "2814462280"

if you want to get the last object you can add one line code
const lastObj = audio_obj[lastKey] // {"direction": "inbound"}

Hope this helps you.


text:
Q: g++ ld shared library error with code::blocks There are similar topics, but I haven't managed to find my answer in them.
I am building a test console application using the code::blocks IDE. It needs to load a DVB shared library called libhdhomerun.so (from Silicon Dust) for the HD Homerun DVB tuners. The HDHR tuner library has being installed using ./configure, ..., sudo make install, ldconfig etc and it all works with their utilities (built at the same time). So - the library is there and OK.
The library installed itself into /usr/local/lib. There is actually no symlink to it as there is with other shared libraries, but then it doesn't have any version information on the end either.
When I build the code (having explicitly included /usr/local/lib/libhdhomerun.so), the ld stage fails with
"cannot find -lhdhomerun.so"

I have tried every combination of including (/usr/local/lib/) libhdhomerun.so, hdhomerun.so, libhdhomerun, hdhomerun, creating a symlink to it etc. Nothing makes any difference.
The bizarre thing is that I have udev, mysql and libdvbv5 shared libraries included in exactly the same way, and they are fine. The only one that will not link is hdhomerun.
If I run a manual verbose link step from the command line "ld -lhdhomerun.so --verbose", it does fail - because it is trying to find libhdhomerun.so.so.
Any suggestions gratefully received - but I do need to keep using code::blocks.

A: To link the library properly, you need to have library path defined in your environment, and use proper library name with -l flag. Library path is defined in LD_LIBRARY_PATH environment variable. For -l flag to g++, library extension should not be provided - as you already observed, so in your case it should be like this:
-lhdhomerun


text:
Q: jQuery Mobile - Toolbar Ellipsis in iPad I am rendering HTML locally in an iPad app using jQuery Mobile. The titles are getting "..." ellipses in them, even though there is lots of room. I am using off-the-shelf JQM and JQM CSS classes.
How can I tell JQM to render the full title?
Below is a screen shot with some blue markup.
Here's the Title:
`

the long title goes here

`

A: The h1 tag gets margin applied that you can overwrite so the title won't get clipped so much.
.ui-page .ui-header h1 {
    margin-left  : 0;
    margin-right : 0;
}

Here is a demo: http://jsfiddle.net/ubYWU/
Note that you will want to give left/right margin values that make it so your title won't overlap with your icon(s).

A: The combination of setting overflow:hidden and text-overflow:ellipsis is what is causing that  Override the ui-title then play with the margin to try and center. They probably include this to make room for buttons in the header and footer. Try this:
.ui-header .ui-title, .ui-footer .ui-title {
    overflow:visible;
    margin: .6em 20%;
}

JQM 1.1-RC1's default left and right margin was set at 30% for this. Just adjust it till it fits your needs.
UPDATE: I added the version that used the 30% default. Thanks Jasper.

A: It's also important to note you should add a "line-height:" to your elements so in case they wrap they will not land on top each other on line 2


text:
Q: return list of validation errors on field in pydantic Is it possible to return a list of validation errors for a specific field, without having separate validators for the same field? It would be nice to get all errors back in 1 shot for the field, instead of having to get separate responses back for each failed validation.
@validator('password')
def check_password(cls, value):
    password = value.get_secret_value()

    failed = []

    min_length = 8
    if len(password) < min_length:
        failed.append('Password must be at least 8 characters long.')
        return value

    if not any(character.islower() for character in password):
        failed.append('Password missing lower case')
        return value

   if len(failed) > 0:
      raise ValueError(failed)

Output:
{
    "detail": [
        {
            "loc": [
                "body",
                "password"
            ],
            "msg": "['Password must be at least 8 characters long.', 'Password missing lower case']",
            "type": "assertion_error"
        }
    ]
}

However, "msg" comes as a string list. Can we get that as a list?

A: I don't think that's possible.
If you check out the class delcaration ValidationError In the repository for pydantic, you  see how the msg prop is generated using the method error_dict
In error_dict msg is generated using the following code :

 type_ = get_exc_type(exc.__class__)
    msg_template = config.error_msg_templates.get(type_) or getattr(exc, 'msg_template', None)
    ctx = exc.__dict__
    if msg_template:
        msg = msg_template.format(**ctx)
    else:
        msg = str(exc)

Which will always return a string, no matter what you pass to your ValueError constructor.
Furthermore, splitting your function into multiple validators doesn't seem to work either, as pydantic will only report the first failing validator

from pydantic import BaseModel, validator

class TestModel(BaseModel):
    password: str

    @validator("password")
    def is_lower_case(cls, value):
        if not value.islower():
            raise ValueError("Must be lower")
        return value

    @validator("password")
    def is_long_enough(cls, value):
        if len(value) < 3:
            raise ValueError("Too short")
        return value

Output:

>>> from test_model import TestModel
>>> TestModel(password="Te")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pydantic/main.py", line 331, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for TestModel
password
  Must be lower (type=value_error)

A: Decided to add a middleware to FastAPI as a low touch approach to solving this for my use case. I do not want to modify / manage custom installations of pydantic, so adding a middleware to my API seems like a better alternative, for now?
@app.exception_handler(RequestValidationError)
def validation_exception_handler(request, exc):
    errors = []

    for each in exc.errors():
        error = {"message" if key == "msg" else key: ast.literal_eval(value) if value[0] == '[' and value[-1] == ']' else value for key, value in each.items()}
        errors.append(error)

    return JSONResponse({"detail": errors}, status_code = 422)

Above logic is renaming the "msg" key to "message", and converting list representations in a string to a list.

A: Here is my "caveman approach" for this problem - unwrap the string list with regex:
import re
from pydantic import BaseModel, ValidationError, validator

class UserModel(BaseModel):

    username: str
    password: str

    @validator("password")
    def passwords_match(cls, v):
        errors = []
        if "7" in v:
            errors.append("Illegal password")
        if len(v) < 4:
            errors.append("too short")
        if errors:
            raise ValueError(errors)

        return v

try:
    UserModel(
        username='scolvin',
        password='gg7'
    )
except ValidationError as e:
    for error in e.errors():
        error_msg = error["msg"]
        L = [m[0][1:-1] for m in re.finditer("'[^']*'", error_msg)]
        error["msg"] = L
    print(e.json())

It contains a complete reproducible minimal example and solution. It is indeed not that elegant, but might just be what solves your problem.

A: You can use ast.literal_eval on msg field value.


text:
Q: MySQL Optimizations I'm running a dedicated server with about 20 websites active. About 6 of them are Magento installations. Running the server as a webserver (web, e-mail, and MySQL ).
This is a preemptive optimization. Currently, I don't seem to have any issues, but I feel that it's good to be proactive and optimize now to avoid any potential problems later.
The server is an 8 core CPU, 8Gb RAM, running CentOS 6. The 8GB of RAM is spread around the entire server, not just the database.
I'm trying to optimize my MySQL installation for the best possible performance and stability. Ran MySQLTuner (1.7.4) and getting these suggestions.
Would appreciate some help in optimizing the settings.
Thank you!
UPDATE: 11/28/2017 08:20PM EST
 - Added additional 8GB of RAM.
 - Latest MySQLTuner results. Global Status, Variables, Innodb Status files updated.

Can view the 3 files requested here.
Latest info below:
-------- Storage Engine Statistics -----------------------------------------------------------------
[--] Status: +ARCHIVE +BLACKHOLE +CSV -FEDERATED +InnoDB +MEMORY +MRG_MYISAM +MyISAM +PERFORMANCE_SCHEMA
[--] Data in MyISAM tables: 90M (Tables: 300)
[--] Data in InnoDB tables: 923M (Tables: 3591)
[--] Data in MEMORY tables: 3M (Tables: 141)
[OK] Total fragmented tables: 0

-------- Security Recommendations ------------------------------------------------------------------
[OK] There are no anonymous accounts for any database users
[OK] All database users have passwords assigned
[--] There are 612 basic passwords in the list.

-------- CVE Security Recommendations --------------------------------------------------------------
[OK] NO SECURITY CVE FOUND FOR YOUR VERSION

-------- Performance Metrics -----------------------------------------------------------------------
[--] Up for: 13d 17h 16m 32s (29M q [25.279 qps], 860K conn, TX: 43G, RX: 9G)
[--] Reads / Writes: 68% / 32%
[--] Binary logging is disabled
[--] Physical Memory     : 7.7G
[--] Max MySQL memory    : 5.1G
[--] Other process memory: 964.7M
[--] Total buffers: 4.4G global + 1.1M per thread (100 max threads)
[--] P_S Max memory usage: 555M
[--] Galera GCache Max memory usage: 0B
[OK] Maximum reached memory usage: 5.0G (65.37% of installed RAM)
[OK] Maximum possible memory usage: 5.1G (66.51% of installed RAM)
[OK] Overall possible memory usage with other process is compatible with memory available
[OK] Slow queries: 0% (35/29M)
[OK] Highest usage of available connections: 21% (21/100)
[OK] Aborted connections: 0.01%  (114/860297)
[!!] name resolution is active : a reverse name resolution is made for each new connection and can reduce performance
[!!] Query cache may be disabled by default due to mutex contention.
[OK] Query cache efficiency: 90.8% (22M cached / 25M selects)
[!!] Query cache prunes per day: 43104
[OK] Sorts requiring temporary tables: 0% (38 temp sorts / 360K sorts)
[!!] Joins performed without indexes: 22932
[OK] Temporary tables created on disk: 23% (201K on disk / 844K total)
[OK] Thread cache hit rate: 99% (21 created / 860K connections)
[OK] Table cache hit rate: 47% (7K open / 16K opened)
[OK] Open file limit used: 4% (867/20K)
[OK] Table locks acquired immediately: 99% (5M immediate / 5M locks)

-------- Performance schema ------------------------------------------------------------------------
[--] Memory used by P_S: 555.4M
[--] Sys schema isn't installed.

-------- ThreadPool Metrics ------------------------------------------------------------------------
[--] ThreadPool stat is enabled.
[--] Thread Pool Size: 8 thread(s).
[!!] thread_pool_size between 16 and 36 when using InnoDB storage engine.

-------- MyISAM Metrics ----------------------------------------------------------------------------
[!!] Key buffer used: 19.5% (52M used / 268M cache)
[OK] Key buffer size / total MyISAM indexes: 256.0M/22.5M
[OK] Read Key buffer hit rate: 99.9% (3M cached / 3K reads)
[!!] Write Key buffer hit rate: 42.3% (124K cached / 52K writes)

-------- InnoDB Metrics ----------------------------------------------------------------------------
[--] InnoDB is enabled.
[--] InnoDB Thread Concurrency: 4
[OK] InnoDB File per table is activated
[OK] InnoDB buffer pool / data size: 4.0G/923.8M
[!!] Ratio InnoDB log file size / InnoDB Buffer pool size (50 %): 1.0G * 2/4.0G should be equal 25%
[!!] InnoDB buffer pool instances: 8
[--] InnoDB Buffer Pool Chunk Size not used or defined in your version
[OK] InnoDB Read buffer efficiency: 99.99% (383379684 hits/ 383413960 total)
[!!] InnoDB Write Log efficiency: 72.46% (2434433 hits/ 3359563 total)
[OK] InnoDB log waits: 0.00% (0 waits / 925130 writes)

-------- AriaDB Metrics ----------------------------------------------------------------------------
[--] AriaDB is disabled.

-------- TokuDB Metrics ----------------------------------------------------------------------------
[--] TokuDB is disabled.

-------- XtraDB Metrics ----------------------------------------------------------------------------
[--] XtraDB is disabled.

-------- RocksDB Metrics ---------------------------------------------------------------------------
[--] RocksDB is disabled.

-------- Spider Metrics ----------------------------------------------------------------------------
[--] Spider is disabled.

-------- Connect Metrics ---------------------------------------------------------------------------
[--] Connect is disabled.

-------- Galera Metrics ----------------------------------------------------------------------------
[--] Galera is disabled.

-------- Replication Metrics -----------------------------------------------------------------------
[--] Galera Synchronous replication: NO
[--] No replication slave(s) for this server.
[--] This is a standalone server.

-------- Recommendations ---------------------------------------------------------------------------
General recommendations:
    Control warning line(s) into /var/lib/mysql/ file
    Control error line(s) into /var/lib/mysql/ file
    Configure your accounts with ip or subnets only, then update your configuration with skip-name-resolve=1
    Adjust your join queries to always utilize indexes
    Consider installing Sys schema from https://github.com/mysql/mysql-sys
    Thread pool size for InnoDB usage (8)
    Read this before changing innodb_log_file_size and/or innodb_log_files_in_group:
Variables to adjust:
    query_cache_size (=0)
    query_cache_type (=0)
    query_cache_size (> 100M)
    join_buffer_size (> 256.0K, or always use indexes with joins)
    thread_pool_size between 16 and 36 for InnoDB usage
    innodb_log_file_size should be (=512M) if possible, so InnoDB total log files size equals to 25% of buffer pool size.
    innodb_buffer_pool_instances(=4)

Below are the settings currently in my config file.
[mysqld]

datadir=/var/lib/mysql
socket=/chroot/tmp/mysql.sock

userstat=1

ft_min_word_len=3

max_connections=100 # MAX CURRENT X 5
max_connect_errors=25
connect_timeout=10
interactive_timeout=20
wait_timeout=50
delayed_insert_timeout=10
#join_buffer_size=1M

max_allowed_packet=16M

myisam_sort_buffer_size=1M
#sort_buffer_size=1M

#read_buffer_size=1M
#read_rnd_buffer_size=2M

thread_cache_size=100  # from 192 MySQL v 8 recommends CAP of 100 to avoid overload
thread_concurrency=4

query_cache_size=100M # from 256M
#query_cache_limit=32M #remove to allow default of 1M rather than 32M
query_cache_type=1
query_cache_min_res_unit = 512  # from 4K to conserve qcache RAM used per RESULT

tmp_table_size=80M # from 512M
max_heap_table_size=80M # from 512M
max_tmp_tables=10
slow_query_log=1
long_query_time=10
slow-query-log-file  = /var/lib/mysql/mysql-slow.log
table_open_cache = 10000  # 10000 from 2000 to support the 28,000 opened by instance

innodb-file-per-table=1

character-set-server=utf8
collation-server=utf8_general_ci

# Tweaking below
# 256M
innodb_buffer_pool_size = 4G  # to match RAM reported by MySQLTuner
# 512 MB
key_buffer_size = 256M  # from 512M used only my MyISAM
# 16MB
bulk_insert_buffer_size = 16M
innodb_thread_concurrency = 4
innodb_autoinc_lock_mode = 0
skip-external-locking
# Double write off :)
innodb_doublewrite = true
low_priority_updates = 1
#innodb_checksums = false
innodb_support_xa = false
max_write_lock_count = 10
innodb_flush_log_at_trx_commit = 2
innodb_max_dirty_pages_pct = 40
innodb_io_capacity = 400
innodb_write_io_threads = 4
innodb_read_io_threads = 4
innodb_adaptive_flushing = 1
innodb_flush_method = O_DIRECT
innodb_log_file_size=1G
innodb_print_all_deadlocks = 1 # to error log, if you ever have one, you will WISH you had the details.
innodb_buffer_pool_dump_at_shutdown=1 # from OFF to allow quick warmup
innodb_buffer_pool_load_at_startup=1 #from OFF to allow warmed buffer_pool
#skip-name-resolve=1
#log_error_verbosity=3
log_warnings = 2 # to record Aborted Connections in error.log

A: Your my.cnf includes 4 lines that should be removed, they are
sort_buffer_size
read_buffer_size
read_rnd_buffer_size
join_buffer_size
these are all per connection RAM requirements and are driving your RAM footprint much higher than necessary. Let the DEFAULTS work for you to improve response time with room to breathe in RAM.
Consider adjusting the following in your my.cnf, please
key_buffer_size = 512M  # from 1G because 200M is used now
innodb_buffer_pool_size = 4G  # to match RAM reported by MySQLTuner
max_connections = 100  # from 500, until more than 8 are used
thread_cache_size = 100  # from 192 MySQL v 8 recommends CAP of 100 to avoid overload
query_cache_limit     remove to allow default of 1M rather than 32M
query_cache_min_res_unit = 512  # from 4K to conserve qcache RAM used per RESULT
table_open_cache = 10000  # from 2000 to support the 28,000 opened by instance

After the above items have been configured, shutdown/restart have been completed and you have 7 (or more) consecutive days of uptime, please refresh your my.cnf and MySQLTuner report, THEN
for another detailed analysis, add/refresh to OriginalPost the following,
SHOW GLOBAL STATUS;
SHOW GLOBAL VARIABLES;
SHOW ENGINE INNODB STATUS;
for up to five specific additional cfg recommendations, one per day to be applied, monitor.

A: query_cache_size=256M  -->  50M -- A large size can actually slow down due to purging
query_cache_type=1  -- Do you actually find it useful?  Provide SHOW GLOBAL STATUS LIKE "Qc%";

tmp_table_size=512M  --> No mo than 1% of RAM; else could lead to swapping
max_heap_table_size=512M  --> Ditto

slow_query_log=1
long_query_time=1  -- Good.  But only 18 slow queries?

thread_cache_size = 100  -- Wasting RAM since you haven't seen more than 9.

table_open_cache = 10000  -- OK if you need it.  But do you really have thousands of tables?

innodb_buffer_pool_size = 4G  -- Good (for 8G of RAM)
key_buffer_size = 512M  -- Too high if not using MyISAM

innodb_flush_log_at_trx_comm -- mispelled

innodb_max_dirty_pages_pct = 40  -- this low a setting probably leads to more I/O

[!!] Joins performed without indexes: 1453  -- Let's see some
[!!] Temporary tables created on disk: 29% (29K on disk / 98K total)  -- Let's see some

Notes:

*

*You cannot "tune your way out of performance problems".  Some of my suggestions above will help some.

*Slow queries must be investigated.

*Move from MyISAM to InnoDB wherever possible.

*The Query Cache, in most production systems should be turned off.

*Is Magento on the same server?  How much RAM is it using?  All the advice given here assumes you have 8GB of RAM available to MySQL.  If you have less, then several settings need to be lowered.

*For more tuning analysis, see here.  That blog includes a couple of suggestions around the space limitation in this forum.  It also suggests what to do with the Slowlog.

*You mentioned "stability", yet you are using MyISAM, and have turned off the double-write buffer and set innodb_flush_log_at_trx_commit a setting for performance, not data integrity.
Deeper dive
A few more things showed up:
Observations:
Version: 5.6.36-82.1-log
7.7 GB of RAM
Uptime = 9d 23:50:34
You are not running on Windows.
Running 64-bit version
It appears that you are running both MyISAM and InnoDB.

The More Important Issues
tmp_table_size and max_heap_table_size are dangerously high at 512M.  If a number of complex queries were to be run simultaneously, you could run out of RAM, leading to a significant slowdown.  Recommend no more than 1% (80M) of RAM for each.  (max_tmp_tables is unused.)
query_cache_size leads to degraded performance when it is too big.  Lower to 50M.
There are a lot of table scans; set long_query_time to 1 and turn on the SlowLog.  Later, discover the worst queries and work on them.
Turning off the double-write buffer is a small invitation to corruption of the database.
It seems that neither InnoDB, nor MyISAM, tables are so big as to need increasing their buffers.  In fact they could be lowered if RAM is needed elsewhere.
For many reasons, MyISAM tables should be converted to InnoDB.
Conversion from MyISAM to InnoDB
table_open_cache may as well be lowered to 3000.
innodb_log_file_size is much higher than necessary, but is probably not worth changing.
"Savepoints" are rarely used in MySQL; how are they working for you?
Details and other observations
( (key_buffer_size - 1.2 * Key_blocks_used * 1024) / _ram ) = (512M - 1.2 * 5839 * 1024) / 8267812044.8 = 6.4% -- Percent of RAM wasted in key_buffer.
-- Decrease key_buffer_size.
( innodb_buffer_pool_size / _ram ) = 4096M / 8267812044.8 = 51.9% -- % of RAM used for InnoDB buffer_pool
( table_open_cache ) = 10,000 -- Number of table descriptors to cache
-- Several hundred is usually good.
( Innodb_buffer_pool_pages_free * 16384 / innodb_buffer_pool_size ) = 216,083 * 16384 / 4096M = 82.4% -- buffer pool free
-- buffer_pool_size is bigger than working set; could decrease it
( innodb_max_dirty_pages_pct ) = 40 -- When buffer_pool starts flushing to disk
-- Are you experimenting?
( Innodb_buffer_pool_pages_free / Innodb_buffer_pool_pages_total ) = 216,083 / 262136 = 82.4% -- Pct of buffer_pool currently not in use
-- innodb_buffer_pool_size to bigger than necessary?
( Innodb_buffer_pool_bytes_data / innodb_buffer_pool_size ) = 735,395,840 / 4096M = 17.1% -- Percent of buffer pool taken up by data
-- A small percent may indicate that the buffer_pool is unnecessarily big.
( Innodb_dblwr_pages_written/Innodb_pages_written ) = 0/1260380 = 0 -- Seems like these values should be equal?
( innodb_doublewrite ) = OFF -- Extra I/O, but extra safety in crash.
-- OFF is OK for FusionIO, Galera, Slaves
( Innodb_os_log_written / (Uptime / 3600) / innodb_log_files_in_group / innodb_log_file_size ) = 1,246,395,904 / (863434 / 3600) / 2 / 1024M = 0.00242 -- Ratio (see minutes)
( Uptime / 60 * innodb_log_file_size / Innodb_os_log_written ) = 863,434 / 60 * 1024M / 1246395904 = 12,397 -- Minutes between InnoDB log rotations Beginning with 5.6.8, this can be changed dynamically; be sure to also change my.cnf.
-- (The recommendation of 60 minutes between rotations is somewhat arbitrary.) Adjust innodb_log_file_size. (Cannot change in AWS.)
( Innodb_rows_deleted / Innodb_rows_inserted ) = 1,249,027 / 1276124 = 0.979 -- Churn
-- "Don't queue it, just do it." (If MySQL is being used as a queue.)
( expand_fast_index_creation ) = OFF -- ALTER and OPTIMIZE may be greatly sped up by using ON.
-- Probably better to be ON.
( innodb_thread_concurrency ) = 4 -- 0 = Let InnoDB decide the best for concurrency_tickets.
-- Set to 0
( innodb_print_all_deadlocks ) = OFF -- Whether to log all Deadlocks.
-- If you are plagued with Deadlocks, turn this on. Caution: If you have lots of deadlocks, this may write a lot to disk.
( min( tmp_table_size, max_heap_table_size ) / _ram ) = min( 512M, 512M ) / 8267812044.8 = 6.5% -- Percent of RAM to allocate when needing MEMORY table (per table), or temp table inside a SELECT (per temp table per some SELECTs). Too high may lead to swapping.
-- Decrease tmp_table_size and max_heap_table_size to, say, 1% of ram.
( innodb_buffer_pool_populate ) = OFF = 0 -- NUMA control
( local_infile ) = ON
-- local_infile = ON is a potential security issue
( Key_blocks_used * 1024 / key_buffer_size ) = 5,839 * 1024 / 512M = 1.1% -- Percent of key_buffer used . High-water-mark.
-- Lower key_buffer_size to avoid unnecessary memory usage.
( Key_writes / Key_write_requests ) = 131,634 / 155998 = 84.4% -- key_buffer effectiveness for writes
-- If you have enough RAM, it would be worthwhile to increase key_buffer_size.
( query_cache_size ) = 256M -- Size of QC
-- Too small = not of much use. Too large = too much overhead. Recommend either 0 or no more than 50M.
( (query_cache_size - Qcache_free_memory) / Qcache_queries_in_cache / query_alloc_block_size ) = (256M - 63512256) / 115486 / 8192 = 0.217 -- query_alloc_block_size vs formula
-- Adjust query_alloc_block_size
( Created_tmp_disk_tables / (Created_tmp_disk_tables + Created_tmp_tables) ) = 148,564 / (148564 + 549507) = 21.3% -- Percent of temp tables that spilled to disk
-- maybe increase tmp_table_size and max_heap_table_size; avoid blobs, etc.
( tmp_table_size ) = 512M -- Limit on size of MEMORY temp tables used to support a SELECT
-- Decrease tmp_table_size to avoid running out of RAM. Perhaps no more than 64M.
( (Com_insert + Com_update + Com_delete + Com_replace) / Com_commit ) = (257684 + 342113 + 118532 + 235) / 389763 = 1.84 -- Statements per Commit (assuming all InnoDB)
-- Low: Might help to group queries together in transactions; High: long transactions strain various things.
( Select_scan / Com_select ) = 527,912 / 1359892 = 38.8% -- % of selects doing full table scan. (May be fooled by Stored Routines.)
-- Add indexes / optimize queries
( binlog_error_action ) = IGNORE_ERROR -- What to do if the binlog cannot be written.
-- IGNORE_ERROR is the default for backwards compatibility, but ABORT_SERVER is recommended.
( binlog_format ) = STATEMENT -- STATEMENT/ROW/MIXED. ROW is preferred; it may become the default.
( expire_logs_days ) = 0 -- How soon to automatically purge binlog (after this many days)
-- Too large (or zero) = consumes disk space; too small = need to respond quickly to network/machine crash.
(Not relevant if log_bin = OFF)
( innodb_autoinc_lock_mode ) = 0 -- Galera: desires 2 -- 2 = "interleaved"; 1 = "consecutive" is typical; 0 = "traditional".
( back_log / max_connections ) = 70 / 100 = 70.0%
( thread_cache_size ) = 100 -- How many extra processes to keep around (Not relevant when using thread pooling) (Autosized as of 5.6.8; based on max_connections)
-- 0 is good for Windows
0 is inefficient for non-Windows; 10 is probably fine
( thread_cache_size / max_connections ) = 100 / 100 = 100.0%
-- (0 for Windows)
(The following "abnormal" values are not necessarily "bad", merely uncommon.)
Abnormally small:
Innodb_dblwr_pages_written = 0
Threads_connected = 0.0042 /HR
delayed_insert_timeout = 10
interactive_timeout = 20
myisam_sort_buffer_size = 1MB
query_cache_min_res_unit = 512
thread_concurrency = 4
wait_timeout = 50

Abnormally large:
Com_drop_user = 0.0042 /HR
Com_empty_query = 15 /HR
Com_release_savepoint = 0.19 /HR
Com_rollback_to_savepoint = 15 /HR
Com_savepoint = 0.19 /HR
Com_show_create_func = 0.0083 /HR
Com_show_processlist = 0.17 /sec
Com_show_status = 0.17 /sec
Com_stmt_send_long_data = 1.9 /HR
Handler_savepoint = 0.19 /HR
Handler_savepoint_rollback = 15 /HR
Open_table_definitions = 4,172
Open_tables = 7,852
Qcache_free_blocks = 49,773
Qcache_total_blocks = 287,236
max_heap_table_size = 512MB

Abnormal strings:
ft_min_word_len = 3
innodb_force_load_corrupted = OFF
innodb_support_xa = OFF
low_priority_updates = ON
optimizer_trace = enabled=off,one_line=off
optimizer_trace_features = greedy_search=on, range_optimizer=on, dynamic_range=on, repeated_subselect=on
secure_file_priv = /var/lib/mysql-files/
sha256_password_private_key_path = private_key.pem
sha256_password_public_key_path = public_key.pem
slave_rows_search_algorithms = TABLE_SCAN,INDEX_SCAN
sql_slave_skip_counter = 0
userstat = ON

A: my.cnf things to do in [mysqld] section:
thread_concurrency=30 # from 4 to support more concurrent processing
innodb_io_capacity_max=6000 # from 2000 (default)
innodb_io_capacity=1200 # from 400 per second
innodb_thread_concurrency=15 # from 4
innodb_write_io_threads=8 # from 4
key_buffer_size=16M # from 256M less than 5M used in 13 days
expire_logs_days=5 # from 0 to allow research more days
innodb_purge_threads=2 # from 1 to reduce DEL delays
innodb_read_ahead_threshold=8 # from 56 to enable read ahead quicker
innodb_stats_sample_pages=32 # from 8 for more accurate cardinality data
low_priority_updates=OFF # from ON to minimize exposure to power fails
max_join_size=1000000000 # from huge number to 1 Billion row limit
max_seeks_for_key=32 # from huge number to reasonable limit before scan
sql_select_limit=1000000000 # from huge number to 1 Billion row limit
query_prealloc_size=32768 # from 8192 to avoid RAM allocation all day for large queries
lock_wait_timeout=300 # from 31536000 secs (1 year) until replication needed

One minute of your general log from a busy time of day would allow analysis to suggest code changes to get more than 1 of each 21 queries to be stored in Query Cache.
5 pages of your slow query log would reveal many details leading to possible index creation and/or code changes to reduce processing time.  MySQLTuner is whining about joins without indexes.  And they do take much longer than when properly indexed on both sides of the = variables.
Posting from you Linux system  ulimit -a would reveal all limits to help with getting more tables, table definitions and open file capacity available.
Continued success with your installation.  Please consider upvote and/or acceptance for ideas that help your team.

A: This script will allow 10 second elapsed time reporting of global status values USED with calculated RPS and Rate per Minute for each item.
# filename globalstatusage10sec.sql   Last Update 201801310853 whauck
# 2015-01-23 from schlomi's web site
# http://code.openark.org/blog/mysql/mysql-global-status-difference-using-single-query
# shortened AS labels for columns to be effective
SELECT STRAIGHT_JOIN
   LOWER(gs0.VARIABLE_NAME) AS variable_name,
   gs0.VARIABLE_VALUE AS "Begin",
   gs1.VARIABLE_VALUE AS "End",
   (gs1.VARIABLE_VALUE - gs0.VARIABLE_VALUE) AS diff,
   (gs1.VARIABLE_VALUE - gs0.VARIABLE_VALUE) / 10 AS psec,
   (gs1.VARIABLE_VALUE - gs0.VARIABLE_VALUE) * 60 / 10 AS
pminute
FROM
   (
     SELECT
       VARIABLE_NAME,
       VARIABLE_VALUE
     FROM
       INFORMATION_SCHEMA.GLOBAL_STATUS
     UNION ALL
     SELECT
       '',
       SLEEP(10)
     FROM DUAL
   ) AS gs0
   JOIN (
     SELECT
       VARIABLE_NAME,
       VARIABLE_VALUE
     FROM
       INFORMATION_SCHEMA.GLOBAL_STATUS
   ) gs1 USING (VARIABLE_NAME)
WHERE
   gs1.VARIABLE_VALUE != gs0.VARIABLE_VALUE LIMIT 0,800
;


text:
Q: How can I remove my Activity setContentView from the Back Stack? There are a hundred questions regarding this on Stackoverflow, but none of them are about my specific issue.
I'm starting my Activity with this code as a static function within my Activity class:
fun startForResult(activity: Activity, code: Int) {
    val intent = Intent(activity, MyActivity::class.java)
    activity.startActivityForResult(intent, code)
    activity.overridePendingTransition(R.anim.none, R.anim.none)
}

When MyActivity starts in runs onCreate and the setContentView(R.layout.activity) within it.  This seems to go on the Back Stack. The Activity has only a FrameLayout which is full screen and is a placeholder/frame for the fragments I want to load. My Activity is very simple, like a wizard with 3 fragments/screens, all full screen. Once my activity OnCreate completes my presenter loads the first Fragment, FragmentA using code like this:
supportFragmentManager
    .beginTransaction()
    .replace(R.id.myContentFrame, FragmentA.newInstance())
    .addToBackStack(null)
    .commit()

This also goes on the back stack. The user presses the next button and my presenter runs this code:
supportFragmentManager
    .beginTransaction()
    .replace(R.id.myContentFrame, FragmentB.newInstance())
    .addToBackStack(null)
    .commit()

When the user presses the back button on FragmentB is takes the user back to FragmentA, which is fine. My problem occurs when they press the back button on FragmentA it takes them to a clear screen, which is apparently this setContentView(R.layout.activity) event, it's been added to the back stack and I'm going back to it. So I'd like to have that event, the start of the Activity, and its invisible layout NOT added to the back stack. When a user is on FragmentA and presses the back button I'd like the Activity to just finish.
I've tried a bunch of different things to get rid of this setContentView(R.layout.activity) transaction in my back stack and nothing has worked. I assume there is an easy solution to this, like setting a FLAG, but it has eluded me. In the past I've overridden the OnBackPress method, and I assume that will work, but I'm still curious if there's an easier way to pop that first (Activity) item off my back stack without requiring me to override OnBackPressed.
What am I missing?

A: I think you no need add to back stack with fragment A. When in fragment A user back press Activity will be finish!


text:
Q: Dual subgradient method - can we solve approximation of dual? Consider the problem to minimize $f(x)$ under the constraints $x \leq b$ and $x \in X$.
I Lagrange relax the constraint $x \leq b$ getting
$L(x,u) = f(x) + u^t(x-b)$.
When using the subgradient method, we set $u^0$ to some arbitrary value and treat it as fixed in each iteration, find $q(u^k) = \inf_{x\in X}L(x,u^k)$ and then take a step in a subgradient direction.
Suppose calculating $q(u^k) = \inf_{x\in X}L(x,u^k)$ is still hard in some sense. Can we solve an approximative problem instead? Will it still converge to a dual optimum? Under what conditions? Is there some way to bound the error?
Answers or references both appreciated.

A: In general, this is a very difficult problem.
If X is a conic constraint, potential reduction methods come closest to what you are saying. That is not an approximate problem but figures out a candidate function to minimize.
If X is some complicated inequality set involving several funky functions , 9/10 chances are it cannot be done EVEN IF IT IS CONVEX unless you are able to devise some nice embedding (based on my experience at least)

A: In general, you need to be able to solve the subproblem to $\epsilon$ optimality in order for approximate subgradients to converge. In the specific case the poster (me) was interested in, it would not have been possible. For convergence, you need to be able to guarantee the iterations brings you geometrically closer to the optimal solution set. There is no way to verify this is the case here since I wanted to approximately solve an NP-problem in each iteration.


text:
Q: jquery fancybox 1.3.0 iframe I am have some difficulty getting an iframe to load in an overlay. My user level is competent html 5 css3 xhtml and can read php and JavaScript.
I was able to get youtube video to play in lightbox_frame and iframe. but had no joy with getting an html page into an iframe in an overlay.
I was reading on fancyapps and what the example was is:
Iframe
so adapted below.

A: Rather than defining an iframe, you can mention type: iframe to get the contents as iframe in fancybox.
Open page

and in script you can mention:

This will show the contents of the page as iframe in overlay.


text:
Q: Why does this call to update the email subject return an error? I'm using the DocuSign C# SDK for the REST API.  Calling the EnvelopesApi.Update() method to change the email subject on an envelope.
My testers are reporting an occasional error:
Error calling Update: { "errorCode": "INVALID_REQUEST_PARAMETER", "message": "The request contained at least one invalid parameter. Value for 'status' must be 'created', 'sent' or 'voided'." }
I'm reusing the current values from the GetEnvelope call, so my guess is the status isn't in the proper state, but they report that the envelope has not been signed yet.  Should I set the status to 'sent'? I ONLY want to update the email subject and message.  Is it possibly because I'm nulling the purge state?  Is this the wrong way to update the email subject and message?
        EnvelopesApi envelopesApi = new EnvelopesApi();

        Envelope envelope = envelopesApi.GetEnvelope(AccountId, envelopeId);
        envelope.EmailSubject = emailSubject;
        envelope.EmailBlurb = emailMessage;
        envelope.PurgeState = null;

        var updateOptions = new EnvelopesApi.UpdateOptions { resendEnvelope = "true" };

        var updateSummary = envelopesApi.Update(AccountId, envelopeId, envelope, updateOptions);

A: When the envelope's status changes to "delivered" (after all recipient's have viewed the document), the call to .update fails.  It is as the error says, the status must be 'sent', 'created', or 'voided'.  So you must update the status along with the email and subject.
I can't say if this is appropriate for everyone's use-case but it seems to make sense.


text:
Q: How to fire an Event via Fuel SDK I want to implement this procedure via Java fuelsdk
https://code.exacttarget.com/marketing-automation/journey-builder/events/how-to-fire-an-event
    ETClient client = new ETClient();
    ETRestConnection restConnection = client.getRESTConnection();

    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("Authorization", "Bearer " + client.getAccessToken());
    jsonObject.addProperty("EventDefinitionKey", "XXXXXX-xxxxxxxx-xxxxx-xxxxx");

    //Not able to create TreeMap
    //"Data": {
    //      "accountNumber":"123456",
    //      "patronName":"John Smith" }
    }

    String result = restConnection.post("/interaction-experimental/v1/events", jsonObject);
    System.out.println("Result:::" + result);

UPDATED
Finally, I figured out how to do that, but after successfull execution, nothing happens.
2014-06-16T19:34:11.815+0200 main com.exacttarget.fuelsdk.ETRestConnection DEBUG: 201 Created
2014-06-16T19:34:11.817+0200 main com.exacttarget.fuelsdk.ETRestConnection DEBUG: "{\r\n  \"eventInstanceId\": \"88607cad-9b8d-4391-bb88-ca9150d71d0d\"\r\n}"

Thanks

A: Looking at the payload you're sending, it appears you're missing the ContactKey or ContactID property. Knowing which one of these to use depends upon how the Interaction within Journey Builder is configured.
How has your Trigger been defined in the Trigger Administration View in Journey Builder? The preferred method is to use Contact Key as the mapping to the EventDataSource's Sendable Field.
It appears you're receiving an EventInstanceId as a response from the request. When you say "nothing happens", could you provide some more information please?
- Is the row added to the Event Data Source associated with the Trigger for the running Interaction?


text:
Q: How to get Current page Title of Relationship Model in Laravel? i have some fields in my database table, and i want to display title,description and keywords according to every page, Please let me know how i can display this. My database fields name are metatitle,metadesc,keyword
Here are my Controller code where i am displaying the property list...
    public function listtype($slug){
    $prtype= Listing::whereHas('proType',function($q) use($slug){
        $q->where('slug','like','%'.$slug.'%');
    })->paginate(50);
    return view('property-type',compact('prtype','title'));
}

A: You can do the following way:
 public function listtype($slug){
    $prtype= Listing::whereHas('proType',function($q) use($slug){
        $q->where('slug','like','%'.$slug.'%');
    })->with('proType')->paginate(50);
    dd($prtype); /** for checking **/
    return view('property-type',compact('prtype', $prtype));
 }


text:
Q: Limit of characters in string I have the textbox that takes some string. This string could be very long. I want to limit displayed text (for example to 10 characters) and attach 3 dots like:
if text box takes value "To be, or not to be, that is the question:" it display only "To be, or..."
Or
if text box takes value "To be" it display "To be"
            Html.DevExpress().TextBox(
                    tbsettings =>
                    {
                        tbsettings.Name = "tbNameEdit";;
                        tbsettings.Width = 400;
                        tbsettings.Properties.DisplayFormatString=???
                    }).Bind(DataBinder.Eval(product, "ReportName")).GetHtml();

A: You should use a Label control to display the data. Set AutoSize to false and AutoEllipsis to true. There are good reasons why a TextBox does not have this functionality, among which:

*

*where are you going to store the truncated data?

*if the user selects the text to edit or even copy, how do you handle that?

If you counter-argument is that the TextBox is read-only, then that is only more reason to re-think the control you are using for this.

A: Try this:
string displayValue = !string.IsNullOrWhiteSpace(textBox.Text) && textBox.Text.Length > 10
    ? textBox.Text.Left(10) + "..."
    : textBox.Text;

In an extension method:
public static string Ellipsis(this string str, int TotalWidth, string Ellipsis = "...")
{
    string output = "";

    if (!string.IsNullOrWhiteSpace(str) && str.Length > TotalWidth)
    {
        output = output.Left(TotalWidth) + Ellipsis;
    }

    return output;
}

Using it would be:
string displayValue = textBox.Text.Ellipsis(10);

A: If you need to use a regex, you can do this:
Regex.Replace(input, "(?<=^.{10}).*", "...");

This replaces any text after the tenth character with three dots.
The (?<=expr) is a lookbehind. It means that expr must be matched (but not consumed) in order for the rest of the match to be successful. If there are fewer than ten characters in the input, no replacement is performed.
Here is a demo on ideone.

A: Something like this?
static void SetTextWithLimit(this TextBox textBox, string text, int limit)
{
    if (text.Length > limit)
    {
        text = text.SubString(0, limit) + "...";
    }
    textBox.Text = text;
}

Show what you have tried and where you are stuck.

A: string textToDisplay = (inputText.Length <= 10)
          ? inputText
          : inputText.Substring(0, 10) + "...";

A: You don't need to use regex
string s = "To be, or not to be, that is the question:";
s = s.Length > 10 ? s.Remove(10, s.Length - 10) + "..." : s;

A: string maxStringLength = 10;
string displayStr = "A very very long string that you want to shorten";
if (displayStr.Length >= maxStringLength) {
    displayStr = displayStr.Substring(0, maxStringLength) + " ...";
}

//displayStr = "A very very long str ..."


text:
Q: A set $U$ is open iff it is union of open balls Let $(X,d)$ be a metric space. Consider the collection $\mathcal{T} = \{ U \subset X: \forall u \in U, \exists r>0 \; \; , B_r(u) \subset U \}$. We showed that $(X, \mathcal{T} )$ is a topological space. $\mathbf{Homework }:$ Please show that $U \in \mathcal{T} \iff U = \bigcup_{u \in U} B_r(u) $
Attempt:
Suppose $U$ is open. We want to show that $U = \bigcup_{u \in U} B_r(u)$. Since $U$ is open, for all $u \in U$, we can find some $r>0$ such that $u \in B_r(u) \subset \bigcup_{u \in U} B_r(u)$. So that $U \subset \bigcup_{u \in U} B_r(u)$. Now, if $x \in \bigcup_{u \in U} B_r(u)$, then we can find some $u' \in U$ such that $x \in B_r(u) $. And so $x \in U$. Therefore, we have shown that $U = \bigcup_{u \in U} B_r(u)$.
Conversely, Suppose $U = \bigcup_{u \in U} B_r(u)$. We want to show that $U$ is open. Pick some $u \in U$. So there is some $u' \in U$ such that $u \in B_r(u') \subset U$. So $U$ is open.
Is this a correct solution? thanks


text:
Q: if / whether it rains or not
It's not important if it rains or not.

Does this sentence sound odd to you because of using 'if' instead of using 'whether'?

A: It's not important if it rains or not.
There's nithing wrong with the sentence; it's grammatical.
You can use either whether or if with "or not" in end position, with no difference in meaning. However, the use of whether is far more common and idiomatic in the sentence.
You can also use "or not" immmediately after whether as follows:
It's not important whether or not it rains.


text:
Q: Overriding the paint() method I've got a beginner question here that I was hoping someone with some Java experience could help me with. Currently taking an intro to OOP course focused on Java. My instructor is currently covering awt and swing, specifically the need to override the paint method so that graphics are redrawn when a window is resized, etc. I like to do as much outside reading as possible, and my concern is that the examples that my professor gives involve things that I've read are not best practices. To get to the point...
I understand that it's necessary to override the paint method, but I don't know the best way to do so. My professor's examples are all similar to the following:
class Example extends JFrame {
  public void paint(Graphics g) {
    super.paint(g);
    g.drawString("Blah, blah");
  }

  public static void main(String[] args) {
    Example a = new Example();
    a.setDefaultCl...
    \\Etc...
  }
}

This bothers me because it doesn't seem right to include everything for the GUI in the same class as my main method. Also, I read on a different thread here that you shouldn't extend JFrame, but there wasn't an explanation as to why. My solution was to create a class handling the gui and instantiate JFrame within the constructor. However, unless I'm mistaken, doing so won't let me override the paint method. I feel compelled  to extend JFrame to allow me to override paint, but again I read that was the wrong thing to do.
Any help would be sincerely appreciated, I know I can just model my code off of what he has but I really want to understand this and know the best way to handle it.

A:
I understand that it's necessary to override the paint method

No you should not override the paint() method.
You should override the paintComponent() method of a JPanel and then add the panel to the frame.
Read the section from the Swing tutorial on Custom Painting for more information and working examples.
The tutorial will also show you how to better structure your code so that the GUI is created on the Event Dispatch Thread (EDT). The tutorial also has a section on Concurrency which will explain why this is important.


text:
Q: Why won't the img show? what is wrong with "skrivut" `

What im trying to do here is making a kidnaplettergenerator. Its supposed to convert the text in input, to letters, that i've saved in my array, bokstaver.
The problem that i'm getting is that, the img wont show, help would be appriciated. :)

A: document.getElementById("skrivut").innerHTMl

You need to write innerHTML, little typo there ;)

A: for (var i = 0; i < input.length; i++) {
        for (var b = 0; b < bokstav.length; b++) {
            if (input[i] === bokstav[b]) {
                document.getElementById("skrivut").innerHTMl += "";
                console.log("");
                //add break
                break;
            }
        }
    }


text:
Q: When I change the pictures after entering the site, the pictures are uploaded late https://awenarts.com/new-site/
When you enter the connection for the first time, you change the pictures using the mouse wheel. but at first the pictures are loading late
but it's fine the next time you come to the same picture. I wonder if we need to throw the pictures into the browser's cache before the page is loaded? I will be glad if you help
HTML code:

JS code:

var parallax = document.querySelector('.parallax');
var iLayer = document.querySelector('.image-layer');
var lShadow = document.querySelector('.layer-shadow');
var pTitle = document.querySelector('.parallax-title h1');
var iNo = document.querySelector('.image-no h5');
var dLength = pData.length;
var dNo = 0;

sParallax();
parallax.addEventListener('wheel', throttle(() => {

    if (event.deltaY < 0) {
        dNo++;
        if(dNo >= dLength) {
            dNo = 0;
        }
        pTitle.classList.add('slide-text-down');
        sParallax();
    }
    else if (event.deltaY > 0) {
        dNo--;
        if(dNo < 0) {
            dNo = dLength - 1;
        }
        pTitle.classList.add('slide-text-up');
        sParallax();
    }
},2000));

function sParallax() {
    iNo.innerHTML = "0" + (dNo+1) + " - " + "0" + dLength;
    iLayer.classList.add('filter-off');
    lShadow.classList.add('shadow-off');

    setTimeout(function(){
        parallax.style.backgroundImage = 'url('+ pData[ dNo ].url +')';
        iLayer.classList.remove('filter-off');
        lShadow.classList.remove('shadow-off');
        pTitle.classList.remove('slide-text-up');
        pTitle.classList.remove('slide-text-down');
        pTitle.innerHTML =  pData[dNo].title;
    },800)
}

A: The issue is that the image is not downloaded the first time until the class is changed to the appropriate value.
To preload the images, store them in a local array as in the following answer:
Preloading images with JavaScript
This will ensure that all images are in the cache before being needed.


text:
Q: Detecting signed dots on piece of paper with c# / php / anylanguage A worker has a printed piece of paper (standardized from template) with options (say a checkbox). He checks stuff, sign dots - this ok, this is not, do this, do that based on that report.
I want to create a program (probably with c#) that will read the signed dots from scanned paper and order stuff based on data it will get. Right now another worker is doing this.
Is there a way in any programing language?
If not maybe there is a free program that already is doing this, produce output if file and programing go from there. (I found freemark for example but it's not free and far from perfect from what I read)
I know this question is a little broad - sorry for this.

A: I've recently tackled a similar situation, I too searched for ready made software but ended up solving it programatically
The idea is to use some OCR tool (like tesseract) to identify the position of each checkbox, by their labels.
Every checkbox should have a label before or after the rectangle/mark, use the OCR to identify it's position, using the label position you can easily crop out just the rectangle with the check-mark
Once you have the checkbox's rectangle isolated you can choose an algorithm to know if it's checked or not, here's some approaches:

*

*Use some machine learning to recognize a check-mark(X or whatever)

*Calculate the average color of the rectangles, darker checkboxes will have something in them

*Count the number of pixels you have to expand from the center to reach a black pixel, if there's a mark on the checkbox you'll quickly reach a black pixel, if not you'll only reach one when you hit the rectangle. Here you can decide a threshold, like if you have to walk more than 40% of the checkbox, it's probably empty

The same ideas apply for other stuff like radio buttons, the only difference is that they are circular


text:
Q: ORA-06550: line 0, column 0: PLS-00907: cannot load library unit `COLUMN_NAME` (referenced by) So, I got this error message

Started:  9:00:01 AM  Error: 2018-01-26 09:33:53.01     Code: 0xC002F210     Source: Run proc SP_MISSING_FILE_CASE_CLOSURE Execute SQL Task     Description: Executing the query "begin  SP_MISSING_FILE_CASE_CLOSURE;  end;" failed with the following error: "ORA-06550: line 0, column 0:  PLS-00907: cannot load library unit USAGE.SP_MISSING_FILE_CASE_CLOSURE (referenced by )". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.  End Error  DTExec: The package execution returned DTSER_FAILURE (1).  Started:  9:00:01 AM  Finished: 9:33:53 AM  Elapsed:  2031.88 seconds.  Process Exit Code 1.  The step failed.

sometimes, but sometimes my SSIS job runs normally. Can someone provide me with some kind of solution? I cannot see any pattern in it's failure except PROCEDURE which is always the same.
Any help is greatly appreciated.

A: You should try this syntax (add schema)
begin
execute  <schema>.SP_MISSING_FILE_CASE_CLOSURE;
end;


text:
Q: TCP connection with 2 Android devices
I want to make one Android device a server that will make a HotSpot, and when another Android device connects to that HotSpot it could communicate with the server by TCP connection.
Creating the HotSpot and connecting to it works fine, but I can't connect via TCP.
I am trying to connect via IP that I get after connecting to HotSpot with:
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ip = wifiInfo.getIpAddress();

But the server and client waits for socket connection, so maybe this IP is wrong? If it is wrong, how can I receive proper IP to connect via TCP?
Here is the code of the client:
public class LoginActivity extends Activity {

    private static final String AP_NAME = "\"MobileEduPlatform\"";
    private static final String TAG = "LoginActivity";

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

    public void connectToHS(){
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        wifi.disconnect();
        wifi.enableNetwork(configureNetwork(), true);
    }

    public int configureNetwork(){
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiConfiguration config = new WifiConfiguration();
        config.status = WifiConfiguration.Status.ENABLED;
        config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        config.SSID = AP_NAME;
        int id =  wifi.addNetwork(config);
        wifi.saveConfiguration();
        wifi.enableNetwork(id, true);
        return id;
    }

    public void onClick2(View view){
        String otherIP = "";
        String ip = getIpAddr();
        new TCPClient(this).execute(ip);
    }

    public String getIpAddr() {
           WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
           WifiInfo wifiInfo = wifiManager.getConnectionInfo();
           int ip = wifiInfo.getIpAddress();

           String ipString = String.format(
            "%d.%d.%d.%d",
           (ip & 0xff),
           (ip >> 8 & 0xff),
           (ip >> 16 & 0xff),
           (ip >> 24 & 0xff));

           return ipString;
    }
}

public class TCPClient extends AsyncTask<String, Void, Boolean> {
    private int TCP_SERVER_PORT = 55000;

    @Override
    protected Boolean doInBackground(String... arg0) {
        runTcpClient(arg0[0]);
        return true;
    }
    private void runTcpClient(String ip) {

        try {
            Socket s = new Socket(ip, TCP_SERVER_PORT);
            BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

            String outMsg = "TCP connecting to " + TCP_SERVER_PORT + System.getProperty("line.separator");
            out.write(outMsg);
            out.flush();

            String inMsg = in.readLine() + System.getProperty("line.separator");
            s.close();

        } catch (UnknownHostException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        }
    }
}

And the server:
public class WifiAPActivity extends Activity {
    private boolean wasAPEnabled = false;
    private static WifiAP wifiAp;
    private WifiManager wifi;
    private static Button btnWifiToggle;

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

        btnWifiToggle = (Button) findViewById(R.id.btnWifiToggle);
        wifiAp = new WifiAP();
        wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

        btnWifiToggle.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                wifiAp.toggleWiFiAP(wifi, WifiAPActivity.this);
            }
        });

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }

    public void onClick(View view){
        new TCPServer2(this).execute("");
    }
}

public class TCPServer2 extends AsyncTask<String, Void, Boolean>{
    private Exception exception;
    private int TCP_SERVER_PORT = 55000;

    protected Boolean doInBackground(String... urls) {
        runTcpServer();
        return true;
    }

    private void runTcpServer() {
        ServerSocket ss = null;

        try {
            ss = new ServerSocket(TCP_SERVER_PORT);
            Socket s = ss.accept();

            BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            String incomingMsg = in.readLine() + System.getProperty("line.separator");

            String outgoingMsg = "goodbye from port " + TCP_SERVER_PORT + System.getProperty("line.separator");
            out.write(outgoingMsg);
            out.flush();

            s.close();

        } catch (InterruptedIOException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


text:
Q: Clean URLS/.htaccess <IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteBase /
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteRule ^(.*)$ index.php?q=$1 [L,QSA

Looking for feedback
Goal: I am trying to enable "Clean URLs" on a Drupal 7 site (such that example.com/?q=user resolves to example.com/user).
I've just spent way too long pouring through official Drupal docs and comments, to no avail, so any suggestions are greatly appreciated!
I have checked the box "Enable Clean URLs" in Drupal (/admin/config/search/clean-urls) and got the all-clear that the configuration options were saved. So now I am actually able to go to example.com/user and it does indeed display the same content as example.com/?q=user. What I want, however, is for example.com/?q=user to be rewritten in the URI as example.com/user.
The relevant .htaccess code is shown above, and my Apache conf appears to be properly configured.

A: Clean urls do indeed work but I kept getting errors until I found this
This saved my sanity:

*

*disable Overlay module

*go to Clean URLS

*change URL from: /?q=admin/config/search/clean-urls

*to: /admin/config/search/clean-urls

*Then the Check box should appear

A: I was searching for this issue, the solution that work for me was that:

*

*Left click on the wamp server icon and go to the apache.

*Here sub menu will be opened, go to the apache modules and enable the rewrite_module.

*now restart wamp server and then check your site.

*Enable clean url will now be active.

A: there should be a closing bracket on your last line "]". Perhaps this is the source of your frustration?


text:
Q: How to use StopWatch multiple times in C#? I have  short code that performs different operations and I want to measure the time that takes to perform each. I read here about Stopwatch class, and wanted to optimize my time measurements.
my functions calls 5 other functions and I want to measure each without declaring :
stopwatch sw1 = new stopwatch();
stopwatch sw2 = new stopwatch();
etc..

my function looks like that:
public bool func()
{
 ....
 func1()
 func2()
 ....
 ....
 func5()
}

is there any way to measure the time using one stopwatch instance?
thanks!!

A: Yes, try this:
    void func1()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();
        func1();
        sw.Stop();
        Console.Write(sw.Elapsed);

        sw.Restart();
        func2();
        sw.Stop();
        Console.Write(sw.Elapsed);
    }

A: Use delegates to pass a method as a parameter to a function.
Here I used Action Delegates as the methods specified does not return a value.
You can modify it accordingly if your method has a return type or parameter by using a Function delegate
    static void Main(string[] args)
    {
        Console.WriteLine("Method 1 Time Elapsed (ms): {0}", TimeMethod(Method1));
        Console.WriteLine("Method 2 Time Elapsed (ms): {0}", TimeMethod(Method2));
    }

    static long TimeMethod(Action methodToTime)
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        methodToTime();
        stopwatch.Stop();
        return stopwatch.ElapsedMilliseconds;
    }

    static void Method1()
    {
        for (int i = 0; i < 100000; i++)
        {
            for (int j = 0; j < 1000; j++)
            {
            }
        }
    }

    static void Method2()
    {
        for (int i = 0; i < 5000; i++)
        {
        }
    }
}

By using this you could pass any method you want.
Hope that helps!

A: You can use this little class:
public class PolyStopwatch
{
    readonly Dictionary<string, long> counters;

    readonly Stopwatch stopwatch;

    string currentLabel;

    public PolyStopwatch()
    {
        stopwatch = new Stopwatch();
        counters = new Dictionary<string, long>();
    }

    public void Start(string label)
    {
        if (currentLabel != null) Stop();

        currentLabel = label;
        if (!counters.ContainsKey(label))
            counters.Add(label, 0);
        stopwatch.Restart();
    }

    public void Stop()
    {
        if (currentLabel == null)
            throw new InvalidOperationException("No counter started");

        stopwatch.Stop();
        counters[currentLabel] += stopwatch.ElapsedMilliseconds;
        currentLabel = null;
    }

    public void Print()
    {
        if (currentLabel != null) Stop();

        long totalTime = counters.Values.Sum();
        foreach (KeyValuePair<string, long> kvp in counters)
            Debug.Print("{0,-40}: {1,8:N0} ms ({2:P})", kvp.Key, kvp.Value, (double) kvp.Value / totalTime);
        Debug.WriteLine(new string('-', 62));
        Debug.Print("{0,-40}: {1,8:N0} ms", "Total time", totalTime);
    }
}

Use it like this:
var ps = new PolyStopwatch();

ps.Start("Method1");
Method1();
ps.Stop();

// other code...

ps.Start("Method2");
Method2();
ps.Stop();

ps.Print();

If calls follow each other, you can omit the Stop()
ps.Start("Method1");
Method1();
ps.Start("Method2");
Method2();
ps.Print();

It works well with a loop:
for(int i = 0; i < 10000; i++)
{
    ps.Start("Method1");
    Method1();
    ps.Start("Method2");
    Method2();
}
ps.Print();

A: What you need is the Restart function of the Stopwatch class, something like this:
public bool func()
{
    var stopwatch = Stopwatch.StartNew();

    func1();

    Debug.WriteLine(stopwatch.ElapsedMilliseconds);

    stopwatch.Restart();

    func5();

    Debug.WriteLine(stopwatch.ElapsedMilliseconds);
}

A: I use:
void MyFunc()
    {
        Watcher watcher = new Watcher();
        //Some call
        HightLoadFunc();
        watcher.Tick("My high load tick 1");

        SecondFunc();
        watcher.Tick("Second tick");

        Debug.WriteLine(watcher.Result());
        //Total: 0.8343141s; My high load tick 1: 0.4168064s; Second tick: 0.0010215s;
    }

Class
class Watcher
{
    DateTime start;
    DateTime endTime;

    List<KeyValuePair<DateTime, string>> times = new List<KeyValuePair<DateTime, string>>();

    public Watcher()
    {
        start = DateTime.Now;
        times.Add(new KeyValuePair<DateTime, string>(start, "start"));
        endTime = start;
    }

    public void Tick(string message)
    {
        times.Add(new KeyValuePair<DateTime, string>(DateTime.Now, message));
    }

    public void End()
    {
        endTime = DateTime.Now;
    }

    public string Result(bool useNewLine = false)
    {
        string result = "";
        if (endTime == start)
            endTime = DateTime.Now;

        var total = (endTime - start).TotalSeconds;
        result = $"Total: {total}s;";

        if (times.Count <2)
            return result + " Not another times.";
        else
            for(int i=1; i<times.Count; i++)
            {
                if (useNewLine) result += Environment.NewLine;
                var time = (times[i].Key - times[i - 1].Key).TotalSeconds;
                var m = times[i];
                result += $" {m.Value}: {time}s;";
            }

        return result;
    }
}


text:
Q: Run random actions i would anyone know how to run actions by random?
let action2 = SKAction.colorizeWithColor(UIColor.cyanColor(), colorBlendFactor: 1.0, duration: 3)
let action3 = SKAction.colorizeWithColor(UIColor.purpleColor(), colorBlendFactor: 1.0, duration: 3)
let action6 = SKAction.colorizeWithColor(UIColor.darkGrayColor(), colorBlendFactor: 1.0, duration: 3)
let action7 = SKAction.colorizeWithColor(UIColor.yellowColor(), colorBlendFactor: 1.0, duration: 3)
let action8 = SKAction.colorizeWithColor(UIColor.redColor(), colorBlendFactor: 0.3, duration: 3)
let action9 = SKAction.colorizeWithColor(UIColor.orangeColor(), colorBlendFactor: 1.0, duration: 3)

let round1 = (SKAction.repeatActionForever(SKAction.sequence([action2,action3,action6,action7,action8,action9])))
let round2 = (SKAction.repeatActionForever(SKAction.sequence([action9,action8,action6,action7,action3,action2])))
let round3 = (SKAction.repeatActionForever(SKAction.sequence([action3,action9,action6,action3,action2,action7])))

var colors = [round1,round2,round3]

self.scene?.runAction(arc4random_uniform(UInt32(colors.count)))

I get the error on   self.scene?.runAction(arc4random_uniform(UInt32(colors.count)))

A:  self.scene?.runAction(arc4random_uniform(UInt32(colors.count)))

This code will generate, something like:
 self.scene?.runAction(4)
 self.scene?.runAction(2)

Got the problem?
You need an array of actions, somewhere you can put the actions, and then get from it by an index.
Try
let arrayOfActions = [action2, action3, action4,..] //complete with the actions

 self.scene?.runAction(arrayOfActions[arc4random_uniform(UInt32(colors.count))])