text:
Q: NodeJs Mongoose How can I get out a data from "find().then" in a "find().then"? Sorry for my Title, I don't know what can I put.
Can you help me please, I would like to print data from a "then" in a "then" ?
Thank you
models.book.find()
  .then( function (content) {
    var i = 0;

    while (content[i]) {
      models.author.findOne({"_id": content[i].author_id}, function(err, data) {
        console.log(data); //here, it' good
        content[i] = data;

        MY_DATA = content;

        return MY_DATA;
      });

      i++;
    };
  })
  .then(function (result) {
    console.log(result); // here I would like to print MY_DATA
  });

A: There are a number of problems with your code, and I don't think it's behaving as you're expecting it to.
Chaining Promises
In order to effectively chain promises how you're expecting, each promise callback needs to return another promise. Here's an example with yours changed around a bit.
var promise = models.book.find().exec(); // This returns a promise
// Let's hook into the promise returned from
var promise2 = promise.then( function (books) {
  // Let's only get the author for the first book for simplicity sake
  return models.author.findOne({ "_id": books[0].author_id }).exec();
});

promise2.then( function (author) {
  // Do something with the author
});

In your example, you're not returning anything with your callback (return MY_DATA is returning within the models.author.findOne callback, so nothing happens), so it's not behaving as you're expecting it to.
model.author.findOne is asynchronous
model.author.findOne is asynchronous, so you can't expect to call it multiple times in the callback without handling them asynchronously.
// This code will return an empty array
models.book.find( function (err, books) {
  var i = 0, results = [];

  while (books[i]) {
    models.author.findOne({ "_id": books[i].author_id}, function (err, data) {
      // This will get called long after results is returned
      results.push(data);
    });

    i++;
  };

  return results; // Returns an empty array
});

Handling multiple promises
Mongoose uses mpromise, and I don't see a method to handle multiple promises together, but here's a way your case could be done.
var Promise = require('mpromise');

models.book.find().exec()
  .then( function (books) {
    var i = 0,
        count = 0,
        promise = new Promise(),
        results = [];

    while (books[i]) {
      models.author.findOne({ "_id": books[i].author_id }, function (err, author) {
        results.push(author);
        count++;
        // Keep doing this until you get to the last one
        if (count === books.length) {
          // Fulfill the promise to get to the next then
          return promise.fulfill(results);
        }
        return;
      });
    }

    return promise;
  })
  .then( function (results) {
    // Do something with results
  });

I don't know if this will work exactly like it is, but it should give you an idea of what needs to be done.


text:
Q: ASP.NET Web Api точка в запросе Здравствуйте. Проблема в том, что при посылке запрос, например, http://site.com/api/namecontroller/Петров П.П., то он это воспринимается, как URL, а не как переменная, что можно сделать, чтобы приложение понимало, что это параметр?
P.S. Параметры передаются в такой форме: namecontroller/param1/param2/param3/
A: как-то так:
http://site.com/api/namecontroller?param_name=Петров П.П.

соответственно, если параметров несколько:
<...>controller?param_name=Петров П.П.&param2_name=param2&param3_name=param3

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to load .mp3 in Flutter I want to add music to my project, and I added an .mp3 file, but it says it can't find the assets file.
This is the code:
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Music Player',
      home: MusicPlayer(),
    );
  }
}

class MusicPlayer extends StatefulWidget {
  @override
  \_MusicPlayerState createState() =\>  \_MusicPlayerState();
}

class \_MusicPlayerState extends State \<MusicPlayer\> {
  AudioCache player = AudioCache();
  String musicPath = "assets/audios/Meditation.mp3";

  @override
  void initState() {
    super.initState();
    player.load(musicPath);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Music Player'),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text('Play Music'),
          onPressed: () {
            player.loadAsFile(musicPath);
          },
        ),
      ),
    );
  }
}

I tried everything... and still get the same error. How can I fix this?

This is the error:

This is pubspec.yaml file:

A: This can happen in just_audio if you don't set the assets location in pubspec.yaml.
    flutter:
      assets:
        - audio/

This tells Flutter that you have an audio folder in the root of your project where you keep your audio assets.
After doing that, you should be able to set the asset and play it like so:
await player.setAsset('audio/cow.mp3');
player.play();

The error can also happen if you spelled something in the path wrong, but I assume you already checked for that.


text:
Q: ILMath.Vec() Appears to be Generation Slightly Wrong Output (Potential Bug?) I'm comparing ILMath.Vec() with MatLab's and I'm seeing significant rounding errors.
For example, if I create a vector (using Start:0, Step:1.2635048525911006, End:20700) for each system:
MatLab: [Start:Step:End]
ILNumerics: Vec<double>(Start, Step, End)
And then take the average abs difference, I get an average error of 1.56019608343883E-09. However, I if create the vector by hand (using multiplication), I get an average error of only 3.10973469197506E-13, 4 magnitudes smaller error.
After looking at ILNumerics' vec function (using Reflector), I think I know why the average error value is so large. The ILMath.vec() function is using addition vs. multiplication. Summing the step value 16,384 times is not the same thing as multiplying the step value x N (where N is the current loop count) 16,384 times! The addition's rounding errors add up very quickly!
Please consider fixing this issue.


text:
Q: Why using two or more fragments in the same Activity? I am a beginner android developer, and right now I'm learning about fragments in android, and so and as I read that :

A fragment is just a part of an activity. You can have a fragment that
  takes up part of a screen or a whole screen. Or you can show multiple
  fragments at the same time to make up a whole screen. Within an
  activity, you can also swap out different fragments with each other.
  (You can also have invisible fragments as well, that do some work
  related to the activity, but we won't cover those in this course.)
Fragments were introduced in Android when we started building for
  larger screen devices like tablets. Let me show you an example.
In the master/detail pattern, a list fragment is on the left side of
  the screen, while the detail fragment on the right swaps out depending
  on the list item selected.

So, I'm asking what's the utility of fragments apart from adapting to larger screens?
Thanks !!

A: It's mostly about reusable UI and self-contained code.
In a bigger project these can come in handy.
Also you can dynamically configure whats on the screen based on settings, maybe a/b testing, remote configuration etc. without lots of rewritten code. Team members can work independently on code parts if they are self-contained. Components can be tested in other activities, with different configurations.
So it really dependes on your use case.

A: You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).
Source : developer.android.com/guide/components/fragments


text:
Q: Remove a row on ng-click using angularJs I have a table with the default empty row(Row further includes a columns with different functionalities).Dynamically a multiple rows can be added by click of a button as per the requirement.i want to remove a row when i click a remove-icon from the same-row(remove-icon included in one of the column).

i have a above column to be included in all rows.whenever i click on remove-icon from any of the rows.(i want to remove a particular row from which icon is clicked)
 vm.removeService = function (service, removeService) {

}

Here,is the ng-repeat code for the row.

 vm.servicesWithCountries = [{ serviceName:"", countries: []}];

A: Hi you can do like below : Assuming your ng-repeat object will be like somewhat mention below.

            Hello, {{item.name}}!

        Delete

and in Controller :
$scope.items = [{
    name: 'item 1',
    id: '4'
  }, {
    name: 'item 2',
    id: '3'
  }, {
    name: 'item 3',
    id: '2'
  }, {
    name: 'item 4',
    id: '1'
  }];

  $scope.delete = function(item) {
    $scope.items.splice($scope.items.indexOf(item), 1);
  }

refer this fiddle for complete code

A: You can use splice and  indexOf on your service

Like:
ng-click="vm.removeService(service,true)"

JS
vm.removeService = function(service, removeService) {

    if(removeService === true){
       var index = vm.servicesWithCountries.indexOf(service);
       vm.servicesWithCountries.splice(index, 1);
    }
  }


text:
Q: Progress dialog with thread i am working on list view control in android. when i click on list view item i want one progress dialog box  and after requested data comes i want to stop it
well i put this dialog box in thread  and when thread is stop i want to display another dialog box but it reality its not working it fires error given below
05-10 15:05:10.607: ERROR/AndroidRuntime(820): Uncaught handler: thread MagentoBackground exiting due to uncaught exception
**05-10 15:05:10.617: ERROR/AndroidRuntime(820): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
My code is like this
           Runnable viewQuestions = new Runnable(){
            public void run() {
                getViewAnswer(answerBean);
            }

        };
       thread =  new Thread(null, viewQuestions, "MagentoBackground");
       thread.start();
       m_ProgressDialog = ProgressDialog.show(context, "Please wait...", "Retrieving data ...", true);

      protected void getViewAnswer(AnswerBean answerBean) {
          //fetch data code
            if(viewAnswerBeans != null && viewAnswerBeans.size() > 0){
             m_ProgressDialog.dismiss();
             viewAndGiveAnswerDialog(viewAnswerBeans);
                             dialogbox.show();

         } else {
             m_ProgressDialog.dismiss();
                     dialogBox.show();

         }
      }

my problem is this  "dialogBox.show();" wont work it wont display the message
can any one help me regarding this

A: Its because you are calling a UI component from a non-UI thread. Have a look at the following link
http://developer.android.com/resources/articles/painless-threading.html

A: Use a handler
private Handler gps_ws_handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
            m_ProgressDialog.dismiss();
            dialogBox.show();

    }
};

A: Create a handler within your activity.
Handler handler = new Handler();

Then inside the getViewAnswer, post a message to it.
protected void getViewAnswer(AnswerBean answerBean) {

    //fetch data code

    handler.post(new Runnable() {
    @Override
    public void run() {
        if(viewAnswerBeans != null && viewAnswerBeans.size() > 0){
        m_ProgressDialog.dismiss();
        viewAndGiveAnswerDialog(viewAnswerBeans);
                     dialogbox.show();

         } else {
        m_ProgressDialog.dismiss();
             dialogBox.show();

         }
    }
});
  }

A: For background tasks use AsyncTask with ProgressDialog bounded, like it is shown here.

A: for these purposes, I suggest you use AsyncTask

A: Try this
public class YourActivity extends Activity {
private ProgressDialog m_ProgressDialog = null;
private Runnable viewOrders;
private ListView mListView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.yourLayout);

    viewOrders = new Runnable() {

        public void run() {
            loadList();
        }
    };

    Thread thread = new Thread(null, viewOrders, "MagentoBackground");
    thread.start();
    m_ProgressDialog = ProgressDialog.show(YourActivity.this, "",
            "Get Data...", true);

}

private Runnable returnRes = new Runnable() {

    public void run() {

            mListView = (ListView) findViewById(R.id.yourList);

            //create here your adapter

            mListView.setAdapter(yourAdapter);
            mListView.setOnItemClickListener(new OnItemClickListener() {

                public void onItemClick(AdapterView<?> arg0, View v,
                        int position, long arg3) {

                    //on item click
                }
            });
        }
        m_ProgressDialog.dismiss();
    }
};

private void loadList() {
    try {
        /* Make your request Here
                    The progress Dialog is dismissed automatically after request is  finished */
        }

        Thread.sleep(1000);

    } catch (Exception e) {
    }

    runOnUiThread(returnRes);
}

}


text:
Q: Angular promise callbacks and the digest cycle Are promise callbacks in AngularJS guaranteed to be invoked in a digest cycle?
setTimeout(function () {
  var deferred = $q.defer();
  deferred.resolve();
  deferred.promise.then(function () {
    if ($rootScope.$$phase) {
      //I seem to be hitting this block
      console.log("in digest");
    } else {
      //Could I ever hit this block?
      console.log("not in digest");
    }
  });
});

A: Short Answer
Yes*
*Long Answer
The provider for $q defines the nextTick callback to call $rootScope.evalAsync(callback).
Quoting from the manual:

The $evalAsync makes no guarantees as to when the expression will be executed, only that:

