text:
Q: Fatal Exception: java.lang.NoSuchMethodError: No virtual method callEngineReleaseConnection(Lcom/squareup/okhttp/Call;) The complete error is described as follows:
Fatal Exception: java.lang.NoSuchMethodError: No virtual method callEngineReleaseConnection(Lcom/squareup/okhttp/Call;)V in class Lcom/squareup/okhttp/internal/Internal; or its super classes (declaration of 'com.squareup.okhttp.internal.Internal' appears in /data/app/com.glossyglobe.client-1/base.apk:classes2.dex)
       at com.squareup.okhttp.ws.WebSocketCall.createWebSocket(WebSocketCall.java:125)
       at com.squareup.okhttp.ws.WebSocketCall.access$000(WebSocketCall.java:42)
       at com.squareup.okhttp.ws.WebSocketCall$1.onResponse(WebSocketCall.java:102)
       at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:177)
       at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
       at java.lang.Thread.run(Thread.java:818)

I don't understand why this error is displayed. Libraries and dependencies may be updated, but not
Please tell me how to solve?
buildscript {

    repositories {
        maven { url 'https://maven.fabric.io/public' }
        maven { url "https://www.jitpack.io" }
        maven { url "https://maven.google.com" }
        maven { url 'http://jcenter.bintray.com' }
        maven { url = 'https://oss.sonatype.org/content/repositories/snapshots'}
        jcenter()
        google()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.1'
        classpath 'com.github.triplet.gradle:play-publisher:1.2.2'
        classpath 'com.google.gms:google-services:4.3.3'
        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.0.0-beta02'
    }
}

apply plugin: 'com.android.application'
apply plugin: 'com.github.triplet.play'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'

def AAVersion = '4.3.1'
def AmplitudeVersion = '2.9.2'
def frescoVersion = '1.2.0'