*

*it will execute after the function that scheduled the evaluation (preferably before DOM rendering).

*at least one $digest cycle will be performed after expression execution.

  Any exceptions from the execution of the expression are forwarded to the $exceptionHandler service.
Note: if this function is called outside of a $digest cycle, a new $digest cycle will be scheduled. However, it is encouraged to always call code that changes the model from within an $apply call. That includes code evaluated via $evalAsync.

A: since i can not comment yet: yes, as long as you use $q to create your promise. using 3rd-party-promise-libraries you might be able to escape the digest loop.
btw you could write your code more elegant with a little hack:
$q.when([]).then(function(){
  ...
});


text:
Q: How to debug "TypeError: object of type 'StringVar' has no len()" in Python? Here is the error from the Python 3 shell:
##

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\DMECHCH\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "C:/Users/DMECHCH/OneDrive/Courses ARA/Diploma IT Tech Support Courses/DTEC501 - Programming fundementals/Week 14 Session 1/14-3 Q1.py", line 119, in <lambda>
    check_btn = Button(root_window,text="Change Password",command=lambda: validate_password(pwd1, pwd2))
  File "C:/Users/DMECHCH/OneDrive/Courses ARA/Diploma IT Tech Support Courses/DTEC501 - Programming fundementals/Week 14 Session 1/14-3 Q1.py", line 27, in validate_password
    pwd_length = len(password)
TypeError: object of type 'StringVar' has no len()
##

The error occurs when I click the button
Here is the full code
##

# Functions

def validate_password(first_pwd, second_pwd):
    """
    validates if password is acceptable
    """

    min_length = 8

    number_of_tests = 6
    test1 = 0 #Both entered passwords are identical.
    test2 = 0 #The password is >= 8 characters in length.
    test3 = 0 #if first and last chars are alpha then both must be different
    test4 = 0 #There are no more than 2 vowels in the password.
    test5 = 0 #The password has at least 1 alphabetic character
              #in either upper or lower case.
    test6 = 0 #Not all alphabetic characters are in the same
              #case (either all upper or all lower).

    # test1
    if first_pwd == second_pwd:
        test1 = 1

    password = first_pwd
    pwd_length = len(password)

    # test2
    if pwd_length >= 8:
        test2 = 1

    # test3

    same = 0

    if password[0].isalpha() and password[pwd_length-1].isalpha():
        if password[0] == password[pwd_length-1].upper():
            same = 1
        if password[0] == password[pwd_length-1].lower():
            same = 1
        if same == 0:
            test3 = 1

    else:
        test3 = 1

    # test4
    vowels = ["a","e","i","o","u","A","E","I","O","U"]
    count = 0
    max_vowels = 2
    for vowel in vowels:
        count = count + password.count(vowel)

    if count <= max_vowels:
        test4 = 1

    alpha_chars = []

    # test5
    for char in password:
        if char.isalpha():
            alpha_chars.append(char)
            test5 = 1

    # test6
    alpha_count = len(alpha_chars)
    upper_count = 0
    lower_count = 0
    for char in alpha_chars:
        if char == char.upper():
            upper_count = upper_count + 1
        if char == char.lower():
            lower_count = lower_count + 1

    if alpha_count != upper_count and \
       alpha_count != lower_count:
        test6 = 1

    test_count = test1 + test2 + test3 + test4 \
                 + test5 + test6

    if test_count == number_of_tests:
           return True

    return False

# Program Code

from tkinter import *

root_window = Tk()

# window title
root_window.title("Title")

# window size
root_window.geometry("400x200")

# label asking for password
pwd_label = Label(root_window, text="Please enter your password")
pwd_label.pack()

# pwd entry boxes

pwd1 = StringVar()
pwd1_text = Entry(root_window,textvariable=pwd1)
pwd1_text.pack()

pwd2 = StringVar()
pwd2_text = Entry(root_window,textvariable=pwd2)
pwd2_text.pack()

# pwd check button
check_btn = Button(root_window,text="Change Password",command=lambda: validate_password(pwd1, pwd2))
check_btn.pack()

root_window.mainloop()

##

After the function is called I want to print out the return from that function to the shell either True or False but need to get past the error first
I am still new to Python so my code likely needs some improvement.

A: Your code is passing Tkinter StringVars to the validate_password() function. You need to call the get() method of the StringVar to get a Python string. Like p1 = first_pwd.get().

A: In your validate_password function, you declare
password = first_pwd
pwd_length = len(password)

But you are passing in a StringVar as first_pwd.  The StringVar object has not length.  You need to .get() the text before passing to the function.


text:
Q: Creating Jar for SpringBoot Application with JSP pages using Gradle I have an SpringBoot Application which has few JSP pages within it. When I boot the main class from my eclipse it is working perfectly. But at the same time, when I package it as jar, the WEB-INF/jsp folder is not configured properly. I am stuck here. Request your help
Below is my Gradle script
buildscript {
    ext {
        springBootVersion = '1.5.4.RELEASE'
    }
    repositories {

        maven {
            url "https://plugins.gradle.org/m2/"
        }
}
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.arun'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

task packSSO(type: Jar) {
    manifest {
        attributes(
            'Implementation-Title': 'Arun Spring Boot Application',
            'Implementation-Version': version,
            'Built-By': System.getProperty('user.name'),
            'Built-Date': new Date(),
            'Main-Class':  'com.arun.MainGate',
            'Built-JDK': System.getProperty('java.version')
        )
    }
    sourceSets {
    main {
        resources {
            srcDirs "src/main/resources"
        }
    }
}
    baseName = project.name + '-all'
    from {
        configurations.compile.collect {
            it.isDirectory() ? it : zipTree(it)
        }
    }
    with jar
}

repositories {

        maven {
            url "https://plugins.gradle.org/m2/"
        }
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.springframework.boot:spring-boot-starter-tomcat')
    compile('org.apache.tomcat.embed:tomcat-embed-jasper')
    compile ('javax.servlet:jstl:1.2')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    testImplementation 'junit:junit:4.12'
}

I exploded the created Jar and the structure looks like below.

so when i run java -jar SSOPage-0.0.1-SNAPSHOT.jar  it couldn't find the JSP pages. What exact folder structure should i need to follow and how to package the WEB-INF in gradle ?

A: I think you must use WAR packaging for a Spring Boot application that uses JSPs. However, you can still use it like a self-contained executable JAR file, as in $ java -jar ./build/libs/hcro-pdi-1.0.0.war.
Here's my build.gradle file from a Spring Boot 2.0.1 project that uses JSPs.
plugins {
    id 'org.springframework.boot' version '2.0.1.RELEASE'
    id "io.spring.dependency-management" version "1.0.4.RELEASE"
}

apply plugin: 'org.springframework.boot'
apply plugin: 'war'

bootWar {
    baseName = 'hcro-pdi'
    version = '1.0.0'
}

gradle.projectsEvaluated {
    tasks.withType(JavaCompile) {
        options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
    }
}

repositories {
    mavenCentral()
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
    compile('org.springframework.boot:spring-boot-starter-jdbc')
    compile('javax.servlet:jstl')
    compile('org.apache.tomcat.embed:tomcat-embed-jasper')

    // Devtools enable hot-reloading of JSP and static content
    compile("org.springframework.boot:spring-boot-devtools")

    compile(group: 'org.mariadb.jdbc', name: 'mariadb-java-client', version: '2.2.0')
    compile(group: 'org.apache.commons', name: 'commons-lang3', version: '3.7')
    compile(group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.5')
    compile(group: 'joda-time', name: 'joda-time')
    compile(group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-joda')

    compileOnly('org.projectlombok:lombok')
    testCompile('org.springframework.boot:spring-boot-starter-test')

}

// When running in bootRun task, automatically reload static resources when changed
// https://docs.spring.io/spring-boot/docs/current/reference/html/build-tool-plugins-gradle-plugin.html#build-tool-plugins-gradle-running-applications
bootRun {
    jvmArgs "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"
    sourceResources sourceSets.main
}

And, you do have to add the two properties to application.properties shared by @Yogi.
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

A: You need to create application.properties under resources folder in your application and define below properties:
spring.mvc.view.prefix: /WEB-INF/jsp/ (your path for JSP files)
spring.mvc.view.suffix: .jsp

Sample MVC examples:

*

*http://www.springboottutorial.com/creating-web-application-with-spring-boot


text:
Q: range grouping list of strings and numbers I have a list looks like that
String[] lst = {BB,2,1,3,AA,DD,A3,A1,EE,A2,4);
I need to group & range that list, but having trouble with that,
need to find something like this as a result

result: (1-4),(A1-A3),(AA-BB),(DD-EE)

The code I came up with is this
Map<Character, List<String>> collect;

collect = Arrays.stream(str).
flatMap(s -> Stream.of(s.split("[^a-zA-Z0-9]"))).
filter(s -> !s.trim().isEmpty()).
sorted().
collect(Collectors.groupingBy(s -> s.charAt(0)));

but it groups by the first letter, which means AA grouped with A1-A3, and so on.
its not that trivial grouping, and I would appreciate any help.

A: As another user has mentioned in the comments, rolling your own solution is not straightforward. To solve this particular problem you can do something like
    String[] str = {"BB","2","1","3","AA","DD","A3","A1","EE","A2","4"};
    Map<String, List<String>> collect;

    collect = Arrays.stream(str)
            .flatMap(s -> Stream.of(s.split("[^a-zA-Z0-9]")))
            .filter(s -> !s.trim().isEmpty())
            .sorted()
            .collect(Collectors.groupingBy(s -> {
                final StringBuilder groupKey = new StringBuilder();
                char first = s.charAt(0);
                if (Character.isAlphabetic(first)) {
                    if (first >= 'D') {
                        groupKey.append("ALPHA-HIGH");
                    } else {
                        groupKey.append("ALPHA-LOW");
                    }
                } else {
                    groupKey.append("NON-ALPHA");
                }
                if (s.length() == 2) {
                    char second = s.charAt(1);
                    if (Character.isAlphabetic(second)) {
                        if (first >= 'D') {
                            groupKey.append("_ALPHA-HIGH");
                        } else {
                            groupKey.append("_ALPHA-LOW");
                        }
                    } else {
                        groupKey.append("_NON-ALPHA");
                    }
                }
                return groupKey.toString();
            }));

Which will give you the output you're looking for. Note that a key (String) is used instead of a single character.
What's going on here? You've got lots of different possible groups which I see as two macro-groups: alphabetic and non. The non alphabetic stuff in your case is numeric. The strings of length 2 can have the second character as alpha or as numeric. The alpha characters are considered "high" if they're D or greater.
Output
four groups:
NON-ALPHA: {1, 2, 3, 4}
ALPHA-LOW_NON-ALPHA: {A1, A2, A3}
ALPHA-HIGH_ALPHA-HIGH: {DD, EE}
ALPHA-LOW_ALPHA-LOW: {AA, BB}

A: To build such continious groups, you first need to define a function which taking two items identify if they follow each other, i.e. stand in continious order. E.g. "1" is followed by "2", but not by "3" nor "A"; "AA" is followed by "BB" in your example. Having such a function, you iterate over sorted list and comparing neghboring items decide whether to open a group, close it, or print an item standalone.
I'd call such function follows(String a, String b). Then the algotithm to build groups is as simple as:
static String printGroups(String[] items) {
  Arrays.sort(items);      // strictly saying, sorting order must be consistent with `follows`
  boolean open = false;    // a group is open currently
  StringBuilder result = new StringBuilder();
  for (int i = 0; i < items.length; ++i) {
    if (!open && i > 0) {
      result.append(',');
    }
    if (i < items.length - 1 && follows(items[i], items[i + 1])) {
      if (!open) {
        // open a group
        result.append('(').append(items[i]).append('-');
        open = true;
      }
    } else if (open) {
      // close the group
      result.append(items[i]).append(')');
      open = false;
    } else {
      // print a standalone item
      result.append(items[i]);
    }
  }
  return result.toString();
}

The follows function, adjusted to your example (looks awful, you may make it more clear/readable using java streams or StringUtils or whatever) --
static boolean follows(String a, String b) {
    if (a.length() != b.length() && a.length() == 0) {
        return false;
    }
    // AAA -> BBB
    if (allSame(a) && allSame(b) && (b.charAt(0) - a.charAt(0) == 1)) {
        return true;
    }
    // ABC1 -> ABC2
    // finding common prefix
    int p = 0;
    while (p < a.length() && a.charAt(p) == b.charAt(p)) {
        ++p;
    }
    return (p == a.length() - 1) && (b.charAt(p) - a.charAt(p) == 1);
}

static boolean allSame(String chars) {
    char s = chars.charAt(0);
    return chars.chars().allMatch(c -> s == c);
}

After that, you just split a text to items and feed:
printGroups("BB,2,1,3,AA,DD,A3,A1,EE,A2,4".split(","));  // (1-4),(A1-A3),(AA-BB),(DD-EE)

A: Here's my solution.
This will work for any given AdjacentAwareComparator so long as it's implemented correctly for its value space. The below comparator is for the value space you defined.
You can easily adapt getRanges to accept a List rather than array or to only store the first and last of a range if you don't want all the elements:
import static java.lang.Character.isDigit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Main {

    /**
     * Marker interface.
     *
     * Implementors MUST adhere to all contracts of Comparator, and MUST return -1 or 1 if and only if
     * the compared values are adjacent to one another within the set of all possible values.
     */
    @FunctionalInterface public interface AdjacentAwareComparator<T> extends Comparator<T> {};

    /**
     * Assumes the input is valid in the defined value space.
     *
     * Sort order: Digit (natural), Alpha+Digit (by alpha, then by digit), Alpha+Alpha (natural)
     */
    private static AdjacentAwareComparator<String> comparator = (x, y) -> {
        // uses 2 and -2 to compare values as non-adjacent
        if (x == null) return (y == null) ? 0 : -2;
        if (y == null) return 2;
        // both are not null...

        if (x.isEmpty()) return y.isEmpty() ? 0 : -2;
        if (y.isEmpty()) return 2;
        // both are at least length 1...

        char x1 = x.charAt(0), y1 = y.charAt(0);
        if (isDigit(x1)) return isDigit(y1) ? (x1 - y1) : -2;
        if (isDigit(y1)) return 2;
        // both start with letters...

        int d1 = x1 - y1; // delta between first chars
        char x2 = x.charAt(1), y2 = y.charAt(1);
        if (isDigit(x2)) return isDigit(y2) ? ((d1 == 0) ? (x2 - y2) : (d1 * 2)) : -2;
        if (isDigit(y2)) return 2;

        // the strings are double letters (eg. 'AA' and 'BB')
        return d1;
    };

    public static <T> List<List<T>> getRanges(T[] arr, AdjacentAwareComparator<T> comp) {
        if (arr.length == 0) {
            return new ArrayList<>();
        }
        List<List<T>> ranges = new ArrayList<>();
        List<T> range = new ArrayList<>();

        // sort using the custom Comparator
        Arrays.sort(arr, comp);
        T prev = arr[0];
        range.add(prev);

        // iterate through the sorted array
        for (int i = 1; i < arr.length; i++) {
            T curr = arr[i];
            int d = comp.compare(prev, curr);
            if (d < -1 || 1 < d) {
                // prev and curr are not adjacent nor equal, so start a new range
                ranges.add(range);
                range = new ArrayList<>();
            }
            range.add(curr);
            prev = curr;
        }
        ranges.add(range);
        return ranges;
    }

    public static void main(String[] args) {
        String[] arr = {"4","1","BB","ZZ","A1","5","A5","FF","3","B2","A2","B1","AA"};
        for (List<String> range : getRanges(arr, comparator)) {
            System.out.println("{" + String.join(", ", range) + "}");
        }
        // prints:
        //   {1}
        //   {3, 4, 5}
        //   {A1, A2}
        //   {A5}
        //   {B1, B2}
        //   {AA, BB}
        //   {FF}
        //   {ZZ}
    }
}


text:
Q: Determining Nvarchar length I've read all about varchar versus nvarchar. But I didn't see an answer to what I think is a simple question. How do you determine the length of your nvarchar column? For varchar it's very simple: my Description, for example, can have 100 characters, so I define varchar(100). Now I'm told we need to internationalize and support any language. Does this mean I need to change my Description column to nvarchar(200), i.e. simply double the length? (And I'm ignoring all the other issues that are involved with internationalization for the moment.)
Is it that simple?

A: From microsoft web site:
A common misconception is to think that NCHAR(n) and NVARCHAR(n), the n defines the number of characters. But in NCHAR(n) and NVARCHAR(n) the n defines the string length in byte-pairs (0-4,000). n never defines numbers of characters that can be stored. This is similar to the definition of CHAR(n) and VARCHAR(n).
The misconception happens because when using characters defined in the Unicode range 0-65,535, one character can be stored per each byte-pair. However, in higher Unicode ranges (65,536-1,114,111) one character may use two byte-pairs. For example, in a column defined as NCHAR(10), the Database Engine can store 10 characters that use one byte-pair (Unicode range 0-65,535), but less than 10 characters when using two byte-pairs (Unicode range 65,536-1,114,111). For more information about Unicode storage and character ranges, see
https://learn.microsoft.com/en-us/sql/t-sql/data-types/nchar-and-nvarchar-transact-sql?view=sql-server-ver15

A: Generally it is the same as for varchar really. The number is still the maximum number of characters not the data length.
nvarchar(100) allows 100 characters (which would potentially consume 200 bytes in SQL Server).
You might want to allow for the fact that different cultures may take more characters to express the same thing though.
An exception to this is however is if you are using an SC collation (which supports supplementary characters). In that case a single character can potentially take up to 4 bytes.
So worst case would be to double the character value declared.

A: @Musa Calgar - exactly right.   That link has the information for the answer to this question.
But to make sure the question itself is clear, we are talking about the 'length' attribute we see when we look at the column definition for a given table, right?  That is the storage allocated per column.  On the other hand, if we want to know the number of characters for a given string in the table at a given moment you can:
"SELECT myColumn, LEN(myColumn) FROM myTable"
But if the storage length is desired, you can drag the table name into the query window using SSMS, highlight it, and use 'Alt-F1' to see the defined lengths of each column.
So as an example, I created a table like this specifiying collations. (Latin1_General_100_CI_AS_SC allows for supplemental characters - that is, characters that take more than just 2 bytes):
CREATE TABLE [dbo].[TestTable1](
    [col1] [varchar](10)  COLLATE Latin1_General_100_CI_AS,
    [col2] [nvarchar](10) COLLATE Latin1_General_100_CI_AS_SC,
    [col3] [nvarchar](10) COLLATE Latin1_General_100_CI_AS
) ON [PRIMARY]

The lengths show up like this (Highlight  in query window and Alt-F1):
Column_Name    Type        Length  [...] Collation

col1           varchar      10           Latin1_General_100_CI_AS
col2           nvarchar     20           Latin1_General_100_CI_AS_SC
col3           nvarchar     20           Latin1_General_100_CI_AS

If you insert ASCII characters into the varchar and nvarchar fields, it will allow you to put 10 characters into all of them.  There will be an error if you try to put more than 10 characters into those fields:
"String or binary data would be truncated.
The statement has been terminated."
If you insert non-ASCII characters like 'ā' you can still put 10 of them into each one, but SQL Server will convert the values going into col1 to the closest known character that fits into 1-byte.  In this case, 'ā' will be converted to 'a'.
However, if you insert characters that require 4 bytes to store, like for example, '', you will only be allowed to put FIVE of them into the varchar and nvarchar fields.   Any more than that will result in the truncation error shown above.  The varchar field will show question marks because it has no single-byte character that it can convert that input to.
So when you insert five of these '', do a select of that row using len(<colname>) and you will see this:
col1          len(col1)    col2          len(col2)      col3           len(col3)
??????????    10                5                    10

So the length of col2 shows 5 characters since supplemental characters were defined when the table was created (see above CREATE TABLE DDL statement).  However, col3 did not have _SC for its collation, so it is showing length 10 for the five characters we inserted.
Note that col1 has ten question marks.  If we had defined the col1 varchar using the _SC collation instead of the non-supplemental one, it would behave the same way.


text:
Q: How to add child entity without parent in OneToOne bidirectional relationship I have 2 entities: Group and User.
Both are in OneToOne relationship, User is parent and Group is a child.
Problem is that I have an error when I save the group entity to the database:
org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.robert.app.ws.io.entity.GroupEntity.user]
Group entity:
    public class GroupEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(nullable = false, unique = true)
private String name;

@OneToMany(mappedBy = "group")
private List<ChildEntity> children;

//FK z tablicy users
@OneToOne
@MapsId
UserEntity user;

//getters and setters

User entity:
    public class UserEntity implements Serializable {

private static final long serialVersionUID = 8748598732973872010L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

@Column(nullable = false)
private String userId;

@Column(nullable = false, length = 50)
private String firstName;

@Column(nullable = false, length = 50)
private String lastName;

@Column(nullable = false, length = 15)
@Enumerated(EnumType.STRING)
private Gender gender;

@Column(nullable = false, length = 20)
private String pesel;

@Column(nullable = false, length = 20)
@Enumerated(EnumType.STRING)
private AccountType accountType;

@Column(nullable = false, length = 60)
private String address;

@Column(nullable = false, unique = true)
private String email;

private String encryptedPassword;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "user",
orphanRemoval = true)
private List<ChildEntity> children = new ArrayList<>();

@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
private GroupEntity group;

GroupServiceImlp class:
    @Override
    public GroupDto createGroup(GroupDto group) {

    GroupEntity groupEntity = new GroupEntity();
    BeanUtils.copyProperties(group, groupEntity);

    GroupEntity storedGroup = groupRepository.save(groupEntity);

    GroupDto returnValue = new GroupDto();
    BeanUtils.copyProperties(storedGroup, returnValue);

    return returnValue;
}

I want to create the group and assign the user to this group later (would like to do it in android application). I have a button where I just add new group to database. In another view I would like to match particular group which is already created, with the user.
I am sure I do not understand something related to relationships in JPA, but I am new in Spring, so thats why I am looking for help.

A: Remove the @MapsId in GroupEntity
By default, the entities are mapped by IDs. Your GroupEntity should look like that.
public class GroupEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private String name;

    @OneToMany(mappedBy = "group")
    private List<ChildEntity> children;

    //FK z tablicy users
    @OneToOne
    UserEntity user;

    .
    .
    .
}


text:
Q: How to check a list in Haskell? This is my code:
module Main where

import Data.Graph.Inductive
import Data.Graph.Inductive.Example

func :: Graph gr=> gr a b ->[Node]->Int-> [(Node,Int)]
func graph (x:xs) y
        |indeg graph x == 0 = (x,y+1):func (delNode x graph ) xs (y+1)

graph2:: Gr Int Int
graph2 = mkGraph (genLNodes 1 14)[(1,2,1),
                (1,3,1),
                (3,14,1),
                (14,6,1),
                (14,7,1),
                (2,4,1),
                (2,5,1),
                (4,6,1),
                (5,7,1),
                (6,8,1),
                (7,9,1),
                (8,10,1),
                (9,11,1),
                (10,12,1),
                (11,12,1),
                (12,13,1),
                (14,13,1)]

Graph2 have 14 nodes and e.g (1,2,1) means, edge from node 1 to node 2 with a weight of 1.
Func takes my Graph2, topological sorting vertices and some number e.g 0.
Func checks if  inward-bound degree of the Node is equal to 0 and creates list of tuples where x is IdNode and y is increasing when indeg graph x == 0 is true. The vertex is removed
And here is my problem, I want to see if more vertices has a degree of 0 and add 1.
EDIT:
The function should act as follow:
topsort: [1,3,14,2,5,7,9,11,4,6,8,10,12,13]

*

*check in-bound degree for each node in the list.

*if degree is equal 0, add 1 to path lenght ( node 1 in-bound is equal 0 so path length= 1)

*remove node from graph and  check in-bound degree of nodes after removing node and return to step 2.

continuing example:
after removing node 1, nodes 2 and 3 have in-bound = 0 so I add 1 to path length (path lenght = 2 for node 2 and 3 ) and I remove node 2 and 3.
Now in-bound degree =0 have 14,4,5 so I add 1 to path length (path lenght =3) and I remove these nodes and so on
I hope that the image of the graph will help.

A: With lazy evaluation you can use the "tie-the-knot" method to compute the depths very declaratively:
minOr0 [] = 0
minOr0 ds = minimum ds

depths :: Graph gr => gr a b  -> [(Node, Int)]
depths gr =
  let pairs = [ (x, depth x) | x <- nodes gr ]
      depth x = 1 + minOr0 [ d | y <- pre gr x, let Just d = lookup y pairs ]
  in pairs

test2 = depths graph2

The definition between pairs and depth is circular: evaluating a tuple in pairs calls depth. Calling depth will look up other tuples in pairs. If the graph does not have any cycles the process will eventually
terminate.
Due to the way lazy evaluation works in Haskell, the calls to depth
are effectively memoized.


text:
Q: Red5 - AS3 - Recording output sounds 'robotic' and distorted on some Android phones I am using Red5 with AS3 (Adobe AIR) for recording voice. I am following this tutorial for doing the same: http://sziebert.net/posts/server-side-stream-recording-updated/
When I deploy my builds on mobile it works fine on the iPhone and iPad. Even on Android it works fine on some phones like the Nexus, Samsung S2 and Sony Xperia. However, on some phones like the Motorola and some of the cheaper handsets, the recorded output sounds 'robotic' and is distorted.
My microphone settings on AS3 are:
m_microphoneReference = Microphone.getMicrophone();

m_microphoneReference.rate = 44;
m_microphoneReference.gain = 100;
//m_microphoneReference.setSilenceLevel(10);
m_microphoneReference.setUseEchoSuppression(true);

I fiddled around with the microphone bit rates in AS3 and sound was a bit better. But I am trying to find the reason for this distortion. Any pointers?

A: Since you're saying that there is an improvement in the quality when you lower the rate, that seems to indicate the phones in question are not up to the task. Nexus models are normally top-of-the-line so its no surprise that the perform well. I would suggest allowing a user to select the rate if they experience issues as well as informing them of potential issues with the "listed" devices and os versions.


text:
Q: Filter (searching) on Microsoft Azure (graph) API I would like to query the Microsoft Azure AD by passing either a mobile number or a postal code. I am able to filter using the givenName using the startsWith() function but not able to search with mobile/postal code.
My request is users?$filter=postalCode%20eq%20'560036'&api-version=1.6
and getting the response:
{
  "odata.error": {
    "code": "Request_UnsupportedQuery",
    "message": {
      "lang": "en",
      "value": "Unsupported or invalid query filter clause specified for property 'postalCode' of resource 'User'."
    }
  }
}

A: My issue was that I was trying this on an Azure AD B2C tenant. This is not supported on this type of tenant.
I've missed the note in the docs about this:
https://learn.microsoft.com/en-us/graph/aad-advanced-queries?tabs=http
The note's text is below:

A: According to this old post in Microsoft Developer you can add OR clause to filter more than one field if you use startsWith() function.

users?$filter=startswith(postalCode, '560036') OR startswith(mobileNumber, '123456')

Of course, you still have to encode equal sign, parenthesis and spaces


text:
Q: PyCharm Unresolved reference 'print' I started to learn python language, and decided to try out PyCharm IDE, which looks really nice. But, whenever I write print it says "Unresolved reference 'print'". I can run the program, but this red-underline is really annoying. How can I fix this?

A: If you're in PyCharm and you're getting "Unresolved reference xrange" it's because xrange was removed in Python 3. Range takes over its functionality now. Was working on fast string concat from here:
https://waymoot.org/home/python_string/
And credit for the answer is from /r/learnpython:
https://www.reddit.com/r/learnpython/comments/2udj3s/pycharm_issue/

A: This could be related to the version of python you are using. Under python 2.x print is a statement:
print "hello world"

Under python 3, print is now a function call:
print("hello world")

A: Same problem, I deleted the .idea and __pycache__ directories in the project directory and everything was fine :)

A: Just delete .idea folder from your project directory.

A: I have had the same problem as you, even though I configured Python 3.4.0 as the project's interpreter and all print's in the code were Python 3 compliant function calls.
I got it sorted out by doing this in PyCharm:

File -> Invalidate Caches / Restart... -> Invalidate and Restart


text: Q: how to share a image using instagram in background without opening app share dialog I am developing an app that has a functionality for sharing a image in facebook and instagram.once user clicked share button for both facebook and instagram it first check whether app is installed on our device as well check whether user login on the app.once the checking is completed the image hase to be posted on those app without opening facebook and instagram app.can anyone tell me the code for doing such functionality.Thanks in advance.


text:
Q: Making a Log Heatmap with ggplot2 I currently have a data frame of frequencies and would like to make a heatmap. The Heat map that I have is not in-depth enough, and I am unsure of how to cluster the data by rows and by columns. What else should I add to my code?
Here is some sample data, to give a solid example, the first 6 rows of my .txt file:
df <- matrix(c("cdr3aa", "Ana-Wk0-CD4", "Ana-Wk27-CD4", "Ana-Wk0-CD8", "Ana-Wk27-CD8", "nonshared", "shared",
 "CASSLSPSTGNYGYTF", 1.12E-05, 0, 0.067313861, 0.049220624, 0.188215557, 0,
 "CASCSRTSTDTQYF", 0, 3.19E-06, 0.065083991, 0.034558507, 0.105607859, 0,
 "CASGGQG_GNQPQHF", 4.61E-04, 2.98E-04, 0, 0, 0.079950136, 0,
 "CASRLRTGYDTEAFF", 7.50E-06, 6.38E-06, 0.057943843, 0.047042366, 0.073757427, 0,
 "CAISEWDRAGELFF", 3.75E-06, 1.12E-05, 0.069951496, 0.060104224, 0.060978181, 0,
 "CASSFPIREESSYNEQFF", 0, 0, 0.018718651, 0.015058722, 0.023803322, 0), ncol = 7, byrow = TRUE)

This is what I currently have so far:
#Input of data
df <- read.table("TESTING.txt", header=TRUE, comment.char="", sep = "\t")
#Removing the first row
result <-df[-1]
#Setting the rownames as the CDR3 sequences
row.names(result) <- df$cdr3aa

#Making the HeatMap
dt2 <- result %>%
   rownames_to_column() %>%
   gather(colname, value, -rowname)
head(dt2)

ggplot(dt2, aes(x = colname, y = rowname, fill = value)) +
   geom_tile()

This gives me a heatmap like so:

Now, I am trying to make my heatmap more like this:

As you can see, this heatmap has the clustering of rows that I am looking for and the color scheme that I would like.
I am also guessing that a proper heatmap is done on a logarithmic scale. The first pic is not like that, and I apologize. I know that I am close to my goal but I am unsure on how to proceed to get to the final result. I would like to keep the format of the first pic; all I would have to do is put "Sample ID" as the x title and "CDR3AA" as the y title. Any help for this would be greatly appreciated. I am still learning R, so anything that there is to learn I am willing to learn it. Thx!

A: I am also guessing that a proper heatmap is done on a logarithmic scale.
You can do heatmap with log-transformed data, but basically you can also use other transformations - as long as the values will be normalized.
You can do a log-transformation for a dataframe column like this:
df$log_col <- log(df$col)

or like this:
df$log10_col <- log10(df$col)

NB: You read the data as dataframe while your data sample/example uses the matrix, which are different structures.


text:
Q: Ubuntu 22.04 hung when shutdown or reboot Recently my laptop(Y9000P 2022 Lenovo) always hung when shutdown or restart. the screen shows info:
[15105.071402] INFO: task systemd-shutwod:1 blocked for more than 120 seconds.
[15105.071424]       Tainted: P        W  OE     5.15.0-41-generic #44-Ubuntu
[15105.071430] "echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this message.

And I look up the key words "120 seconds" under the folder /var/log/. and found that :
**./syslog.1:73594:Jul 27 14:12:06 damon-Y9000P kernel: [15105.071402] INFO: task gpu-manager:17668 blocked for more than 120 seconds.**
./syslog.1:74318:Jul 27 14:20:10 damon-Y9000P kernel: [15588.399811] INFO: task gpu-manager:19212 blocked for more than 120 seconds.
**./kern.log.1:15467:Jul 27 14:12:06 damon-Y9000P kernel: [15105.071402] INFO: task gpu-manager:17668 blocked for more than 120 seconds.**
./kern.log.1:15719:Jul 27 14:20:10 damon-Y9000P kernel: [15588.399811] INFO: task gpu-manager:19212 blocked for more than 120 seconds.

I looked the syslog.1 and kern.log.1, there are same backtrace info:
73594 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071402] INFO: task gpu-manager:17668 blocked for more than 120 seconds.
 73595 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071424]       Tainted: P        W  OE     5.15.0-41-generic #44-Ubuntu
 73596 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071430] "echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this message.
 73597 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071435] task:gpu-manager     state:D stack:    0 pid:17668 ppid: 17667 flags:0x00000002
 73598 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071449] Call Trace:
 73599 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071454]  <TASK>
 73600 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071463]  __schedule+0x23d/0x590
 73601 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071478]  ? path_init+0x3a2/0x3e0
 73602 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071489]  schedule+0x4e/0xb0
 73603 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071496]  schedule_preempt_disabled+0xe/0x10
 73604 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071503]  __mutex_lock.constprop.0+0x263/0x490
 73605 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071511]  __mutex_lock_slowpath+0x13/0x20
 73606 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071518]  mutex_lock+0x34/0x40
 73607 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071524]  control_store+0x28/0x90
 73608 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071535]  dev_attr_store+0x14/0x30
 73609 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071546]  sysfs_kf_write+0x3b/0x50
 73610 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071556]  kernfs_fop_write_iter+0x134/0x1c0
 73611 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071565]  new_sync_write+0x114/0x1a0
 73612 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071577]  vfs_write+0x1cd/0x260
 73613 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071586]  ksys_write+0x67/0xe0
 73614 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071592]  __x64_sys_write+0x19/0x20
 73615 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071597]  do_syscall_64+0x59/0xc0
 73616 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071604]  ? syscall_exit_to_user_mode+0x27/0x50
 73617 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071612]  ? __x64_sys_newfstatat+0x1c/0x20
 73618 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071621]  ? do_syscall_64+0x69/0xc0
 73619 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071626]  ? exit_to_user_mode_prepare+0x37/0xb0
 73620 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071637]  ? syscall_exit_to_user_mode+0x27/0x50
 73621 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071643]  ? __x64_sys_newfstatat+0x1c/0x20
 73622 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071651]  ? do_syscall_64+0x69/0xc0
 73623 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071656]  ? exit_to_user_mode_prepare+0x37/0xb0
 73624 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071663]  ? syscall_exit_to_user_mode+0x27/0x50
 73625 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071670]  ? __x64_sys_close+0x11/0x40
 73626 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071677]  ? do_syscall_64+0x69/0xc0
 73627 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071682]  ? do_syscall_64+0x69/0xc0
 73628 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071686]  ? __x64_sys_newfstatat+0x1c/0x20
 73629 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071694]  ? do_syscall_64+0x69/0xc0
 73630 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071699]  ? do_syscall_64+0x69/0xc0
 73631 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071703]  entry_SYSCALL_64_after_hwframe+0x44/0xae
 73632 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071714] RIP: 0033:0x7fb4e84bea37
 73633 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071722] RSP: 002b:00007ffe4172f668 EFLAGS: 00000246 ORIG_RAX: 0000000000000001
 73634 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071731] RAX: ffffffffffffffda RBX: 0000000000000005 RCX: 00007fb4e84bea37
 73635 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071737] RDX: 0000000000000005 RSI: 000055782c7070e0 RDI: 0000000000000004
 73636 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071741] RBP: 000055782c7070e0 R08: 0000000000000000 R09: 000055782c7070e0
 73637 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071745] R10: 000055782c7080e0 R11: 0000000000000246 R12: 0000000000000005
 73638 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071748] R13: 000055782c6ee4b0 R14: 00007fb4e85c0600 R15: 00007fb4e85bfa00
 73639 Jul 27 14:12:06 damon-Y9000P kernel: [15105.071755]