android {
    compileSdkVersion = 29
    buildToolsVersion "29.0.3"

    aaptOptions
            {
                cruncherEnabled = false
            }
    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }
    packagingOptions {
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/*'
        exclude 'META-INF/LICENSE.txt'

        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

repositories {
    mavenCentral()
    maven { url 'https://maven.fabric.io/public' }
    maven { url "http://jzaccone.github.io/SlidingMenu-aar" }
    maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local' }
    google()
    jcenter()
}

play {
    if (!project.hasProperty('track_value')) {
        logger.info("you need pass track (alpha, beta, production) -Ptrack_value=value")
        return
    }

    if (!project.hasProperty('service_account')) {
        logger.info('Please pass service_account')
    }

    if (!project.hasProperty('key_file')) {
        logger.info('Please pass key_file')
    }

    track = track_value
    serviceAccountEmail = service_account
    pk12File = file(key_file)
}

dependencies {

    implementation 'com.parse.bolts:bolts-android:1.+'

    implementation 'com.nineoldandroids:library:2.4.0'
    implementation 'com.daimajia.easing:library:1.0.0@aar'
    implementation 'com.daimajia.androidanimations:library:1.1.2@aar'

    implementation 'com.makeramen:roundedimageview:2.0.0'

    implementation 'com.sothree.slidinguppanel:library:3.1.0'
    implementation 'com.jeremyfeinstein.slidingmenu:library:1.3@aar'

    implementation 'com.asksira.android:loopingviewpager:1.1.2'
    implementation 'com.romandanylyk:pageindicatorview:1.0.1'

    implementation "com.amplitude:android-sdk:$AmplitudeVersion"

    implementation('com.crashlytics.sdk.android:crashlytics:2.10.1@aar') {
        transitive = true
    }

    implementation 'com.appsflyer:af-android-sdk:5.2.0@aar' //5.1.1
    implementation 'com.android.installreferrer:installreferrer:1.1.2'

    implementation "com.android.support:appcompat-v7:" + SUPPORT_LIBRARY_VERSION
    implementation "com.android.support:recyclerview-v7:" + SUPPORT_LIBRARY_VERSION
    implementation "com.android.support:cardview-v7:" + SUPPORT_LIBRARY_VERSION
    implementation "com.android.support:design:" + SUPPORT_LIBRARY_VERSION
    implementation 'android.arch.lifecycle:extensions:1.1.1'

    implementation "com.google.firebase:firebase-core:16.0.1" //16.0.1
    implementation "com.google.firebase:firebase-messaging:18.0.0" //18.0.0
    implementation 'com.google.firebase:firebase-database:17.0.0'
    implementation 'com.google.firebase:firebase-analytics:16.0.1'
    implementation 'com.google.firebase:firebase-auth:17.0.0'
    implementation 'com.google.firebase:firebase-firestore:18.0.0'

    implementation 'com.google.maps.android:android-maps-utils:0.3.4'

    implementation 'com.android.support:multidex:1.0.3'

    implementation 'org.greenrobot:eventbus:3.0.0'

    implementation 'com.squareup.retrofit2:retrofit:2.8.1'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.4.1'
    implementation 'com.google.code.gson:gson:2.8.5'

    annotationProcessor "org.androidannotations:androidannotations:$AAVersion"
    implementation "org.androidannotations:androidannotations-api:$AAVersion"

    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'

    implementation 'pl.charmas.android:android-reactive-location:0.10@aar'

    implementation 'com.googlecode.libphonenumber:libphonenumber:8.3.2'

    implementation 'com.stripe:stripe-android:7.0.1'

    implementation 'com.braintreepayments.api:drop-in:3.+'

    implementation 'com.payfort:start:0.2'

    implementation 'ru.tinkoff.acquiring:ui:1.4.5'
    implementation 'ru.tinkoff.acquiring:card-io:1.4.5'

    implementation 'com.facebook.android:facebook-android-sdk:4.42.0'
    implementation 'com.facebook.android:facebook-login:4.42.0'

    implementation 'com.timqi.sectorprogressview:library:2.0.1'

    implementation 'com.github.florent37:singledateandtimepicker:2.1.1'

    implementation 'com.github.stfalcon:frescoimageviewer:0.5.0'
    implementation "com.facebook.fresco:fresco:$frescoVersion"

    implementation 'com.cesards.android:cropimageview:1.0.2.1'

    implementation 'com.hbb20:ccp:2.2.0'

    implementation 'com.netflix.rxjava:rxjava-android:0.18.4'

    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation project(':creditCardEntry')
    implementation project(':wheel')
    implementation project(':viewflow')
    implementation project(path: ':chat')

    implementation 'com.google.android.gms:play-services-maps:16.0.0'
    implementation 'com.google.android.gms:play-services-places:16.0.0'
    implementation 'com.google.android.gms:play-services-identity:16.0.0'
    implementation 'com.google.android.gms:play-services-location:16.0.0'
    implementation 'com.google.android.gms:play-services-gcm:16.0.0'
    implementation 'com.google.android.gms:play-services-base:16.0.0'

}

P.S. If there is not enough data for informational content, I will supplement

A: I searched for a solution for a long time and found: It turned out there was a conflict between
'com.squareup.retrofit2: retrofit: 2.8.1' and
'com.google.firebase: firebase-firestore:18.0.0'.
Just remove this: 'com.google.firebase:firebase-firestore:18.0.0'
A source: https://en.programqa.com/question/58921485/


text:
Q: SQL Calculate time between one row and the next one I have a table clicks
click_id int
created datetime

Example data
1 2021-03-01 12:15:17
2 2021-03-01 12:15:21
3 2021-03-01 12:17:21
4 2021-03-01 13:17:59

I want to select all clicks including the time difference (in seconds) between it and the soonest click afterwards
Result needed:
1 - 2021-03-01 12:15:17 - 4
2 - 2021-03-01 12:15:21 - 120
3 - 2021-03-01 12:17:21 - 3602
4 - 2021-03-01 13:17:23 - null

Can this be achieved using MySQL?

A: On MySQL 8+, we can use LEAD with TIMESTAMPDIFF:
SELECT
    click_id,
    created,
    TIMESTAMPDIFF(SECOND, created, LEAD(created) OVER (ORDER BY created)) AS diff_sec
FROM yourTable
ORDER BY created;

redpajama_set_name: RedPajamaStackExchange


text:
Q: TeamViewer moving all windows into currently viewed monitor I believe this may be a new feature but I would very much like to disable it.
I have three monitors and anything I launch automatically gets moved into the screen I am currently viewing despite me having specifically placed it elsewhere before closing it last.
I would like for apps that were last closed off-screen to still launch off-screen.
I am running the latest beta version (11).


text:
Q: Big gap in horizontal uicollectionview using orthogonalScrollingBehavior As the title suggests I face weird bug (at least I did not expect that) where my items in my collection view have big gap like in this picture

I am using orthogonalScrollingBehavior from new compositional layout API
this is my code
let itemSize = NSCollectionLayoutSize(widthDimension: .absolute(100), heightDimension: .fractionalHeight(1))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
item.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 8)

let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(200))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])

let section = NSCollectionLayoutSection(group: group)
section.orthogonalScrollingBehavior = .continuous
return section

I was expecting that the only gap between them is made by contentInsets. Please help if you know the answer or the reason why this happens

A: I had the same problem. Try to use widthDimension: .estimated(1) for the group
NSCollectionLayoutSize. Example:
func makeTestLayoutSection() -> NSCollectionLayoutSection {
    let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .absolute(400), heightDimension: .absolute(500)))
    let group = NSCollectionLayoutGroup.horizontal(layoutSize: NSCollectionLayoutSize(widthDimension: .estimated(1), heightDimension: .absolute(500)), subitems: [item])
    let section = NSCollectionLayoutSection(group: group)
    section.orthogonalScrollingBehavior = .continuous
    return section
}

Tested on tvOS 15.0

A: same happening to me, maybe it's a bug since if visible cell widths are fitting the content width, then it does not get this annoying spacing. trying to find a workaround.


text:
Q: invoke $ajax on confirmation how can i prevent/invoke $ajax by pressing Cancel or Ok button by calling  myConfirm function ? currently i get undefined if i try with:
 var vCal = myConfirm('dialogText', 'dialogTitle');

do i missed something ?
function myConfirm(dialogText, dialogTitle) {
$('
' + dialogText + '
').dialog({
    .....
    buttons: {
      "OK" : function (e) {
        console.log('yes');
        $(this).dialog('destroy');
        return true;
      },
      "Abbrechen" : function (e) {
        console.log('no');
        $(this).dialog('destroy');
        return false;
      }
    }
});
}

function openTickerDialogDelete (id) {
....

if(!myConfirm('dialogText', 'dialogTitle')) {
    return false;
}
console.log('call ajax');
$.ajax({
    .....
        success: function( data ) {

        }
})
}

using return confirm() works great, but i would like to use the dialog box
thank you

A: Simply place the ajax call inside the OK button function it will execute when the button is clicked:
function myConfirm(dialogText, dialogTitle, okCallback) {
$('
' + dialogText + '
').dialog({
    .....
    buttons: {
      "OK" : function (e) {
        if ($.isFunction(okCallback)) {
           okCallback();
        }
        $(this).dialog('destroy');
        return true;
      },
      "Abbrechen" : function (e) {
        console.log('no');
        $(this).dialog('destroy');
        return false;
      }
    }
});
}

Open dialog with any success function:
myConfirm('dialogText', 'dialogTitle', function(){
    $.ajax({
        .....
        success: function( data ) {

        }
    });
});

Open a dialog without a success function
myConfirm('dialogText', 'dialogTitle');

Calling a function with parameters:
myConfirm('dialogText', 'dialogTitle', function(){
    tickerDelete(id);
});


text:
Q: How to assign a Gmail drive to a drive letter? I would like to assign a drive letter to a GMail drive so that I could script some output to it.  Are they any hacks to get this to work?

A: GMail Drive no longer works (well) -- Google put rate limits into Gmail to prevent this kind of (ab)use of Gmail.  It's like being attached to a hard drive over a bad satellite connection to Rwanda*.
You might look into Amazon's S3, which is a cheap web-hosted data storage service; then ask this question again from an S3 perspective.
* Incidentally, that's what I deal with at work on a weekly basis.

A: I use the SMEStorage service for this which works really well. The GMail package I signed up for enables you to use GMail as a Storage Cloud and it works really well. There are also some windows tools that you can use. I'm using the paid version which gives me a vitual (namespace) drive, sync, and shell tools as well as MS Office and Open Office integration. If sign up for the Lifetime Cloud package (which is what I did) you can use up to 10 GMail accounts.


text:
Q: Eclipse won't restart I have Ubuntu 14.04.2 LTS and Eclipse Java EE IDE for Web Developers
Version: Luna Release (4.4.0)
When I restarting it it shuts down also fine but don't want to start.
All I have in workspace/.metadata/.log file is:
!ENTRY org.eclipse.ui.browser 2 0 2015-05-14 09:49:26.402
!MESSAGE Internal browser is not available: No more handles [Unknown Mozilla path (MOZILLA_FIVE_HOME not set)]

!ENTRY org.eclipse.egit.ui 2 0 2015-05-14 09:49:29.067
!MESSAGE Warning: EGit couldn't detect the installation path "gitPrefix" of native Git. Hence EGit can't respect system level
Git settings which might be configured in ${gitPrefix}/etc/gitconfig under the native Git installation directory.
The most important of these settings is core.autocrlf. Git for Windows by default sets this parameter to true in
this system level configuration. The Git installation location can be configured on the
Team > Git > Configuration preference page's 'System Settings' tab.
This warning can be switched off on the Team > Git > Confirmations and Warnings preference page.

This warning isn't repeat with restart trial.
What I need to look for for find the reason?


text:
Q: ASP.NET MVC - Form Returns Null Model Unless Model is Wrapped in a Custom ViewModel I have a pair of views in my application that both display the same Editor Template for one of my model items; of the two views ("Add" and "Edit"), "Edit" works fine, but "Add" is returning null for the model when my controller action handles the post.
I found that if I give the "Add" view a custom ViewModel and call Html.EditorFor(p => p.PageContent) rather than simply calling the EditorFor() on the whole Model object- Html.EditorFor(p => p), then the form returns the correct, non-null model, but that generates other problems pertaining to my client-side scripting and control IDs (as now all of the fields are prefixed with "PageContent_"). I am using the same Editor Template technique in a few different places throughout my application and none of the others are exhibiting this odd dependency on a ViewModel.
Has anyone else ever experienced similar problems?
Edit View
<%@ Page Title="" Language="C#" MasterPageFile="~/Areas/Admin/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<PageContent>" %>

<% using (Html.BeginForm())
   { %>
<%=Html.Hidden("PageID", Model.Page.ID) %>
<%=Html.EditorFor(p => p)%>
<input type="submit" name="btnSave" value="Save" />
<input type="submit" name="btnCancel" value="Cancel" class="cancel" />
<% }

Action (Working)
[HttpPost, ValidateInput(false)]
public ActionResult EditContent(int id, FormCollection formCollection) {}

Add View
<%@ Page Title="" Language="C#" MasterPageFile="~/Areas/Admin/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<PageContent>" %>

<% using (Html.BeginForm())
   { %>
<%=Html.Hidden("PageID", ViewData["PageID"]) %>
<%=Html.EditorFor(p => p)%>
<input type="submit" name="btnSave" value="Save" />
<input type="submit" name="btnCancel" value="Cancel" class="cancel" />
<% } %>

Action (Failing)
// content is ALWAYS null
[HttpPost, ValidateInput(false)]
public ActionResult AddContent(PageContent content, FormCollection formCollection) {}

Before you cry "duplicate"
This question does relate to this one, but this question is intended to target the specific problem I am experiencing rather than the more general question asked there.

A: I tracked down the problem and it's a rather interesting one.
When the DefaultModelBinder attempts to resolve a model item one of the first things it does is check to see if there are any prefixed fields in the data being bound; it does this by checking for any form items that begin with the name of the model object (this seems extremely arbitrary, if you ask me). If any "prefixed" fields are found then it results in different binding logic being invoked.
ASP.NET MVC 2 Preview 2 BindModel() Source
public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
    if (bindingContext == null) {
        throw new ArgumentNullException("bindingContext");
    }
    bool performedFallback = false;
    if (!String.IsNullOrEmpty(bindingContext.ModelName) && !DictionaryHelpers.DoesAnyKeyHavePrefix(bindingContext.ValueProvider, bindingContext.ModelName)) {
        // We couldn't find any entry that began with the prefix. If this is the top-level element, fall back
        // to the empty prefix.
        if (bindingContext.FallbackToEmptyPrefix) {
             /* omitted for brevity */
            };
            performedFallback = true;
        }
        else {
            return null;
        }
    }

    // Simple model = int, string, etc.; determined by calling TypeConverter.CanConvertFrom(typeof(string))
    // or by seeing if a value in the request exactly matches the name of the model we're binding.
    // Complex type = everything else.
    if (!performedFallback) {
       /* omitted for brevity */
    }
    if (!bindingContext.ModelMetadata.IsComplexType) {
        return null;
    }
    return BindComplexModel(controllerContext, bindingContext);
}

The controller action I defined to handle the Add action defines a PageContent item called "content" and in my domain PageContent has a property called "Content" which "matched" with the model name of "content" thus causing the DefaultModelBinder to assume I had a prefixed value when in fact it was simply a member of PageContent. By changing the signature-
from:
[HttpPost, ValidateInput(false)]
public ActionResult AddContent(PageContent content, FormCollection formCollection) {}