How can i to fix this issue?
thanks!


text: Q: The Eclipse executable launcher was unable to locate its companion shared library. dual boot system My eclipse won't open, complaining about not being able to find its companion shared library. I tried uninstalling it and reinstalling it but it doesn't help. I think it may be because I have a dual boot system and have tried to install most things to my hard drive for windows and linux to both access. I have tried looking on similar forum posts about this issue and they don't seem to help.


text:
Q: Obtaining a token using IHttpclientFactory I've written the code below in IhttpclientFactory. For some reasons, the code is not returning a token. oauth is returning null.
I will appreciate it if someone would kindly have a look and tell me where I've gone wrong. thank you
    private async Task<OAuth>Authenticate()
    {
        //build request
        var request = new HttpRequestMessage(HttpMethod.Post, "/oauth/token");

        request.Content = new StringContent(JsonSerializer.Serialize(new OAuth() {grant_type="client_credentials",client_id="",client_secret=""}));

        request.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/x-www-urlencoded");

        //build client
        var client = _clientFactory.CreateClient();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/+json"));

        // send the request
        var response = await client.SendAsync(request);

        OAuth oauth = null;

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStringAsync();
            //deserialise

            var oAuth = Newtonsoft.Json.JsonConvert.DeserializeObject<OAuth>(responseStream);
        }
        return oauth;
    }

}

A: You've got two different OAuth variables 'oauth' and 'oAuth'.  C# identifiers are case-sensitive.
Should be something like
    if (!response.IsSuccessStatusCode)
    {
       throw new InvalidOperationExeption($"OAuth Request Failed With Status code {response.StatusCode}");
    }
    var responseString = await response.Content.ReadAsStringAsync();
    var oAuth = Newtonsoft.Json.JsonConvert.DeserializeObject<OAuth>(responseString);
    return oAuth;


text:
Q: mcrypt and PHPUnit I am using PHPUnit to test a project where mcrypt is heavily used. I have installed phpunit using this SO answer.
Whenever I try and run phpunit, I get the following error:
Fatal error: Call to undefined function mcrypt_create_iv() in
/files/file/using/mcrypt/thing.php on line 20

How can I fix this error? Do I have to install mcrpyt especially for PHPUnit?

A: You can either install MCrypt (which you should do anyway) or mark that specific test as one requiring MCrypt. The latter will cause the test to be skipped if you don't have MCrypt installed.


text:
Q: Atualizar model parcialmente com WebAPI2 Estou começando a desenvolver uma API REST usando ASP.NET WebAPI2.
No meu controller, estou usando o método PATCH para aplicar mudanças parciais a um model.
Tenho um método que está desta forma
[HttpPatch]
[ResponseType(typeof(void))]
public IHttpActionResult EditarNome(int id, string novoNome)
{
    var cliente = _db.Clientes.Find(id);

    if (cliente == null)
    {
        return NotFound();
    }

    cliente.Nome = novoNome;

    _db.Entry(cliente).State = EntityState.Modified;
    _db.SaveChanges();

    return StatusCode(HttpStatusCode.NoContent);
}

Este método, recebe como parâmetro um novo nome e atualiza a propriedade Nome do model.
Na hora de fazer a requisição o endpoint fica
api/Clientes/1?novoNome=JoaquimAlbertoSilva
Seguindo essa lógica, eu precisaria criar mais três métodos, para poder dar a opção do cliente editar apenas estas 4 propriedades do model Cliente.
As minhas dúvidas são:

*

*Esta abordagem esta certa? Devo fazer apenas um método?

*Seria melhor eu definir uma rota para cada tipo de alteração? Algo como:
api/Clientes/1/EditarNome/{novoNome}
api/Clientes/1/EditarApelido/{novoApelido}

A:
Esta abordagem está certa?

Sim, segundo respaldo do RFC 5789, que explica como e quando usar o PATCH.

Devo fazer apenas um método?

Se a atualização parcial exigir apenas um método, sim. Se você precisar de outros tipos de atualização parcial, terá de fazer mais métodos ou usar o objeto Delta<T> (conforme a resposta do @carlosfigueira).

Seria melhor eu definir uma rota para cada tipo de alteração?

Sim, eu diria que é uma abordagem das mais elegantes. Deixar tudo num método só também é uma opção, mas pode subir enormemente a complexidade.
Importante!
Não existe meio-patch. Se fizer um patch, certifique-se de usar todos os atributos passados para o método. Qualquer coisa diferente disso é melhor usar PUT (se for uma atualização do objeto inteiro) ou POST.

A: Com essa abordagem você está sub-utilizando o poder do PATCH. A principal vantagem desse verbo é que o cliente pode enviar somente os atributos a serem alterados, e isso pode ser feito no mesmo resource. Criar uma nova rota para cada atributo significa mais código que o necessário.
O que você precisa usar é o tipo Delta<T> (você precisa incluir um novo pacote do NuGet, Microsoft.AspNet.WebApi.OData). Se você tem uma operação que recebe um parâmetro desse tipo, ele vai conter somente os parâmetros passados pelo cliente, e você pode chamara o método Patch, que aplica tais alterações, como no exemplo abaixo.
[HttpPatch]
[ResponseType(typeof(void))]
public IHttpActionResult EditarNome(int id, Delta<Cliente> alteracoes)
{
    var cliente = _db.Clientes.Find(id);

    if (cliente == null)
    {
        return NotFound();
    }

    alteracoes.Patch(cliente);
    _db.SaveChanges();

    return StatusCode(HttpStatusCode.NoContent);
}

Com esse método, o cliente pode enviar requisições PATCH para qualquer parte do registro a ser alterado. Por exemplo:
PATCH /api/Clientes/1
Content-Type: application/json
Outros-Headers: ...

{ "Nome": "Nome alterado" }

ou também:
PATCH /api/Clientes/1
Content-Type: application/json
Outros-Headers: ...

{ "Apelido": "Novo apelido" }

E você não precisa ter mais de um método para realizar a mesma função (atualizar o objeto no servidor).


text:
Q: c program to print look and say sequence this is my code the actual output and required output differs slightly.
in actual output each number is getting printed at new row.
but i want output to be printed in single row separated by space.
Required output
Sample Input :
1 8
Sample Output:
1 11 21 1211 111221 312211 13112221 1113213211
my code is here
#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *a = malloc(2), *b = 0, *x, c;
    int cnt, len = 1,i=1,lim,s;
  scanf("%d",&s);
 scanf("%d",&lim);
    for (sprintf(a, "%d",s); (b = realloc(b, len * 2 + 1)); a = b, b = x)
    {
        puts(x = a);
        for (len = 0, cnt = 1; (c = *a); )
        {
            if (c == *++a)
                cnt++;
            else if (c)
            {
                len += sprintf(b + len, "%d%c", cnt, c);
                cnt = 1;

            }

        }
      if(i==lim)
        break;
      i++;
    }

    return 0;
}

my output
input > 1

8

output> 1
11
21
1211
111221
312211
13112221
1113213211

A: Use
 printf("%s ",a);

instead of
 puts(x = a);

A:
puts automatically appends a newline. If that's not what you want, you can fputs your string to stdout or use printf.

 fputs(x=a,stdout);

or
 printf("%s ",a);


text:
Q: Save individual files for each dataflow PCollection item In Google's apache-beam dataflow pipeline one can write data to a textfile, the apache-beam's website makes note of the possibility to write "multiple output files" here but the code is the same as for aggregate files (and that's all I get).
Is it possible to generate a file for each item in a PCollection?

A: You can do this yourself by mapping the PCollection with a ParDo that takes an element and writes it to a file using the FileSystems API. The Java version of the API is here, the Python verison is here; in the Java version, you'll need to use FileSystems.open().
Note that likely your pipeline will be vulnerable to issues in case your workers fail and the work gets retried, in that case you may have leftover garbage files from failed attempts.
For a more general solution, you'll need to wait until http://s.apache.org/fileio-write which is currently being implemented and will be released in Beam Java 2.2.


text:
Q: Airflow Dag Run Stalls Mid-Run I have setup airflow v1.10.6 on ubuntu, using python 3.6.8. and have written a simple practice dag that runs a set of 30 parallel tasks. I'm triggering the dag through the UI as this will be run irregularly and I'm just learning.  I'm now configured to LocalExecutor, parallelism=4 in airflow.cfg (full cfg file is below).  The dag run starts and can be viewed in the UI, completes exactly 4 task instances, then the dag run appears to stall in the UI, all other downstream tasks hold either scheduled or no_status forever. If I reset everything, bump up parallelism=10 in airflow.cfg, and re-trigger the run, 10 task instances run and the dag run stalls again in the same way. When the run appears to stall on the UI, I see no errors in the scheduler logs, or webserver logs and the cpus sure looks like the machine is running tasks.  I get the exact same behavior running this dag on CeleryExecutor and running airflow worker as well. Also seems to occur regardless of whether I have schedule_interval=None or timedelta(days=1).
Not to state the obvious but, as I understand it, "parallelism" means as the first 4 tasks instances finish, then others should be able to open up.  Any ideas as to why I am getting this behavior?
Perhaps a sidenote, perhaps not: I have also installed rabbitmq-server for use with Celery and am running the database on an AWS RDS instance in the same vpc.
DAG is below:
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.python_operator import PythonOperator
from datetime import datetime, timedelta
import time
default_args = {
    'owner': 'airflow',
    'depends_on_past': True,
    'start_date': datetime(2019, 6, 1),
    'email': ['airflow@example.com','evanburgess@gmail.com'],
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=1),
}

dag = DAG('example', default_args=default_args, schedule_interval=timedelta(days=1))

def do_a_process(flname, i, j):
    time.sleep(5)

mkarr = PythonOperator(
    task_id='make_random_array',
    default_args=default_args,
    python_callable=do_a_process,
    op_args=('filepath',10000,10000),
    dag=dag)

for i in range(30):

    smo = PythonOperator(
        task_id='gaussian_%i_sigma' % i,
        default_args=default_args,
        python_callable=do_a_process,
        op_args=('fileapth', i, i),
        dag=dag
    )

    stat = PythonOperator(
        task_id='stats_%i_sigma' % i,
        default_args=default_args,
        python_callable=do_a_process,
        op_args=('fileapth', i, i),
        dag=dag
    )
    mkarr >> smo
    smo >> stat