to:
[HttpPost, ValidateInput(false)]
public ActionResult AddContent(PageContent pageContent, FormCollection formCollection) {}

The DefaultModelBinder was once again able to correctly bind to my PageContent model item. I'm not sure why the Edit view didn't also display this behavior, but either way I've tracked down the source of the issue.
It seems to me that this issue falls very close to "bug" status. It makes sense that my view worked initially with the ViewModel because "content" was getting prefixed with "PageContent_", but a core framework feature/bug like this ought not be unaddressed IMHO.


text:
Q: Why doesn't UIViewController fill the window when rotating, while UINavigationController does? I've just noticed that when a UIViewController is the root controller on a window, autorotation bleeds a bit of the window through as it's rotating.

This is not the case when you use a UINavigationController as the root controller, however. What is UINavigationController doing differently to avoid the bleed-through?

A: My guess (unfortunately I don't have a good Xcode presently to test), is that it's related to UIViewController's wantsFullScreenLayout property. I suspect that UINavigationController returns YES, and default VCs return NO.


text:
Q: Child expands past the bounds of its parent when height or width set to 100% using MigLayout in Java I'm trying to use MigLayout to set the height of certain elements to take up the full height of their parent's container using the expression "height 100%" however there is some kind of feedback loop in MigLayout that causes the height to jump to the maximum value when loaded. This issue only happens when the MiGPanel is embedded into a JScrollPane, if I remove the lines of code dealing with the JScrollPane and add the MiGPanel to my JFrame then the program runs as intended. I added the boolean statement in there to make this eaiser to see.
NOTE:
I've seen this fix but I'd like to use a solution where I don't have a margin on the bottom of my program.
How to prevent MigLayout from exceeding a container's bounds
Here is the code:
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import net.miginfocom.swing.MigLayout;

public class StackOverFlowQuestion {
    public static void main(String[] args) {

        JPanel MiGPanel = new JPanel();
        MiGPanel.setBackground(Color.red);
        MiGPanel.setLayout(new MigLayout());

        JPanel greenPanel = new JPanel();
        greenPanel.setBackground(Color.green);
        MiGPanel.add(greenPanel, "pos 0 0, width 33%, height 100%");

        JPanel yellowPanel = new JPanel();
        yellowPanel.setBackground(Color.yellow);
        MiGPanel.add(yellowPanel, "pos 33% 0, width 33%, height 100%");

        JPanel bluePanel = new JPanel();
        bluePanel.setBackground(Color.blue);
        MiGPanel.add(bluePanel, "pos 66% 0, width 34%, height 100%");

        JFrame mainFrame = new JFrame();
        mainFrame.setLayout(new BorderLayout());

        boolean scroll = true;
        if(scroll){
            JScrollPane scrollPane = new JScrollPane();
            scrollPane.add(MiGPanel);
            scrollPane.setViewportView(MiGPanel);
            mainFrame.add(scrollPane);
        }else{
            mainFrame.add(MiGPanel);
        }

        mainFrame.add(scrollPane);
        mainFrame.pack();
        mainFrame.setSize(900, 600);
        mainFrame.setVisible(true);
        mainFrame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    }
}

A: After many sleepless nights, I came up with a solution:
    greenPanel.setLayout(new BorderLayout());
    greenPanel.add(new JLabel("test"));
    MiGPanel.add(greenPanel, "pos 0 0 33% 100%");

    JPanel yellowPanel = new JPanel();
    yellowPanel.setBackground(Color.yellow);
    MiGPanel.add(yellowPanel, "pos 33% 0 66% 100%");

    JPanel bluePanel = new JPanel();
    bluePanel.setBackground(Color.blue);
    MiGPanel.add(bluePanel, "pos 66% 0 100% 100%");

Absolute positioned elements should not use with and height attributes, instead you should use the "pos x y x1 y1" method.


text:
Q: SPD workflow to reset check box I have a sharepoint list that uses a cascading lookup to display items from another list in the first list.  I need to reset the checkbox on the item in the lookup display box in the every week beginning with a date in the "Start Date" field. Is it possible to construct a workflow in SPD to reset the checkbox every 7 days from the "Start Date"?

A: You can make something like a "loop" using SharePoint designer (but actually what you do is delay for a while, then modify the item AND make another instance of the same workflow run when the item is modified). The technique is described here: http://sharepointmagazine.net/technical/development/the-dog-ate-my-task-use-sharepoint-designer-to-email-daily-task-reminders


text:
Q: Pulp not find solution i am trying find optimal solution of problem using Pulp module in Python. My problem  is on photo. I wrote this problem in Pulp but I get that this problem is Infeasible (status -1). I know that this problem have solution but I must make some mistake in code (when I change that variables are continuous problem has continuous solution).
Thank you for your help.
import numpy as np
# Import PuLP modeler functions
from pulp import *

# Creates the 'prob' variable to contain the problem data
prob = LpProblem("Computer company service problem", LpMinimize )
demand = {1: 6000, 2: 7000, 3: 8000, 4: 9500, 5: 11500}

# A dictionary called 'Vars' is created to contain the referenced variables(the routes)
vars_x = LpVariable.dicts("x", range(1,6), 0, None, LpInteger)
vars_y = LpVariable.dicts("y", range(1,6), 0, None, LpInteger)

# The objective function is added to 'prob' first
prob += lpSum([15000*vars_y[i] + 7500*vars_x[i]  for i in range(1,6)]), "Sum_of_employee_cost"

# The demand minimum constraints are added to prob for each demand
for i in range(1,6):
    prob += 160*vars_y[i]-50*vars_x[i]>=demand[i], f"Reach demand in month {i}"

# The demand minimum constraints are added to prob for each demand node (bar)
prob += vars_y[1]==50, f"Workers in month {1}"

for i in range(2,6):
    prob += 0.95*vars_y[i-1]+vars_x[i-1]==vars_y[i], f"Workers in month {i}"

prob.solve()


text:
Q: Animation not playing in Unity 5.3.5f1 For some reason my animation is not playing, it creature looks like it stuck on a 1st frame.
public Animator anim;
void FixedUpdate () {
    targetDistance = Vector3.Distance(target.position, transform.position);

    if (targetDistance < attackDistance)
        {

        attack();
        print("Attack");
    }
}
void attack()
{
    theRigidBody.AddForce(transform.forward * speed);

    anim.Play("attack", -1, 0f);
}

It's printing "Attack" in console and creature changes its pose, but for some reason it's not playing.

A: Did you set your anim variable in the editor ? It probably would lead to an error if not, so you probably did.
Try this :
anim.Play("attack", PlayMode.StopAll);
//or
anim.Play("attack", PlayMode.StopSameLayer);

If no success, do this :
print(anim.Play("attack", PlayMode.StopAll).ToString());

if it returns false, it means that no animation named "attack" was found.


text:
Q: Is it possible to use dynamic objects with Dynamic LINQ? Is it possible to use a list of dynamic objects with dynamic LINQ?
If I create a dynamic object with dynamic properties and then want to use Dynamic LINQ on a list of such objects?
For example, I have (where data is a list of dynamic objects):
IEnumerable<dynamic> result = data.Where(x => x.branch_group != "");

which works.
And:
IEnumerable<dynamic> result = data.Where("branch_group != \"\"");

which does NOT work.

And if I try to get values using Select I get "No property or field 'xxx' exists in type 'Object'".
This should be possible to do, right?
Has someone done these kinds of things before?
Thanks in advance!
UPDATE!
Yay!
I finally found a solution to this after 24 hours (yes, it´s true) of constant hard investigation and severe hallucinations!
I could actually hear those code lines crunhing in my head and I witnessed universes of civilizations go extinct from trying to solve this problem. I saw space-time itself shiver before the vastness of eternal death which surrounded this domain of unsolvability.
BUT! Then I slept for 4 hours and got the solution in the morning.
The key to solving this problem is to create an object which uses an indexer in such a way that the dynamic LINQ library will use it at runtime using the "it"-keyword.
So, it´s actually possible, although every article, blog, forum, [insert source here] etc I´ve read suggested that it was not.
I may even deserve some credit (or like endless dollar$ or something) for this.
(Yeah, yeah, I´m all over-excited about all this and blah, blah, blah. But it´s damn true!) :P
For code sample, please mail to: johan@codelink.se

A: using the opensource Impromtu-Interface (found in nuget)
IEnumerable<dynamic> result = data.Where(Impromptu.InvokeGet(x,"branch_group") != "")

It's ugly, but it would allow "branch_group" to come from a variable, which I assume is the benefit your are looking for over the statement that worked.
Impromptu has wrappers for all types of dlr calls, since it's open source it's possible to dig into the code and adapt the same techniques into a dynamic linq type syntax, but probably a lot of work.


text:
Q: ORACLE and TRIGGERS (inserted, updated, deleted) I would like to use a trigger on a table which will be fired every time a row is inserted, updated, or deleted.
I wrote something like this:
CREATE or REPLACE TRIGGER test001
  AFTER INSERT OR DELETE OR UPDATE ON tabletest001
  REFERENCING OLD AS old_buffer NEW AS new_buffer
  FOR EACH ROW WHEN (new_buffer.field1 = 'HBP00')

and it works.
Since I would like to do the same things if the row is inserted, updated, or deleted, I would like to know what's happening in the trigger.
I think I can manage to find if the row is inserted or updated (I can check the old_buffer with the new_buffer).
How can I know if the row has been deleted?

A: The NEW values (or NEW_BUFFER as you have renamed them) are only available when INSERTING and UPDATING.  For DELETING you would need to use OLD (OLD_BUFFER).  So your trigger would become:
CREATE or REPLACE TRIGGER test001
  AFTER INSERT OR DELETE OR UPDATE ON tabletest001
  REFERENCING OLD AS old_buffer NEW AS new_buffer
  FOR EACH ROW WHEN (new_buffer.field1 = 'HBP00' OR old_buffer.field1 = 'HBP00')

You may need to add logic inside the trigger to cater for code that updates field1 from 'HBP000' to something else.

A: From Using Triggers:

Detecting the DML Operation That Fired
  a Trigger
If more than one type of DML operation
  can fire a trigger (for example, ON
  INSERT OR DELETE OR UPDATE OF
  Emp_tab), the trigger body can use the
  conditional predicates INSERTING,
  DELETING, and UPDATING to check which
  type of statement fire the trigger.

So
IF DELETING THEN ... END IF;

should work for your case.

A: I've changed my code like this and it works:
CREATE or REPLACE TRIGGER test001
  AFTER INSERT OR UPDATE OR DELETE ON tabletest001
  REFERENCING OLD AS old_buffer NEW AS new_buffer
  FOR EACH ROW WHEN (new_buffer.field1 = 'HBP00' OR old_buffer.field1 = 'HBP00')

DECLARE
      Operation       NUMBER;
      CustomerCode    CHAR(10 BYTE);
BEGIN

IF DELETING THEN
  Operation := 3;
  CustomerCode := :old_buffer.field1;
END IF;

IF INSERTING THEN
  Operation := 1;
  CustomerCode := :new_buffer.field1;
END IF;

IF UPDATING THEN
  Operation := 2;
  CustomerCode := :new_buffer.field1;
END IF;

// DO SOMETHING ...

EXCEPTION
    WHEN OTHERS THEN ErrorCode := SQLCODE;

END;

A: Separate it into 2 triggers. One for the deletion and one for the insertion\ update.


text:
Q: What library should I use to get the data from a photo of a QR Code?
Similar: Does anyone know of a C/C++ Unix QR-Code library?

I tried libqrencode but apparently it's only able to generate a QR-Code. However, I need a library that reads the data from a photo of a printed QR-Code.
It must be a C, C++ or Objective-C library and it has to compile on BSD systems. On my platform, Java and .NET are not available.
What libraries can I use?
Thanks.

A: Try using libdecodeqr , it doesn't seem to be updated for over a year but a Google search reveals that it still works.

A: zxing (http://code.google.com/p/zxing/) is probably the most well-known and used in a number of barcode/qr-code apps. The original/primary code is Java but it includes a C++ port that is pretty actively maintained, particularly for QR codes.
The C++ library does not (currently) have an encoder, but it sounds like you want a decoder.


text:
Q: Why don't we know the electric potential at any point in a circuit, only the difference in the electric potential (voltage)? Why in circuit analysis, don't we know the electric potential at any point in a circuit?

A: In loop analysis where we apply Kirchhoff's voltage law (the algebraic sum of the potential differences around a loop equals zero) it is only necessary to consider potential differences.
In doing node analysis where we apply Kirchhoff's current law (the algebraic sum of the currents into a node equals zero) we consider the potentials at the different nodes. In order to do this we assign a potential of zero to some node in the circuit. Then the potential at each node is measured with respect to that node.
Although the assignment of zero potential is technically arbitrary, to facilitate the analysis it is usually a node that is common to multiple branches, or the negative terminal of a battery. But no matter where this zero potential is assigned, the potential differences across specific components will be the same.
Hope this helps.

A: The electric potential at a point is defined as
$$V(\vec a)=-\int_{\vec{\mathscr O}}^{\vec a}\vec E \cdot d\vec S$$
provided that $\nabla \times \vec E = 0$ (in other words, that there are no changing magnetic fields; you need this condition for the uniqueness of the $V$). In words, voltage is amount of work per charge $q$ needed to bring the charge $q$ from $\vec{\mathscr O}$ to $\vec a$.
However, as you can see, the value of $V(\vec a)$ is dependent on the choice of the reference point $\vec{\mathscr O}$. It is customary to choose it as infinity, since the electric field is in realistic cases zero there, and the lower limit of the integral usually vanishes. Note that this is not the case with "infinite" objects, since the electric field continues to infinity, and we need to use other reference point if we want potentials not to diverge
In realistic cases, if we choose other reference point $\vec{\mathscr O'}$, this corresponds to adding a constant, which doesn't influence the voltage difference (which we are ordinarily interested in):
$$V(\vec a)=-\int_{\vec{\mathscr O'}}^{\vec a}\vec E \cdot d\vec S=-\int_{\vec{\mathscr O'}}^{\vec{\mathscr O}}\vec E \cdot d\vec S-\int_{\vec{\mathscr O}}^{\vec a}\vec E \cdot d\vec S=-\int_{\vec{\mathscr O}}^{\vec a}\vec E \cdot d\vec S+K$$
So, with our circuit, we can (of course, the circuit is realistic scenario, it doesn't have infinite plates) choose the reference point of infinity, and the potential is known at every point (not just the potential drop). However, we usually give potential drop since this is the difference of two potentials, and the choice of a reference point doesn't influence it.
The simplest component of the circuit with well-known potential is the ground or the negative terminal: it is zero. If you then specify the potential difference to the ground/negative terminal, this is the same as the potential.


text:
Q: PHP Обработка многомерного массива $POST Есть форма отправки с массивом:
<form action="script.php" method="post" autocomplete="off">
<input type="text" name="number[one]" value="111">
<input type="text" name="number[two]" value="222">
<input type="text" name="number[three]" value="333">
<button type="submit">GO</button>
</form>

В script.php ошибка:
if($_POST['number']) {
 $result = $_POST['number'][one],$_POST['number'][three];
}

Как сделать, чтобы в $result записалось '111,333'?

A: как то так
if(!empty($_POST['number'])) {
$result = $_POST['number']['one'].','.$_POST['number']['three'];
echo $result;
}

A: Замените эту строку:
$result = $_POST['number']['one'] , $_POST['number']['three'];

На вот эту:
$result = $_POST['number']['one'] . $_POST['number']['three'];

Или на эту:
$result = $_POST['number']['one'] .','. $_POST['number']['three'];

У вас там банальная опечатка.


text:
Q: Jetty and Jersey 404 error on an old project As part of my work, I am trying to update some of our services and one is being deployed with Jetty & Jersey. Unfortunately the code is very old (some dependencies are from 2014), and while it is compiling and server starts, whenever I run it from my IDE with mvn jetty:run the root directory shows the Directory / message correctly whereas for all other URLs I get the error 404 NOT FOUND.
I don't get any warning/error messages on console and I can't find why it happens. I've searched a lot but the code seems correct, the only thing that is missing is the web.xml but I think Jetty is embedded, and I need to mention that this code is already running in production as a JAR.
Below you can see some of the files:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sample</groupId>
    <artifactId>sample</artifactId>
    <version>2.0</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.2.2.v20140723</version>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.21</version>
        </dependency>

        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>9.2.3.v20140905</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
            <version>9.2.3.v20140905</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-server</artifactId>
            <version>2.7</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <version>2.7</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-jetty-http</artifactId>
            <version>2.7</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
            <version>2.7</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
            <version>2.7</version>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160212</version>
        </dependency>

    </dependencies>

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

</project>

The class below is referenced to start the server:
ApiService.java

import com.simple.api.restendpoint.*;
import org.apache.log4j.Logger;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.server.*;
import org.eclipse.jetty.server.handler.IPAccessHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;

import java.util.HashSet;
import java.util.Set;

public class ApiService {
    Logger log = Logger.getLogger(ApiService.class);

    private static ApiService instance;
    private final Server server;

    private ApiService(){
        //CREATE CONFIG
        Set<Class<?>> s = new HashSet<>();
        s.add(restEndpoint.class);

        ResourceConfig config = new ResourceConfig(s);

        //CREATE CONTAINER
        ServletContainer container = new ServletContainer(config);

        //CREATE CONTEXT
        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        context.addServlet(new ServletHolder(container),"/*");

        //CREATE RPC SERVER
        QueuedThreadPool threadPool = new QueuedThreadPool();
        threadPool.setMaxThreads(50);
        server = new Server(threadPool);

        server.setHandler(context);

        ServerConnector connector = new ServerConnector(server);
        connector.setPort(8080);

        server.addConnector(connector);

        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath("testkeystore");
        sslContextFactory.setKeyStorePassword("testkeystore");
        sslContextFactory.setKeyManagerPassword("testkeystore");

        // SSL HTTP Configuration
        HttpConfiguration https_config = new HttpConfiguration();
        https_config.addCustomizer(new SecureRequestCustomizer());

        // SSL Connector
        ServerConnector sslConnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(https_config));
        sslConnector.setPort(Settings.getInstance().getRpcPort());
        server.addConnector(sslConnector);

    }

    public static ApiService getInstance() {
        if (instance==null) {
            instance = new ApiService();
        }
        return instance;
    }

    public void start() {
        try {
            //START RPC
            server.start();
            server.join();
            log.info("Server started");
        }
        catch (Exception e) {
            //FAILED TO START RPC
            log.error("Error starting server");
        } finally {
            server.destroy();
        }
    }
}

restEndpoint.java
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Context;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

@Path("/v4/restEndpoint")
@Produces({"application/json"})
public class restEndpoint {
    Logger log = Logger.getLogger(restEndpoint.class);

    private static final String VERSION = "v4";

    private static final ExecutorService executors = Executors.newFixedThreadPool(20);

    @Context
    HttpServletRequest request;

    @GET
    @Path("/getsamplejson")
    public void getSampleJson(@Suspended final AsyncResponse asyncResponse) {
        executors.execute(new Runnable() {
            @Override
            public void run() {
                String result = veryExpensiveOperation();
                asyncResponse.resume(result);
            }

            private String veryExpensiveOperation() {
                JSONObject sampleJson = new JSONObject().put("test", 0);
                return sampleJson.toString();
            }
        });
    }
}

Any idea why is it happening?
http://localhost:8080/v4/restEndpoint/getsamplejson returns 404 NOT FOUND
http://localhost:8080/ shows Directory: /
Should I try to build it as a JAR and run it through that, instead of using the mvn jetty:run command?

A: You have an embedded-jetty instance, started from code.
That is evidenced by the ApiService source you have provided.
You cannot use the jetty-maven-plugin to manage / start / run that class.
The jetty-maven-plugin is exclusively for working with webapps, either as WAR packaged files, or as exploded webapp directories. (webapps will either have a WEB-INF/web.xml and / or Servlet annotated classes within it)
You'll need to start the server using other means that is unique to your project, likely some kind of main class, or testcase, that eventually instantiates the ApiService and calls .start() on it.


text:
Q: read data in txt file and put them into a specific format What I want to achieve?
• Insert Lat and Long Data into a .txt file (Per line and lat and lon are seperated by "," )
[.txt file]
59.4834, 8.84748
58.4973, 8.38564
• Read data and paste it into a specific format
The Format
<Placement Lat="X" Lon="X" Alt="0#AGL" Hdg="0.0"/>
I want the X`s to be replaced by the data in the .txt file.
If I have 3 lines with coordinates, I want 3 placement outputs each.
Let's assume the text file has 3 lines.
23.8474, 8.5824

25.8474, 9.4735

27.4913, 9.2394

Then the output would be
<Placement Lat="23.8474" Lon="8.5824" Alt="0#AGL" Hdg="0.0"/>

<Placement Lat="25.8474" Lon="9.4735" Alt="0#AGL" Hdg="0.0"/>

<Placement Lat="27.4913" Lon="9.2394" Alt="0#AGL" Hdg="0.0"/>```

A: Is this what you're looking for?
with open("your_text_file.txt") as text_file:
    lines = [line.strip().split(", ") for line in text_file.readlines() if line.strip()]
    template = '<Placement Lat="{}" Lon="{}" Alt="0#AGL" Hdg="0.0"/>\n'
    print("\n".join(template.format(*line) for line in lines))

Output:
<Placement Lat="23.8474" Lon="8.5824" Alt="0#AGL" Hdg="0.0"/>

<Placement Lat="25.8474" Lon="9.4735" Alt="0#AGL" Hdg="0.0"/>

<Placement Lat="27.4913" Lon="9.2394" Alt="0#AGL" Hdg="0.0"/>

A: A slightly different approach:
import ast
for lat,lon in map(ast.literal_eval,[x.strip() for x in open("lat_lon.txt","rt") if x.strip()]):
    print (f'<Placement Lat="{lat}" Lon="{lon}" Alt="0#AGL" Hdg="0.0"/>')


text:
Q: What is the difference between creating a model instance using the default Manager and Customer Manager While going through the official Django documentation I came across the Model Instance reference section in which it is mentioned that you can create an instance of the model using the custom Model using self.create. I wanted to know what's the difference between using the create method and the custom create_method when both are using the same fields and in both the cases the data is being saved in the DB.
Documentation:
https://docs.djangoproject.com/en/2.2/ref/models/instances/#creating-objects
class BookManager(models.Manager):
    def create_book(self, title):
        book = self.create(title=title)
        return book

class Book(models.Model):
    title = models.CharField(max_length=100)

    objects = BookManager()

book = Book.objects.create_book("Pride and Prejudice")

Difference between these two

book2 = Book.objects.create(title="Pride and Prejudice")

A: Well in this simplest case, there is no difference. The reason of describing this technique in docs is obvious there

You may be tempted to customize the model by overriding the __init__
  method. If you do so, however, take care not to change the calling
  signature as any change may prevent the model instance from being
  saved. Rather than overriding __init__, try using one of these
  approaches:

It means you may be want to set some extra/default values to model instance. If you override constructor for this purpose, it is a little unsafe (and not usually a practice in django). That's why two other techniques for doing this are described. You are mentioning one of them. You can do some extra stuff in custom manager method if you want
class BookManager(models.Manager):
    def create_book(self, title):
        # you can do some extra stuff here for instance creation
        book = self.create(title=title)
        # or here when it is saved to db
        return book

Otherwise there is no difference.


text:
Q: Android Studio installation troubleshooting I have installed Android Studio on my Mac. After installing, I simply created an application with an empty Activity. No coding, nothing I implemented, just checking my Android Studio. Tried to run that and am getting these errors:
Error: Read timed out
FAILURE: Build failed with an exception.

A problem occurred configuring root project 'MyApplication'.

Could not resolve all artifacts for configuration ':classpath'.
  Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/tools/build/builder/3.3.1/builder-3.3.1.jar'.
  *Try:
  Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more logout. Run with --scan to get full insights.
  -Get more help at https://help.gradle.org
  BUILD FAILED in 57s
  Read timed out

I have tried installing all the Gradles, 3.3.1, 4010.0, 3.5.1.
I have changed the Gradle version in build.gradle and installed all Gradle versions and checked all. Still, it's not working. I am getting the same error.
Earlier, I got the "unable to find the trusted certificate to requested target" but solved that by adding the certificate to the keystore.
Now I am unable to understand why this error is so difficult to fix.
It's just an empty Activity application with no implementation.

A: Firstly, ensure that your have your google() properly configured in your repositories{}, i.e.
repositories {
    google() // make this repo as the first one if Android Gradle Plugin is upgraded from 2.x to 3.x.
    jcenter()
    mavenCentral()
}

See https://stackoverflow.com/a/51151050/8034839 for more detailes.
Secondly, Check your Proxy for gradle
Under your Android project root directory, find gradle.properties file and add below settings:
systemProp.http.proxyHost=my-example-proxy.com
systemProp.http.proxyPort=8080
systemProp.https.proxyHost=my-example-proxy.com
systemProp.https.proxyPort=8080
# Add all your hosts that should be bypassed by your proxy server.
systemProp.https.nonProxyHosts=localhost

Note that this proxy setting will apply to your gradle build commands as well.


text:
Q: adding toggle span to twitter bootstrap collapse I'm using Twitter Bootstrap on a new site and I need to add a plus/minus to the toggler. The section is wrapped in an EE channel entries tag to loop through career entires and create an accordion list. My accordion code is as follows:
{if count == "1"}

{/if}

{title} +

                {careers-summary}

Learn More

{if count == total_results}

{/if}

The javascript I started writing that doesn't seem to want to work is as follows (see new code below):
All I'm trying to do is get the plus sign to change to a minus and vice versa when the accordion is opened/closed. The more I look at the javascript I started, even if it did actually change the text as I'd like, it would not necessarily do so when I clicked on another accordion toggler. What's the best way to get this to work and have it flexible enough to work on multiple accordion togglers?
UPDATE I've made some changes to the javascript and used the events Twitter Bootstrap offers. I also removed the data-parent attribute so these act like collapsible togglers and not an accordion. The new code is as follows:
$('.accordion').on('hide', function () {
    $('.accordion-toggle span').html('+');
})
$('.accordion').on('show', function () {
    $('.accordion-toggle span').html('-');
})

This actually changes the text but it changes the plus/minus sign for every toggler not just the toggler you clicked. I could add a custom class to each span but I'm not sure how I would then target this in the javascript without having to create a show.hide function for each toggled. That seems inefficient and there must be an easier way to do this.

A: You should use the Bootstrap show and hide events like so instead of your click function above:
$(".accordion-body").on("show",function(event){
        $('span', $(this).prev()).text('-');
});
$(".accordion-body").on("hide",function(event){
        $('span', $(this).prev()).text('+');
});

JS Fiddle here.

A: Simple solution worked for Bootstrap 3.
$('[data-toggle="collapse"]').click(function(e) {
    $(e.target).find('.icon-minus-sign, .icon-plus-sign').toggleClass("icon-minus-sign icon-plus-sign");
});

A: The following is for an accordion where only one panel will be open at a time (for Bootstrap 3)
1. CSS - only
#accordion2 .accordion-toggle span.glyphicon.glyphicon-collapse-up:before {
content:"\e160" /* an up type icon */
}

#accordion2 .accordion-toggle.collapsed span.glyphicon.glyphicon-collapse-up:before {
content:"\e159" /* a down type icon */
}

The collapsed class needs to be set in the HTML from the outset
JS fiddle example
2. Javascript
Using Javascript to check for the class '.collapsed' on all the links with class '.accordion-toggle':
jQuery(document).ready(function ($) {
    $(document).on('click', '.accordion-toggle', function () {
        $(".accordion-toggle").each(function () {
            var iconSpan = $(this).find('.glyphicon');
            if ($(this).hasClass('collapsed')) {
                $(iconSpan).removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
            } else {
                $(iconSpan).removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-up');
            }
        });
    });
});

Fiddle: http://jsfiddle.net/JungleEditor/bCk3f/


text:
Q: Group files by date I want to zip the files according to the month and year on which they are modified. I am able to get the month and year using simple date format.
package codes;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.SimpleDateFormat;

public class UsingLoops
{
private static final String FOLDER_PATH = "C:\\Users\\Desktop\\Zip";

public static void main(String[] args) throws IOException
{
    File dir = new File(FOLDER_PATH);

    File[] files = dir.listFiles(new FilenameFilter() {

        @Override
        public boolean accept(File directory, String fileName)
        {
            if (fileName.endsWith(".txt"))
            {
                return true;
            }
            return false;
        }
        });

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");

    for(File f:files)
    {
        System.out.println(f.getName());

        String month = sdf.format(f.lastModified());

        int j = Integer.parseInt(month);

        System.out.println(j);
    }
  }
}

Now I want to list the files according to the month and year.
For example

201412201411 etc..

And how to give the name for the ZIP as the year and month automatically.
Help me out here....
I know how to zip using java, but I need it according to time and naming automation, hope you got my point

A: You can use a SortedMap, keyed by a java.util.Date to build a List of files which have been modified for a specific month/year, for example...
File[] files = ...;

Map<Date, List<File>> mapFiles = new TreeMap<>();

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
for (File file : files) {
    try {
        // This might seem weird, but basically, this will trim
        // off the date (day) and time, making it possible to
        // better match elements which fall within the same month
        // and year...
        // You could use a Calendar here to extract the Year and Month
        // values, it would mean you're not creating so many short lived
        // objects, but that's up to you
        Date date = sdf.parse(sdf.format(new Date(file.lastModified())));
        List<File> group = mapFiles.get(date);
        if (group == null) {
            group = new ArrayList<>(25);
            mapFiles.put(date, group);
        }
        group.add(file);
    } catch (ParseException ex) {
        ex.printStackTrace();
    }
}

// Now, you can process the groups individually...
for (Date date : mapFiles.keySet()) {
    System.out.println(sdf.format(date));
    for (File file : mapFiles.get(date)) {
        System.out.println("    " + file);
    }
}

You don't "have" to use a SortedMap for this, you can use any kind of Map, but this will allow you to sort the groups by their Date key...don't know if it's important or not...
If you wanted to, you could go further and group the files first by year and then have a second group for the months...
Map<Date, Map<Date, List<File>> mapFiles = ...

You could use String as the key, but if you wanted to control the sort order, then Date or Integer would be better


text:
Q: C++ template class static const variable member as map key gives undefined reference I have a bunch of classes that have a static member that is an enum value. And I have a map somewhere else with this enum as key. Now if I use a template parameter in a function to access the map, I get an undefined reference.
To make it clear, here is a simplified non-working example :
template<int T>
struct A
  {
    static const int Type = T;
  }

template<class T>
void fun()
  {
    cout << map_[T::Type] << endl;
  }

map<int, string> map_{{1337, "1337"}};

main :
fun<A<1337>();

gives me (g++ 4.7) :
undefined reference to `(anonymous namespace)::A<1337>::Type'

However this :
template<class T>
void fun()
  {
    auto key = T::Type;
    cout << map_[key] << endl;
  }

Compile and prints 1337
Can someone explain me this behavior?

A: When you use T::Type, you must define it:
template<int T>
struct A
{
   static const int Type = T;
}

template <int T>
const int A<T>::Type;

Yes, even though you provided its initialiser inline within A<T>!
The reason that you may not have been aware of this, is the same reason that you don't get the same problem in your second case — due to the immediate lvalue-to-rvalue conversion, the standard allows the compiler to optimize the requirement to refer to Type at runtime, able instead to pick out the value at compile-time. The linker then has no need to search for the definition, and you get no error.

[C++11: 9.4.2/2]: The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for a static data member shall appear in a namespace scope enclosing the member's class definition. In the definition at namespace scope, the name of the static
  data member shall be qualified by its class name using the :: operator. The initializer expression in the definition of a static data member is in the scope of its class (3.3.7). [..]
[C++11: 9.4.2/3]: If a non-volatile const static data member is of integral or enumeration type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression
  is a constant expression (5.19). A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [ Note: In both these cases, the member may appear in constant expressions. —end note ] The member shall still be defined in a namespace scope if it is odr-used (3.2) in the program and the namespace scope definition shall not contain an initializer.
[C++11: 3.2/2]: [..] A variable whose name appears as a potentially-evaluated expression is odr-used unless it is an object that satisfies the requirements for appearing in a constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) is immediately applied. [..]

A: That is because std::map::operator[] takes its argument by reference, which makes your variable odr-used (see paragraph 3.2/3 of the C++11 Standard).
In short, the whole thing boils down to the fact that the compiler needs to know the address of an object when it needs to bind a reference to it, and that makes it impossible for it to treat that object just like a pure value and perform inlining.
In that case, you need to provide a definition of your static data member at global namespace scope, so that the compiler knows what region of storage that object occupies (i.e. what its address is):
template<int T>
const int A::Type;

Per paragraph 9.4.2/3 of the C++11 Standard:

If a non-volatile const static data member is of integral or enumeration type, its declaration in the class
  definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression
  is a constant expression (5.19). [ ... ] The member shall still be defined
  in a namespace scope if it is odr-used (3.2) in the program and the namespace scope definition shall not
  contain an initializer.

In the first version of your program, on the other hand, you were only using the value of your static data member, which means Type was not odr-used, and a definition at namespace scope was not needed.


text:
Q: Recording multiple meshcat visualizers I would like to record multiple meshcat visualizers with different prefix ids so I can eventually save them to an HTML file that I can interact with later. I would like the different visualizations to play on top of each other and to be able to select/unselect different visualizations.
Here is a minimal replication of the problem. I expect there to be two cartpole visualizations that are on top of each other. However, I only end up seeing one of them being recorded. The other cartpole seems stuck at the end position when I play back the recording
import meshcat
from pydrake.common import FindResourceOrThrow

from pydrake.multibody.plant import (
    AddMultibodyPlantSceneGraph)
from pydrake.multibody.parsing import Parser
from pydrake.systems.analysis import Simulator
from pydrake.systems.framework import DiagramBuilder
from pydrake.systems.meshcat_visualizer import (
    ConnectMeshcatVisualizer,
)

v = meshcat.Visualizer()
file_name = FindResourceOrThrow(
    "drake/examples/multibody/cart_pole/cart_pole.sdf")
builder = DiagramBuilder()
cart_pole, scene_graph = AddMultibodyPlantSceneGraph(builder, 0.0)
Parser(plant=cart_pole).AddModelFromFile(file_name)
cart_pole.Finalize()

vis = ConnectMeshcatVisualizer(builder=builder,
                                prefix="vis",
                                scene_graph=scene_graph,
                                open_browser=False)

vis2 = ConnectMeshcatVisualizer(
    builder=builder,
    prefix="vis2",
    scene_graph=scene_graph,
    open_browser=False)
vis2.set_name("vis2")

diagram = builder.Build()
diagram_context = diagram.CreateDefaultContext()

cart_pole_context = diagram.GetMutableSubsystemContext(
    cart_pole, diagram_context)
cart_pole.get_actuation_input_port().FixValue(cart_pole_context, .02)

simulator = Simulator(diagram, diagram_context)
simulator.set_publish_every_time_step(False)
vis.start_recording()
vis2.start_recording()
simulator.AdvanceTo(100)
vis.stop_recording()
vis2.stop_recording()

vis.publish_recording()
vis2.publish_recording()

# f = open("saved.html", "w")
# f.write(v.static_html())
# f.close()

A: Here is one solution.  I don't love it, but it accomplishes the stated goal.  Note the changes:

*

*saving and publishing only one animation

*naming the model in the MultibodyPlant with a distinct name for each sim

*setting delete_prefix_on_load=False so it doesn't clear the old geometry

import meshcat
from pydrake.common import FindResourceOrThrow

from pydrake.multibody.plant import (AddMultibodyPlantSceneGraph)
from pydrake.multibody.parsing import Parser
from pydrake.systems.analysis import Simulator
from pydrake.systems.framework import DiagramBuilder
from pydrake.systems.meshcat_visualizer import (
    ConnectMeshcatVisualizer,
)

animation = None

for i in range(3):
    file_name = FindResourceOrThrow(
        "drake/examples/multibody/cart_pole/cart_pole.sdf")
    builder = DiagramBuilder()
    cart_pole, scene_graph = AddMultibodyPlantSceneGraph(builder, 0.0)
    Parser(plant=cart_pole).AddModelFromFile(file_name, f"plant{i}")
    cart_pole.Finalize()

    vis = ConnectMeshcatVisualizer(builder=builder,
                                   scene_graph=scene_graph,
                                   delete_prefix_on_load=False,
                                   open_browser=False)
    if animation:
        vis._animation = animation

    diagram = builder.Build()
    diagram_context = diagram.CreateDefaultContext()

    cart_pole_context = diagram.GetMutableSubsystemContext(
        cart_pole, diagram_context)
    cart_pole.get_actuation_input_port().FixValue(cart_pole_context, .02)

    simulator = Simulator(diagram, diagram_context)
    simulator.set_publish_every_time_step(False)
    vis.start_recording()
    simulator.AdvanceTo(10)
    vis.stop_recording()
    animation = vis._animation

vis.publish_recording()


text:
Q: how to apply lighting to .obj file on pyopengl i implement arcball with an object from .obj file in the center
when i try to implement lighting, the object show strange behaviour

when i turn the object slightly, the object deconstruct and suddenly show the back side

this behaviour doesn's come up until i implement lighting
based on this How to correctly add a light to make object get a better view with pygame and pyopengl
this is what i do regarding the lighting impelementation
if __name__ == "__main__":
    pygame.init()
    display = (SCREEN_WIDTH,SCREEN_HEIGHT)
    screen = pygame.display.set_mode(display, DOUBLEBUF|OPENGL)

    glMatrixMode( GL_PROJECTION );
    gluPerspective(45, (display[0]/display[1]), 0.1, 30000.0)

    glTranslatef(0.0, 0.0, -250)

    glLight(GL_LIGHT0, GL_POSITION,  (1, 1, 1, 0))
    glLightfv(GL_LIGHT0, GL_AMBIENT, (0, 0, 0, 1))
    glLightfv(GL_LIGHT0, GL_DIFFUSE, (2, 2, 2, 1))

    while True:
        mouse_pos = pygame.mouse.get_pos()

        glMatrixMode( GL_MODELVIEW )
        glLoadIdentity()

        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

        glEnable(GL_LIGHTING)
        glEnable(GL_LIGHT0)
        glEnable(GL_COLOR_MATERIAL)
        glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE )

        object1.draw()

        glDisable(GL_LIGHT0)
        glDisable(GL_LIGHTING)
        glDisable(GL_COLOR_MATERIAL)

        pygame.display.flip()
        pygame.time.wait(10)

A: You have to enable the Depth Test. Enable the depth test before the application loop:
glEnable(GL_DEPTH_TEST)


text:
Q: mysql events with specific time I'm using mysql from a hosting company. They give me 50 mb max storage for mysql. And There is a table which grows very fast in my mysql. If I save this table in different format to my server and clean my table for new entries I don't have any storage problems.
My question is, is there a way to set a timeout for server to do it? I mean like if there is a way from server to start a function on a specific time.
Let's say I want my server to start a function at 01.15.2012.. Can I do that? Like is there a way to set server to start my function? and can I write a php function to save my mysql table and clean it?

A: If it's a Linux server you can use cron. Write your php script, then set up the cron process to execute the script at a particular time.

A: You can use MySQL events to run a script or to call stored function.


text:
Q: What conditions for $f(x)$ does $\lim_{x\to\infty} f(x)-\sum_{n=1}^{x}f'(n)$ converge I was exploring the euler-mascheroni constant when I thought of this problem. The euler-mascheroni constant (usually denoted as $\gamma$) can be calculated a number of ways, but the primary example is this formula: $$\lim_{x\to\infty}\ln(x)-\sum_{n=1}^{x}\frac{1}{n}=-\gamma$$
I thought about what other kinds of constants I can generate. I remembered that $\frac{d}{dx}\ln(x)=\frac{1}{x}$, so I first thought to generalize the "constant generating method" like this: $$\lim_{x\to\infty}f(x)-\sum_{n=1}^{x}f'(n)$$ where $f(x)$ and its derivative can be evaluated for all positive integers, and the limit is discrete (meaning $x$ is only a positive integer when it approaches infinity).
For the rest of the question, we'll call it The Operation${}^{{}^{\mathsf{TM}}}$. Of course, this diverges for (I estimate) most functions. For example, when $f(x)=x^2$, the value of the above operation tends to negative infinity. But for other functions that grow more slowly or tend to zero, it can converge. For example, when $f(x)=\ln(x)$, you get the negative of the euler-mascheroni constant (by defenition), and when $f(x)=\frac{1}{x}$, you get essentially the Basel problem which evaluates to $\frac{\pi^2}{6}$. One that I find quite interesting is when $f(x)=\operatorname{W}(x)$ where $\operatorname{W}(x)$ is the Lambert-W funciton (AKA the product-log function), it evaluates to about 0.3688... when I added the first 5000 terms into Wolfram-Alpha. The point to take away from this is that for some functions, the operation will converge to a constant.
So after toying around this a bit, I came to my question: What condition(s) are needed for $f(x)$ so that the operation converges? Assume the limit is always discrete.
Some conditions I am looking for (proof required):

*

*Examples of specific functions given a parameter (e.x. the operation converges for the form $f(x)=x^a$ for $a\leq1$)

*Proof of convergence or divergence given a property (e.x. if $\lim_{x\to\infty} f'(x)=0$, then the operation converges)

*Proof of a property given convergence or divergence (e.x. if the operation converges, then $\lim_{x\to\infty} f'(x)=0$)

*A comparison test (e.x. $\ln(x)$ converges under the operation. $\lim_{x\to\infty}\operatorname{W}(x)<\ln(x)$, therefore $\operatorname{W}(x)$ also converges)

*If at all possible, a complete condition (e.x. the operation converges if and only if $\lim_{x\to\infty} f'(x)=0$)

I haven't been able to prove any of the examples. If this is something known, please share it with me! And if any of you can provide research on this, please share it with me in the comments or an answer. I am very interested in this because I haven't found it anywhere before. The most important (for lack of a better term) or interesting property receives the answer reward.
*post-question note: I find it kind of interesting how the operation takes in a whole function as an input, and a number as an output. It's like a function-function.


text:
Q: In what cases a developer should start considering setting the isolation level explicitly? Under what conditions should a developer consider changing the default isolation level explicitly defined by the framework?
Thanks!

A: Almost never.
There are many clever RDBMS, .net, Jave etc engineers working for Microsoft, Oracle etc who know more than the average code monkey (me and you) about this kind of thing
Some SO questions about dirty reads:

*

*Default isolation level in Microsoft SQL Server 2005

*Using NOLOCK Hint in EF4?
And a recent blog article from SQL Server support team: "Inappropriate usage of high isolation level isn't just about blocking when it comes to performance"


text:
Q: Snakemake specify a new wildcard in a new rule I have input files:
Bob_1.fastq.gz
Bob_2.fastq.gz
Bob_3.fastq.gz
Bob_4.fastq.gz
Ron_1.fastq.gz
Ron_2.fastq.gz
Ron_3.fastq.gz
Ron_4.fastq.gz

I am running demultiplexing and trimming steps in one snakefile, like this:
workdir: "/path/to/dir/"
(SAMPLES,) =glob_wildcards('/path/to/dir/raw/{sample}.fastq.gz')

rule all:
    input:
        expand("demulptiplex/{sample}.fastq.gz", sample=SAMPLES),
        expand("trimmed/{sample}.trimmed.fastq.gz", sample=SAMPLES)

rule sabre:
    input:
        infile="/path/to/dir/raw/{sample}.fastq.gz",
        barcodefile= "files/{sample}.txt"
    output:
        unknownfile=temp("demulptiplex/unknown_barcode_{sample}.fastq.gz"),
    shell:
        """
        /Tools/sabre-master2/sabre se -f {input.infile} -b {input.barcodefile} -u {output.unknownfile}
        """

rule trimmomatic_se:
    input:
        r="{sample}.fastq.gz"
    output:
        r="trimmed/{sample}.trimmed.fastq.gz"
    threads: 10
    shell:
        """java -jar /Tools/Trimmomatic-0.36/trimmomatic-0.36.jar SE -threads {threads} {input.r} {output.r} ILLUMINACLIP:/Tools/Trimmomatic-0.36/adapters/TruSeq3-SE.fa:2:30:10 LEADING:3 TRAILING:3 SLIDINGWINDOW:4:15 MINLEN:36"""

The demultiplex output files are like this:
Bob_1_CL1.fastq.gz.... Bob_1_CL345.fastq.gz
Bob_2_CL1.fastq.gz.... Bob_1_CL248.fastq.gz
Ron_1_dad1.fastq.gz... Ron_1_dad67.fastq.gz

and so on
So,if I do not specify the demultiplex output file the program would create it by itself. My problem is how to specify/introduce a new wildcard from the output of the previous rule in the next trimming step, as the wildcards are different from initial sample now.

A: Wildcards just need to be consistent in a rule, not across the workflow.  The issue here is that you have a rule generating 'unknown' outputs that you need to process further.  For that you need to use checkpoints.
Read through the second block of code about aggregating.  Your checkpoint will be demultiplexing and if you don't have any other steps, all will be your aggregate step that calls checkpoints.demultiplex.get.  If you search for checkpoint on stackoverflow you will find lots of examples; it's a hard feature to use at first!


text:
Q: Python - Custom tkinter - component.setfocus() don't work with customtkinter component like CTkEntry I have this code and focus dont work with customtkinter
from tkinter import *
import customtkinter as ctk
import sys

if len(sys.argv) > 1:
    print("Tk Customized from Tom")
    win = ctk.CTk()
    win.geometry("750x250")
    text = ctk.CTkTextbox(win, width=200, height=200)
    text.pack()
    text.insert(INSERT, "Hello World!")
    entry = ctk.CTkEntry(win, width=100)
    entry.pack()
    entry.focus_set()
else:
    print("Standard Tk ")
    win = Tk()
    win.geometry("750x250")
    text = Text(win, width=30, height=10)
    text.insert(INSERT, "Hello World!")
    text.pack()
    entry = Entry(win, width=30)
    entry.pack()
    entry.focus_set()

win.mainloop()

py testy.py   -> Start standard Tkinter  Focus is on Entry
py testy.py 1 -> Start with customtkinter objects Focus is NOT on Entry
How can get focus on CTkEntry ?


text:
Q: GetDeviceGammaRamp to adjust colors I overlay an OpenGL application (c++), this openGL application uses SetDeviceGammaRamp to set the brightness of the desktop to very high (dont know why). This application is fullscreen and looks good, but my overlay is very bright. Instead of the orange color with normal brightness, I get yellow because of the high gamma.
What I want to do: Get the gamma that is currently set (using GetDeviceGammaRamp), and then use this to adjust the colors I set.
Like; glColor4f(r, g, b, a) becomes glColor4f(r / gamma, g / gamma, b / gamma, a);
So if the brightness of the desktop is very high, the r g and b values will be lower (darker) and will look like they should.
How can I accomplish this? GetDeviceGammaRamp fills a table, how can I use it to modify my colors?
Thanks

A: You may be better off just using the ARB_framebuffer_sRGB extension if you can:
#define GL_FRAMEBUFFER_SRGB 0x8DB9 //might already be defined

bool supportSRGB = (0 != strstr((char*)glGetString(GL_EXTENSIONS), "GL_ARB_texture_non_power_of_two"));
if(supportsSRGB)
{
    glEnable(GL_FRAMEBUFFER_SRGB);
}


text:
Q: PhantomJS package - converting html to pdf issue I'm using PhantomJS Package for converting an HTML page to pdf. I'm using below code for generating the pdf file.
const phantom = require('phantom');

(async function() {
  const instance = await phantom.create();
  const page = await instance.createPage();

  await page.property('viewportSize', { width: 1024, height: 600 });
  const status = await page.open('https://stackoverflow.com/');
  console.log(`Page opened with status [${status}].`);

  await page.render('stackoverflow.pdf');
  console.log(`File created at [./stackoverflow.pdf]`);

  await instance.exit();
})()

Using above code pdf generated successfully. But the page of the generated pdf is too long not A4 size. Can you please let me how to resolve this issue.
To view the generated PDF - https://drive.google.com/file/d/1RfKZd5ZPFpYDOkiPR6mFt_5M0BhRbTXQ/view

A: You should set the page paperSize.

paperSize {object}
This property defines the size of the web page when rendered as a PDF.

page.paperSize = {
  width: '8.267in',
  height: '11.692in',
  margin: {
    top: '50px',
    left: '20px'
  }
};


text:
Q: Why does a POST request become a GET request in Microsoft Edge? I'm using Axios and React in my frontend app. When I'm trying to send POST request over HTTPS with Axios (xhr, fetch) and faced with the strange issue - my POST request turns into GET in Edge dev tools.
Here is my request:
const response = await axios.post(
        config.local + "/api/login/credentials",
        {
          login,
          password
        }
      );

Then I tried to dig dipper - created a simple HTTPS server and tried to send POST request from the client.
const https = require('https');
const fs = require('fs');

const options = {
    key: fs.readFileSync('server.key'),
    cert: fs.readFileSync('server.crt')
};

const PORT = 8188;

function handleRequest(req, res){
    console.log(req.method);
}

const server = https.createServer(options, handleRequest);

server.listen(PORT, function(){
    console.log("Server listening on: https://localhost:" + PORT);
});

And then, as I understand it, that request does not reach the server.
Here are some links:
Issue link 1
Issue link 2

A: Is there any error in console? You could use Fiddler to trace the network traffic and see the details. Also mentioned in the first link you provided, you could also try the two solutions in your GitHub link:
Solution 1:

My issue is caused by HTTPS; the backend is requiring HTTPS while I send an HTTP post from front side. Now I fixed by changing both to HTTPS.

Or Solution 2:

I solved it by passing the data in a different format using the "URLSearchParams " class.
  I had the same problem with:
  Microsoft Edge 44.18362.267.0
  Microsoft EdgeHTML 18.18362
  Windows 10
I think the problem is that Edge only supports certain data types in post requests. If you want to use the content-type 'application/x-www-form-urlencoded' then use URLSearchParams to make it work in Edge and other browsers like Firefox and Chrome. Passing a querystring seems not to work in Edge even if it does in other browsers.
Modifying the original post source code, the result would be:
import Axios from 'axios'
import Promise from 'es6-promise'
Promise.polyfill()
const URL= 'http://192.168.0.112/account/login/username'

// Use URLSearchParams instead:
const dataParams = new URLSearchParams()
dataParams.append('username', 'admin')
dataParams.append('password', 'admin')

Axios.post(URL, dataParams, {
  // if you still have problems try more specific options like:
  // withCredentials: true,
  // crossdomain: true,
  // ...
})
.then(res=>{
    console.log(res)
    }
)
.catch(error=>{
    console.log(error)
    }
)

Aside from that, the issue in your question is usually caused by CORS. If you use CORS and request an untrusted origin, then Microsoft Edge will only send the GET request and lead to the failure of other requests. You could also refer to this thread to understand why CORS requests fail in Microsoft Edge but work in other browsers. Microsoft Edge also uses Enhanced Protected Mode, the outcome is that: if the site is trusted, it will make two requests, OPTIONS and GET, but if it's not trusted, it only makes the GET request which causes it to fail.

A: In my case problem was caused by a self-sign certificate. As soon as I started using normal certificate everything began to work.