And my complete config file (comments removed)is below as well:
[core]
dags_folder = /home/ubuntu/airflow/dags
base_log_folder = /home/ubuntu/airflow/logs
remote_logging = False
remote_log_conn_id =
remote_base_log_folder =
encrypt_s3_logs = False
logging_level = INFO
fab_logging_level = WARN
logging_config_class =
colored_console_log = True
colored_log_format = [%%(blue)s%%(asctime)s%%(reset)s] {%%(blue)s%%(filename)s:%%(reset)s%%(lineno)d} %%(log_color)s%%(levelname)s%%(re
set)s - %%(log_color)s%%(message)s%%(reset)s
colored_formatter_class = airflow.utils.log.colored_log.CustomTTYColoredFormatter
log_format = [%%(asctime)s] {%%(filename)s:%%(lineno)d} %%(levelname)s - %%(message)s
simple_log_format = %%(asctime)s %%(levelname)s - %%(message)s
log_filename_template = {{ ti.dag_id }}/{{ ti.task_id }}/{{ ts }}/{{ try_number }}.log
log_processor_filename_template = {{ filename }}.log
dag_processor_manager_log_location = /home/ubuntu/airflow/logs/dag_processor_manager/dag_processor_manager.log
hostname_callable = socket:getfqdn
default_timezone = utc
executor = LocalExecutor
sql_alchemy_conn = postgresql+psycopg2://airflow:mypassword@my_url_rds.amazonaws.com:5432/airflow
sql_engine_encoding = utf-8
sql_alchemy_pool_enabled = True
sql_alchemy_pool_size = 5
sql_alchemy_max_overflow = 10
sql_alchemy_pool_recycle = 1800
sql_alchemy_pool_pre_ping = True
sql_alchemy_schema =
parallelism = 4
dag_concurrency = 4
dags_are_paused_at_creation = True
max_active_runs_per_dag = 1
load_examples = False
plugins_folder = /home/ubuntu/airflow/plugins
fernet_key = bighexadecimal
donot_pickle = False
dagbag_import_timeout = 30
dag_file_processor_timeout = 50
task_runner = StandardTaskRunner
default_impersonation =
security =
secure_mode = False
unit_test_mode = False
task_log_reader = task
enable_xcom_pickling = True
killed_task_cleanup_time = 60
dag_run_conf_overrides_params = False
worker_precheck = False
dag_discovery_safe_mode = True
default_task_retries = 0
[cli]
api_client = airflow.api.client.local_client
endpoint_url = http://localhost:8080
[api]
auth_backend = airflow.api.auth.backend.default
[lineage]
backend =
[atlas]
sasl_enabled = False
host =
port = 21000
username =
password =
[operators]
default_owner = airflow
default_cpus = 1
default_ram = 512
default_disk = 512
default_gpus = 0
[hive]
default_hive_mapred_queue =
[webserver]
base_url = http://localhost:8080
web_server_host = 0.0.0.0
web_server_port = 8080
web_server_ssl_cert =
web_server_ssl_key =
web_server_master_timeout = 120
web_server_worker_timeout = 120
worker_refresh_batch_size = 1
worker_refresh_interval = 30
secret_key = temporary_key
workers = 4
worker_class = sync
access_logfile = -
error_logfile = -
expose_config = False
authenticate = False
filter_by_owner = False
owner_mode = user
dag_default_view = tree
dag_orientation = LR
demo_mode = False
log_fetch_timeout_sec = 5
hide_paused_dags_by_default = False
page_size = 100
rbac = False
navbar_color = #007A87
default_dag_run_display_number = 25
enable_proxy_fix = False
cookie_secure = False
cookie_samesite =
default_wrap = False
[email]
email_backend = airflow.utils.email.send_email_smtp
[smtp]
smtp_host = localhost
smtp_starttls = True
smtp_ssl = False
smtp_port = 25
smtp_mail_from = airflow@example.com
[sentry]
sentry_dsn =
[celery]
celery_app_name = airflow.executors.celery_executor
worker_concurrency = 16
worker_log_server_port = 8793
broker_url = pyamqp://test:test@localhost:5672/
result_backend = db+postgresql://airflow:snowSNOWsnowSNOW@processing-1.cdpofxkpfulr.us-west-2.rds.amazonaws.com:5432/airflow
flower_host = 0.0.0.0
flower_url_prefix =
flower_port = 5555
flower_basic_auth =
default_queue = default
sync_parallelism = 0
celery_config_options = airflow.config_templates.default_celery.DEFAULT_CELERY_CONFIG
ssl_active = False
ssl_key =
ssl_cert =
ssl_cacert =
pool = prefork
[celery_broker_transport_options]
[dask]
cluster_address = 127.0.0.1:8786
tls_ca =
tls_cert =
tls_key =
[scheduler]
job_heartbeat_sec = 5
scheduler_heartbeat_sec = 5
run_duration = -1
num_runs = -1
processor_poll_interval = 1
min_file_process_interval = 0
dag_dir_list_interval = 300
print_stats_interval = 30
scheduler_health_check_threshold = 30
child_process_log_directory = /home/ubuntu/airflow/logs/scheduler
scheduler_zombie_task_threshold = 300
catchup_by_default = True
max_tis_per_query = 512
statsd_on = False
statsd_host = localhost
statsd_port = 8125
statsd_prefix = airflow
statsd_allow_list =
max_threads = 2
authenticate = False
use_job_schedule = True
[ldap]
uri =
user_filter = objectClass=*
user_name_attr = uid
group_member_attr = memberOf
superuser_filter =
data_profiler_filter =
bind_user = cn=Manager,dc=example,dc=com
bind_password = insecure
basedn = dc=example,dc=com
cacert = /etc/ca/ldap_ca.crt
search_scope = LEVEL
ignore_malformed_schema = False
[mesos]
master = localhost:5050
framework_name = Airflow
task_cpu = 1
task_memory = 256
checkpoint = False
authenticate = False
[kerberos]
ccache = /tmp/airflow_krb5_ccache
principal = airflow
reinit_frequency = 3600
kinit_path = kinit
keytab = airflow.keytab
[github_enterprise]
api_rev = v3
[admin]
hide_sensitive_variable_fields = True
[elasticsearch]
host =
log_id_template = {dag_id}-{task_id}-{execution_date}-{try_number}
end_of_log_mark = end_of_log
frontend =
write_stdout = False
json_format = False
json_fields = asctime, filename, lineno, levelname, message
[elasticsearch_configs]
use_ssl = False
verify_certs = True
[kubernetes]
worker_container_repository =
worker_container_tag =
worker_container_image_pull_policy = IfNotPresent
delete_worker_pods = True
worker_pods_creation_batch_size = 1
namespace = default
airflow_configmap =
dags_in_image = False
dags_volume_subpath =
dags_volume_claim =
logs_volume_subpath =
logs_volume_claim =
dags_volume_host =
logs_volume_host =
env_from_configmap_ref =
env_from_secret_ref =
git_repo =
git_branch =
git_subpath =
git_user =
git_password =
git_sync_root = /git
git_sync_dest = repo
git_dags_folder_mount_point =
git_ssh_key_secret_name =
git_ssh_known_hosts_configmap_name =
git_sync_credentials_secret =
git_sync_container_repository = k8s.gcr.io/git-sync
git_sync_container_tag = v3.1.1
git_sync_init_container_name = git-sync-clone
git_sync_run_as_user = 65533
worker_service_account_name =
image_pull_secrets =
gcp_service_account_keys =
in_cluster = True
affinity =
tolerations =
kube_client_request_args = {"_request_timeout" : [60,60] }
run_as_user =
fs_group =
[kubernetes_node_selectors]
[kubernetes_annotations]
[kubernetes_environment_variables]
[kubernetes_secrets]
[kubernetes_labels]

Here are my requirements:
alembic==1.3.0
amqp==2.5.2
apache-airflow==1.10.6
apispec==3.1.0
argcomplete==1.10.0
asn1crypto==0.24.0
atomicwrites==1.3.0
attrs==19.3.0
Automat==0.6.0
Babel==2.7.0
bcrypt==3.1.7
billiard==3.6.1.0
blinker==1.4
boto3==1.7.84
botocore==1.10.84
cached-property==1.5.1
cachetools==3.1.1
celery==4.3.0
certifi==2019.9.11
cffi==1.13.2
chardet==3.0.4
Click==7.0
cloud-init==19.2
colorama==0.4.1
colorlog==4.0.2
command-not-found==0.3
configobj==5.0.6
configparser==3.5.3
constantly==15.1.0
croniter==0.3.30
cryptography==2.8
defusedxml==0.6.0
dill==0.3.1.1
distro-info===0.18ubuntu0.18.04.1
dnspython==1.16.0
docutils==0.15.2
ec2-hibinit-agent==1.0.0
eventlet==0.25.1
Flask==1.1.1
Flask-Admin==1.5.3
Flask-AppBuilder==1.13.1
Flask-Babel==0.12.2
Flask-Bcrypt==0.7.1
Flask-Caching==1.3.3
Flask-JWT-Extended==3.24.1
Flask-Login==0.4.1
Flask-OpenID==1.2.5
Flask-SQLAlchemy==2.4.1
flask-swagger==0.2.13
Flask-WTF==0.14.2
flower==0.9.3
funcsigs==1.0.0
future==0.16.0
gevent==1.4.0
google-api-core==1.14.3
google-api-python-client==1.7.11
google-auth==1.7.0
google-auth-httplib2==0.0.3
google-auth-oauthlib==0.4.1
google-cloud-bigquery==1.21.0
google-cloud-bigtable==0.33.0
google-cloud-container==0.3.0
google-cloud-core==1.0.3
google-cloud-dlp==0.12.1
google-cloud-language==1.3.0
google-cloud-spanner==1.9.0
google-cloud-speech==1.2.0
google-cloud-storage==1.22.0
google-cloud-texttospeech==0.5.0
google-cloud-translate==2.0.0
google-cloud-videointelligence==1.11.0
google-cloud-vision==0.39.0
google-resumable-media==0.4.1
googleapis-common-protos==1.6.0
graphviz==0.13.2
greenlet==0.4.15
grpc-google-iam-v1==0.11.4
grpcio==1.25.0
grpcio-gcp==0.2.2
gunicorn==19.9.0
hibagent==1.0.1
httplib2==0.14.0
hyperlink==17.3.1
idna==2.8
importlib-metadata==0.23
incremental==16.10.1
iso8601==0.1.12
itsdangerous==1.1.0
Jinja2==2.10.3
jmespath==0.9.4
json-merge-patch==0.2
jsonpatch==1.16
jsonpointer==1.10
jsonschema==3.1.1
keyring==10.6.0
keyrings.alt==3.0
kombu==4.6.6
language-selector==0.1
lazy-object-proxy==1.4.3
librabbitmq==2.0.0
lockfile==0.12.2
Mako==1.1.0
Markdown==2.6.11
MarkupSafe==1.1.1
marshmallow==2.19.5
marshmallow-enum==1.5.1
marshmallow-sqlalchemy==0.18.0
monotonic==1.5
more-itertools==7.2.0
netifaces==0.10.4
numpy==1.17.4
oauthlib==3.1.0
ordereddict==1.1
packaging==19.2
PAM==0.4.2
pandas==0.25.3
pandas-gbq==0.11.0
paramiko==2.6.0
pendulum==1.4.4
pika==0.13.0
pluggy==0.13.0
prison==0.1.0
protobuf==3.10.0
psutil==5.6.5
psycopg2==2.7.7
py==1.8.0
PyAMQP==0.0.8.5
pyasn1==0.4.7
pyasn1-modules==0.2.7
pycparser==2.19
pycrypto==2.6.1
pydata-google-auth==0.1.3
Pygments==2.4.2
pygobject==3.26.1
PyJWT==1.7.1
PyNaCl==1.3.0
pyOpenSSL==19.0.0
pyparsing==2.4.5
pyrsistent==0.15.5
pyserial==3.4
pysftp==0.2.9
pytest==5.2.2
python-apt==1.6.4
python-daemon==2.1.2
python-dateutil==2.8.1
python-debian==0.1.32
python-editor==1.0.4
python3-openid==3.1.0
pytz==2019.3
pytzdata==2019.3
pyxdg==0.25
PyYAML==5.1.2
requests==2.22.0
requests-oauthlib==1.3.0
requests-unixsocket==0.1.5
rsa==4.0
s3transfer==0.1.13
scipy==1.3.2
SecretStorage==2.3.1
service-identity==16.0.0
setproctitle==1.1.10
six==1.13.0
SQLAlchemy==1.3.10
ssh-import-id==5.7
sshtunnel==0.1.5
systemd-python==234
tabulate==0.8.5
tenacity==4.12.0
termcolor==1.1.0
text-unidecode==1.2
thrift==0.11.0
tornado==5.1.1
Twisted==17.9.0
tzlocal==1.5.1
ufw==0.36
unattended-upgrades==0.1
unicodecsv==0.14.1
uritemplate==3.0.0
urllib3==1.25.6
vine==1.3.0
wcwidth==0.1.7
Werkzeug==0.16.0
WTForms==2.2.1
zipp==0.6.0
zope.deprecation==4.4.0
zope.interface==4.3.2

A: All I can say is if you run into this issue, work again on your install.  I used pip3 to install all but rabbitmq-server, for that I installed using apt on ubuntu.  Anaconda gave me issues.


text:
Q: Converter um IPAddress para string Este código obtém o gateway padrão, porém eu não consigo converter o resultado para string e colocar em um label.
public static IPAddress GetDefaultGateway()
{
    var card = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault();
    if(card == null) return null;
    var address = card.GetIPProperties().GatewayAddresses.FirstOrDefault();
    return address.Address;
}

Estou tentando assim:
IPAddress gatway;
gatway = GetDefaultGateway();
if(gatway != null)
{
    label8.Text = gatway.Address.ToString(); //Aqui da erro...
}

A: Essa propriedade é obsoleta. Utilize o método GetAddressBytes() que retornará um array de bytes com cada parte do IP. Depois é só dar um Join() para formar o texto. Algo assim (usando LINQ):
IPAddress gateway = GetDefaultGateway();
if (gateway != null) {
    label8.Text = string.Join(".", gateway.GetAddressBytes().Select(x => x.ToString()));
}

Coloquei no GitHub para referência futura.
Se a informação não é a que deseja, o problema é diferente do que está na pergunta e uma nova deve ser feita. Respondi o que resolve o que foi perguntado.

A: Tenta atribuir o texto da label da seguinte maneira:
string n = Convert.ToString(gatway.Address);
label8.Text = n;


text:
Q: Putting two rows from table into one EDIT:
Got it working.  I created a second view to hold the pivots, i think that was confusing me. Then edited my join for the AmusementMeter table to:
left join AmusementMeter as am_in on m.MachineId = am_in.MachineId and am_in.[Type] = '+'
left join AmusementMeter as am_out on m.MachineId = am_out.MachineId and am_out.[Type] = '-'

Now It all comes back on one row.
Thank you for helping.

I'm having trouble with this query, using Sql Server 2012.  I'm pulling from multiple tables and I'm having trouble with just one right now.  For every Machine there are two AmusementMeter records in the AmesementMeter Table.  I need to get the two records in the AmusementMeter table to come over as one so I don't have two rows for each MachineId in the returned output.
What I have:
 SELECT DISTINCT
        m.MachineId as 'Machine Id' ,
        m.Name as 'Machine Name',
        mc.Name as 'Machine Class',
        m.InstallDate as 'Setup Date',
        m.Serial as 'Machine Serial Number',
        m.[Description] as 'Machine Description',
        l.ID as 'Location Id',
        l.Name as 'Location Name',
        m.DateMovedToLocation as 'Date moved to location',
        m.Manufacturer,
        m.PurchaseDate as 'Purchase Date',
        m.PurchasePrice as 'Purchase Price',
        m.PurchaseFrom as 'Purchase From',
        m.CabinetSerial as 'Cabinet Serial Number',
        m.Color as 'Cabinet Color',
        m.BillValidatorDescription as 'Bill Validator Description',
        CASE WHEN am.[Type] = '+' THEN am.Reading END AS 'IN Meter Reading',
        CASE WHEN am.[Type] = '+' THEN am.Value END AS 'IN Meter Value',
        CASE WHEN am.[Type] = '+' THEN am.Meter END AS 'IN Meter Digits',
        CASE WHEN am.[Type] = '-' THEN am.Reading END AS 'IN Meter Reading',
        CASE WHEN am.[Type] = '-' THEN am.Value END AS 'IN Meter Value',
        CASE WHEN am.[Type] = '-' THEN am.Meter END AS 'IN Meter Digits',
        CASE WHEN Pvt.[1] IS NULL THEN '' ELSE Pvt.[1] END AS 'REDEMPTION',
        CASE WHEN Pvt.[2] IS NULL THEN '' ELSE Pvt.[2] END AS 'MAX BET',
        CASE WHEN Pvt.[3] IS NULL THEN '' ELSE Pvt.[3] END AS 'JACKPOT CAP',
        CASE WHEN Pvt.[4] IS NULL THEN '' ELSE Pvt.[4] END AS '50 AND 100 STAT',
        CASE WHEN Pvt.[5] IS NULL THEN '' ELSE Pvt.[5] END AS 'MUTHA GOOSE KEY',
        CASE WHEN Pvt.[6] IS NULL THEN '' ELSE Pvt.[6] END AS 'LICENSE EXPIRATION YR',
        CASE WHEN Pvt.[7] IS NULL THEN '' ELSE Pvt.[7] END AS 'PERMIT NUMBER',
        CASE WHEN Pvt.[8] IS NULL THEN '' ELSE Pvt.[8] END AS 'GAGGLE VER 126',
        CASE WHEN Pvt.[9] IS NULL THEN '' ELSE Pvt.[9] END AS 'METER VAULT RIVETS ',
        CASE WHEN Pvt.[10] IS NULL THEN '' ELSE Pvt.[10] END AS 'ASSET ID TAG'
    FROM
    (SELECT
        mudfr.MachineId, mudfr.UDFieldId, mudfr.Value
    FROM
        MachineUserDefinedFieldRelation AS mudfr INNER JOIN
        MachineUserDefinedField AS mudf ON mudfr.UDFieldId = mudf.FieldId) AS pv PIVOT
        (Max(Value) FOR UDFieldId IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])) AS Pvt JOIN
        Machine AS m on m.MachineId = Pvt.MachineId  JOIN
        MachineClass as mc on m.CategoryID = mc.ID JOIN
        Location as l on m.LocationID = l.ID INNER JOIN
        AmusementMeter as am on am.MachineId = m.MachineId

Output(I cut out a lot, left in the problem columns):
Won't let me post screenshot, sorry.  I get something like this, where I have MachineId showing up twice.  The other values are from the AmuesmentMeter table.  I want it to only be shown once and were we have the null values the values to take there place.
550001  NULL    NULL    NULL    928204  0.25    6

550001  547563  0.25    6   NULL    NULL    NULL

What I want: (Expected output)
550001  547563  0.25    6   928204  0.25 6

Thank you for helping.

A: You have to add a GROUP BY clause on m.MachineId and select the MAX(columnname) for each column you want to "combine".
No ISNULL function is needed since MAX ignores NULLS

A: EDIT: Got it working. I created a second view to hold the pivots, i think that was confusing me. Then edited my join for the AmusementMeter table to:
left join AmusementMeter as am_in on m.MachineId = am_in.MachineId and am_in.[Type] = '+'
left join AmusementMeter as am_out on m.MachineId = am_out.MachineId and am_out.[Type] = '-'

Now It all comes back on one row.
Thank you for helping.


text:
Q: Variable no definida en class PHP En PHP 5.5 tengo un archivo conexion.php con la conexion a mi base de datos.
<?php
$usuario = "userDB";
$password = "";
$servidor = "localhost";
$basededatos = "myDB";
$conexion = mysqli_connect($servidor, $usuario, $password, $basededatos) or die("No se ha podido conectar al servidor de Base de datos");
?>

Y con include lo llamo en un class en otro archivo  consultas.php
<?php
class consultas {
    public function consultaCorreo($correo) {
        include 'conexion.php';
        if ($correo) {
            $statement = $conexion->prepare('SELECT correo FROM usuario WHERE correo=?');
            $statement->bind_param('s', $correo);
            $statement->execute();
            $rs = $statement->get_result();

    }
}
?>

consultas.php me indica que la variable $conexion (definida en conexion.php) no esta inicializada. Por lo mismo no ejecuta el query.
¿Alguna idea de porque pasa esto?

A: Esto podría ser una solución:
class Conexion
{
    public $usuario = "userDB";
    public $password = "";
    public $servidor = "localhost";
    public $basededatos = "myDB";
    public $conexion;

    public function __construct()
    {
        $this->conexion = mysqli_connect(
                $this->servidor,
                $this->usuario,
                $this->password,
                $this->basededatos
        ) or die("No se ha podido conectar al servidor de Base de datos");
    }

    public function getConnection()
    {
        return $this->conexion;
    }
}

class consultas
{
    public function consultaCorreo($correo)
    {
        $newConexion = new Conexion();
        $conexion = $newConexion->getConnection();

        if ($correo) {
            $statement = $conexion->prepare('SELECT correo FROM usuario WHERE correo=?');
            $statement->bind_param('s', $correo);
            $statement->execute();
            $rs = $statement->get_result();
        }
    }
}

Puedes separar la clase Conexion otro archivo y llamarlo desde donde quieras.


text:
Q: C++ TerminateProcess function I've been searching examples for the Win32 API C++ function TerminateProcess() but couldn't find any.
I'm not that familiar with the Win32 API in general and so I wanted to ask if someone here who is better in it than me could show me an example for,

*

*Retrieving a process handle by its PID required to terminate it and then call TerminateProcess with it.

If you aren't familiar with C++ a C# equivalent would help too.

A: To answer the original question, in order to retrieve a process handle by its PID and call TerminateProcess, you need code like the following:
BOOL TerminateProcessEx(DWORD dwProcessId, UINT uExitCode)
{
    DWORD dwDesiredAccess = PROCESS_TERMINATE;
    BOOL  bInheritHandle  = FALSE;
    HANDLE hProcess = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);
    if (hProcess == NULL)
        return FALSE;

    BOOL result = TerminateProcess(hProcess, uExitCode);

    CloseHandle(hProcess);

    return result;
}

Keep in mind that TerminateProcess does not allow its target to clean up and exit in a valid state. Think twice before using it.


text:
Q: Exporting PDF with jspdf not rendering CSS I am using jspdf.debug.js to export different data from a website but there are a few problems, I can't get it to render the CSS in the exported PDF and if I have an image in the page I am exporting, the PDF returns blank...
Does anyone know a way to fix this ?
Here is a jsfiddle showing it's not rendering the CSS
And my script
$(document).ready(function() {
$('#export').click(function(){
var d = new Date().toISOString().slice(0, 19).replace(/-/g, ""),
        filename = 'financiar_' + d + '.pdf',
        pdf = new jsPDF('p', 'pt', 'letter'),
        specialElementHandlers = {
          '#editor': function( element, renderer ) {
              return true;
          }
    };
    pdf.fromHTML(
          $('.export').get(0) // HTML element
        , 25  // x coord
        , 25  // y coord
        , {
              'width': 550 // was 7.5, max width of content on PDF
            , elementHandlers: specialElementHandlers
        }
    );
    pdf.save( filename );
})
});

A: Slight change to @rejesh-yadav wonderful answer.
html2canvas now returns a promise.
html2canvas(document.body).then(function (canvas) {
    var img = canvas.toDataURL("image/png");
    var doc = new jsPDF();
    doc.addImage(img, 'JPEG', 10, 10);
    doc.save('test.pdf');
});

Hope this helps some!

A: As I know jsPDF is not working with CSS and the same issue I was facing.
To solve this issue, I used Html2Canvas. Just Add HTML2Canvas JS and then use pdf.addHTML() instead of pdf.fromHTML().
Here's my code (no other code):
 var pdf = new jsPDF('p', 'pt', 'letter');
 pdf.addHTML($('#ElementYouWantToConvertToPdf')[0], function () {
     pdf.save('Test.pdf');
 });

Best of Luck!
Edit: Refer to this line in case you didn't find .addHTML()

A: jspdf does not work with css but it can work along with html2canvas. You can use jspdf along with html2canvas.
include these two files in script on your page :

You need to download script files such as
https://github.com/niklasvh/html2canvas/releases
https://cdnjs.com/libraries/jspdf
make clickable button on page so that it will generate pdf and it will be seen same as that of original html page.
Download PDF

It will work perfectly.

A: You can get the example of css implemented html to pdf conversion using jspdf on following link:
JSFiddle Link
This is sample code for the jspdf html to pdf download.
$('#print-btn').click(() => {
    var pdf = new jsPDF('p','pt','a4');
    pdf.addHTML(document.body,function() {
        pdf.save('web.pdf');
    });
})

A: This is sample what I used to add external CSS in HTML, I have external CSS file and link to HTML as normal and get the main element in javascript file then generate the pdf through following code.
htmlString = document.getElementById("main");
pdf.addHTML(htmlString, function () {
   pdf.save('Test.pdf');

});

A: To remove black background only add background-color: white; to the style of


text:
Q: Can't figure out exception message I am having the following error message and I am using petaPOCO.  Why am I having this error message and What am I doing wrong to have this message:
{"There is already an open DataReader associated with this Command which must be closed first."}

This is what I have been able to copy for the exception message.

System.InvalidOperationException was caught
    Message=There is already an open DataReader associated with this Command which must be closed first.
    Source=System.Data
    StackTrace:
         at System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command)
         at System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command)
         at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
         at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
         at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
         at System.Data.SqlClient.SqlCommand.ExecuteScalar()
         at PetaPoco.Database.Insert(String tableName, String primaryKeyName, Boolean autoIncrement, Object poco) in C:\Dev\Code\API\Models\PetaPoco.cs:line 1243
    InnerException:

A: Here is an excellent explanation why this exception is raised:
http://blogs.msdn.com/b/spike/archive/2009/08/20/there-is-already-an-open-datareader-associated-with-this-command-which-must-be-closed-first-explained.aspx
The conclusion is as following:
Because the SqlDataReader keeps the memory stream (resultset) available until you explicitly close the SqlDataReader you can get this exception if you try to create a new reader without closing the previous one.
Alter your code to have a using statement whenever you create a SqlDataReader:
SqlCommand cmd = new SqlCommand(sql, con);
using (SqlDataReader rdr = cmd.ExecuteReader())
{
  while (rdr.Read())
  {
    Console.WriteLine("cid: {0}, ctext: {1}", rdr[0].ToString(), rdr[1].ToString());
  }
}

Using will automatically call dispose() (which closes the reader) when the closure (ending } ) is reached.
If this exception is raised in petaPOCO then there is a bug in their code or you are using the code in an unspecified way.

A: Your ORM (or your usage pattern of the ORM) expects the underlying ADO.NET provider to allow for multiple open DataReaders on a single Connection. SQL Server Provider you seem to use can do that, but you must add MultipleActiveResultSets=True to the connection string you use to connect to the database.

A: I know this is old, but I wanted to add something that may help the next person searching for this. This error happens if you use the Query method. The Query method doesn't load everything in memory. If you need to have it loaded and then have the connection closed, you need to use Fetch.
This is from the website:

Query vs Fetch
The Database class has two methods for retrieving records Query and
  Fetch. These are pretty much identical except Fetch returns a List<>
  of POCO's whereas Query uses yield return to iterate over the results
  without loading the whole set into memory.

Hope this helps someone else.

A: This exception can also be thrown in PetaPoco if your poco doesn't have a parameterless constructor of either public or protected visibility.


text:
Q: useContext passing wrong props I have my context Provider in my AppContext.tsx file
import { useState, useEffect, useContext, createContext } from 'react';

interface AppContextProps {
  children: React.ReactNode
}

const themes = {
  dark: {
    backgroundColor: 'black',
    color: 'white'
  },
  light: {
    backgroundColor: 'white',
    color: 'black'
  }
}

const initialState = {
  dark: false,
  theme: themes.light,
  toggle: () => { console.log('toggle from initalState') }
}

const AppContext = createContext(initialState);

export function AppWrapper({ children }: AppContextProps) {
  const [dark, setDark] = useState(false) // Default theme is light

  // On mount, read the preferred theme from the persistence
  useEffect(() => {
    const isDark = localStorage.getItem('dark') === 'true'
    setDark(isDark)
  }, [dark])

  // To toggle between dark and light modes
  const toggle = () => {
    console.log('toggle from AppWrapper')
    const isDark = !dark
    localStorage.setItem('dark', JSON.stringify(isDark))
    setDark(isDark)
  }

  const theme = dark ? themes.dark : themes.light

  return (
    <AppContext.Provider value={{ theme, dark, toggle }}>
      {children}
    </AppContext.Provider>
  );
}

export function useAppContext() {
  return useContext(AppContext);
}

I insert Appwrapper into my _app.tsx file
import type { ReactElement, ReactNode } from 'react'
import type { NextPage } from 'next'
import type { AppProps } from 'next/app'
import { AppWrapper } from '../contexts/AppContext';
import 'normalize.css/normalize.css';
import '../styles/globals.scss'

type NextPageWithLayout = NextPage & {
  getLayout?: (page: ReactElement) => ReactNode
}

type AppPropsWithLayout = AppProps & {
  Component: NextPageWithLayout
}

const App = ({ Component, pageProps }: AppPropsWithLayout) => {
  const getLayout = Component.getLayout ?? ((page) => page)
  return getLayout(
    <AppWrapper>
      <Component {...pageProps} />
    </AppWrapper>
  )
}

export default App

And I call and import the useAppContext hook to use it in my Header component
import styles from './header.module.scss'
import { useAppContext } from '../contexts/AppContext'

const Header = () => {
  const { theme, toggle, dark } = useAppContext()

  return (

            <input type="checkbox" />

  )
}

export default Header

However, my toggle function logs toggle from initalState instead of toggle from AppWrapper.
The following code below
const { theme, toggle, dark } = useAppContext()

gets data from initialState
const initialState = {
  dark: false,
  theme: themes.light,
  toggle: () => { console.log('toggle from initalState') }
}

instead of what I pass into the value props shown below
<AppContext.Provider value={{ theme, dark, toggle }}>
  {children}
</AppContext.Provider>

How do I correctly pass the value props data into my component instead of the data from initialState?

A: Because my app was using per-page layouts, I inserted AppWrapper in my layout file instead of _app.tsx and everything works
import Header from './header'
import Footer from './footer'
import { AppWrapper } from '../contexts/AppContext';

interface LayoutProps {
  children: React.ReactNode
}

const Layout = ({ children }: LayoutProps) => {
  return (
    <AppWrapper>

      {children}

    </AppWrapper>
  )
}

export const getLayout = (page: LayoutProps) => <Layout>{page}</Layout>;

export default Layout


text:
Q: What is the composition of a skewed tent map with itself? Given the skewed tent map:
$F(x) =
     \begin{cases}
       \text{$\mu x$,} &\quad\text{$x\in [0,\frac{1}{1+s}]$} \\
       \text{$\frac{\mu}{s}(1-x)$,} &\quad\text{$x\in [\frac{1}{1+s},1]$}
     \end{cases}$
I want to find $F^2(x)$. I'm not really sure how to go about this; do I apply $F(x)$ again to the two parts of $F(x)$?
Based on my notes for the non-skewed tent map I have something like this:
$F^2(x) =
     \begin{cases}
       \text{$\mu^2 x$,} &\quad\text{$x\in [0,\frac{1}{\mu(1+s)}]$} \\
       \text{$\frac{\mu}{s}(1-\mu x) $,} &\quad\text{$x\in [\frac{1}{\mu(1+s)},\frac{1}{1+s}]$}  \\
       \text{$\frac{\mu}{s}(1-\frac{\mu}{s}(1-x)) x$,} &\quad\text{$x\in [\frac{1}{1+s},1-\frac{s}{\mu(1+s)}]$}\\
       \text{$\frac{\mu^2}{s}(1-x)$,} &\quad\text{$x\in [1-\frac{s}{\mu(1+s)},1]$}
     \end{cases}$
But I don't really understand how to get here; and I'm not even sure it's right as if $\mu\lt1$ then $\frac{1}{\mu(1+s)}\gt1-\frac{s}{\mu(1+s)}$ which means the intervals are all wrong...

A: First of all, you are right that the formula for $F^2(x)$ does not make sense when $\mu < 1$. I'm going to assume that somewhere in your notes is an assumption that $\mu > 1$, and go from there.
So now we have a formula
$$F^2(x) = F(F(x)) =
\begin{cases}
\mu F(x) & F(x) \in [0,\frac{1}{1+s}] \\
\frac{\mu}{s} (1-F(x)) & F(x) \in [\frac{1}{1+s},1]
\end{cases}
$$
We would like to rewrite this without the expression "$F(x)$" anywhere on the right hand side. To do this, we break into cases.
Case 1: $x \in [0,\frac{1}{1+s}]$ and so $F(x) = \mu x$. We therefore have equivalent statements as follows:
$$F(x) \in \left[0,\frac{1}{1+s}\right] \quad \iff \quad 0 \le F(x) \le \frac{1}{1+s} \quad \iff \quad 0 \le \mu x \le \frac{1}{1+s}
$$
$$\iff 0 \le x \le \frac{1}{\mu(1+s)}
$$
Similarly,
$$F(x) \in \left[\frac{1}{1+s},1\right] \iff \frac{1}{\mu(1+s)} \le x \le \frac{1}{1+s}
$$
From this we obtain two lines of the desired formula for $F^2(x)$, namely
$$F^2(x) = \mu F(x) = \mu^2 x \quad\text{if}\quad x \in \left[0,\frac{1}{\mu(1+s)}\right]
$$
and
$$F^2(x) = \frac{\mu}{s}(1-F(x)) = \frac {\mu}{s}(1- \mu x) \quad\text{if}\quad x \in \left[\frac{1}{\mu(1+s)},\frac{1}{1+s}\right]
$$
I'll leave the formulation and proof of Case 2 to you.


text:
Q: Holt Winters Forecast in Python with Multiple Index Columns I'm very new to Python and to data science. I'm studying forecasting using holt-winters in Python. What puzzles me is that all of what I'm reading so far involves very simple data hierarchy. In other words, the data consists of a date column and a numbers (sales/populations/etc.) column.
The forecast then just tries to predict the numbers for future dates. Ok, but what if I have data with multiple columns like Date, Region, District, Branch, Sales? Sales Is what I'm trying to forecast but, as you can see, the date column is not the only level. How can such a granular forecast work?