text:
Q: How to know what percent of document that I read in Safari? When using Safari to read documentation, how do I know how much do I read or much much more is left to read just like I do with editors?

There seems to be no indicator in Safari for that purpose.

A: If you initiate a scroll a little bit either up or down a scrollbar will appear in Safari letting you know where you are in the document unless it has been disabled by code in the website.
You could use a "User Style Sheet" to have the scrollbar always appear: http://webdesign.about.com/od/css/ht/htcssusersafari.htm
Or you can do it the easiest way and go to "System Preferences > General" and choose "Show Scrollbars > Always".

A: Do you mean the scrollbar?  It's there just hard to see. Next to the words directory and path in the enlargement below. Becomes more visible when you hover that margin of the window.
You can stop auto hiding this in system pref->general->show scroll bars = always.


text:
Q: IntelliJ Select an interpreter to see the installed packages I'm using IntelliJ 2021.2.1. My workspace has some Java projects (JDK11).
I then created a Flask project in pycharm and imported it to my workspace. I can run it, but when I view the "Python Packages" tab in IntelliJ, it says "Select an interpreter to see the installed packages".
In Project Structure | SDKs, I have JDK 11 as well as my Conda environment.
How do I get Python Packages to work in IntelliJ with a Java workspace?
Also, Tools | Manage Python Packages IS working, just the tab at the bottom is showing the error message.

A: You can try one of the following:

*

*Set default project SDK to Python in Project Structure | Project | Project SDK

*Create your Python module as a facet for the Java module, instead of a separate module.

I have created a usability issue for this https://youtrack.jetbrains.com/issue/PY-50547

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does a wrapper class wrap the value of a datatype around its objects? I needed a way to assign a String value to an object of a class I created, for a personal project. As expected,
String str = "Sample";
MyClass obj = (MyClass) str;

does not work, since String can't be converted to MyClass type. But then, how do wrapper classes take String inputs and convert them to, say, an Integer or a Double object? I have searched for "How do wrapper classes work?" but haven't found any solution to my question. All pages only give details of implementations of wrapper classes.
I wonder if you could hep me out. The ability to wrap String values around objects of MyClass as well as to unwrap them would greatly improve the aesthetics of my project.
Thank you.

A:
how do wrapper classes take String inputs and convert them to, say, an Integer or a Double object?

They don't.  You generally have to use methods like Integer.parseInt or Integer.valueOf to convert between Strings and Integers, and other wrapper classes.
If you're asking how the compiler parses those literals, that uses e.g. Integer.decode, but that is something used only for primitive literals and cannot be made to work for your custom classes.  (It's not even available for other Java types that could productively use their own literal format, such as BigInteger.)


text:
Q: How do I know/ How am I to know? Is there any difference between these two questions? Is the second one grammatically right?

How do I know?

vs

How am I to know?

A: Dan Bron's opening comment is correct, but I'd like to explain a bit more about why that's the case.
Basically, it comes down to tense and modality, or conditionality. Using "to be" (or in this case, "am") with an infinitive like "to know" is one of the future tenses English uses*, and it's a tense that expresses intention and plan. So you could rephrase "How am I to know?" as "What plan would you expect me to use to know this?"
Since that's a fairly common sort of thing to say, but "How am I to …" is a fairly formal pattern, it's not surprising that "How do I …?" has been adapted to that use as well informally. Formally, though, "do" is not conditional at all here. It's just asking for a explanation that matches current reality. So you could rephrase it as "Right here, right now, how is it that I know this?"
Obviously, both sentences (and both verbs) are very flexible, so there's a lot of variations possible, and a lot of different subtle implications depending on context. But that's the basic breakdown.
*To the extent that English has future tense, at least, which is the subject of some scholarly debate. Close enough, though.

A: Let's say you are solving a math problem
You are stuck somewhere for hours and after hours of struggle you came to know the reason,  that is you were unaware of a formula which happens to be out of scope for you.  At that point you can say "how am i to know?"
According to me,  "How do I know" is more like a statement
Let's say after hours of struggle you went for a drink and after returning you started again and you solved it. (rare scenario)
Next day you find the solved problem in your bed.  You checked and find a strange formula which solved it.  At that point you may say "how do I know" since you don't remember solving it.


text:
Q: Animate OnComplete firing too early I'm implementing a progress bar (for timing a background task, I already know the exact time it will take) - but I'm having trouble with the oncomplete event firing early.
$("#go").on("click", function(event){

    event.preventDefault();

    $('#report-loader .bar').animate({
        width: 500
    },
    {
        easing: 'linear',
        duration: 500,
        complete: function() {
            alert('complete');
        }
    });
});

Here's a JSFiddle that shows an example of what I mean:
http://jsfiddle.net/ezE8b/1/

A: Replace  : $('#report-loader .bar').animate({
        width: 500
    },

by
$('#report-loader .bar').animate({
        width: "100%"
    },

Works fine for me.


text:
Q: bash : replace text with partially-space-filled string I have a file of the following format.
33256SOL    OW 100092   1.507   1.186   0.847
33256SOL    HW1100093   1.561   1.233   0.783
...

And I would like to change it to
33256SOL    OW     92   1.507   1.186   0.847
33256SOL    HW1    93   1.561   1.233   0.783
...

I would like to do a for loop in bash. However, the formatting was wrong. There is no space filling for a consistent format.
for i in {100001..200000}; do
        j=$(expr $i - 100000)
        sed -i "s/$i/$j/g" number.txt
done

Is there anyway to fill the variable with space and put it in sed?

A: awk solution:
awk -F"[[:space:]][[:space:]]+" '{$2=substr($2,1,3) " " substr($2,4)-100000}1' file

The output:
33256SOL OW  92 1.507 1.186 0.847
33256SOL HW1 93 1.561 1.233 0.783

*

*-F"[[:space:]][[:space:]]+" - field separator (by multiple spaces)

*substr($2,1,3) - get the first 3 characters of the 2nd field

*substr($2,4)-100000 - subtract 100000 from 6-difit number of the 2nd field

To obtain tab-formatted output just add the OFS (output field separator) like below:
awk -F"[[:space:]][[:space:]]+" -v OFS="\t" '{$2=substr($2,1,3)" "substr($2,4)-100000}1' file

The output:
33256SOL    OW  92  1.507   1.186   0.847
33256SOL    HW1 93  1.561   1.233   0.783

A: Another solution :
cat number.txt | cut -c -15 > prefix
cat number.txt | cut -c 16- | awk '{printf "%s %s %s %s\n", $1 - 100000, $2, $3, $4}' | paste prefix -

First line recover first part of line we don't want to change.
Second line take part of line we want to change (cut), change it (awk), and paste part previously recover by first line (paste).


text:
Q: Avoiding circular imports Python I know this question have already been answered, but for my application, I can't resolve it. What I'm trying to do is to setup a database using MongoAlchemy instead of using MongoClient. I want to have diffrent scripts for every operation This is my main file, app.py:
import os

from flask import Flask, jsonify
from blueprints.db import insert_db
from blueprints.delete_blueprint import delete_bp
from blueprints.insert_blueprint import insert_bp
from blueprints.read_blueprint import read_bp
from blueprints.login_update_blueprint import log_update
import traceback

app = Flask(__name__)

app.register_blueprint(log_update)
app.register_blueprint(read_bp)
app.register_blueprint(insert_bp)
app.register_blueprint(delete_bp)

# database configuration
app.config['MONGOALCHEMY_DATABASE'] = 'rest_api'

# populate table with initial values
insert_db.populateTables()

# mail configuration
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'chis.simion12@gmail.com'
app.config['MAIL_PASSWORD'] = ''
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True

@app.errorhandler(404)
def page_not_found(c):
    return 'The required page does not exist'

@app.errorhandler(400)
def bad_req(c):
    return 'Bad request. Please review the request'

@app.errorhandler(Exception)
def handle_Exception(error):
    print("\n ______ ERROR ______\n")
    print(traceback.format_exc())
    print("_____________________\n")

    response = dict()
    response['message'] = "A PROBLEM HAS OCCURED, PLEASE TRY AGAIN LATER"
    response['status_code'] = 500
    response = jsonify(response)
    response.status_code = 500

    return response

if __name__ == '__main__':
    app.secret_key = os.urandom(12)
    app.run(debug=True, threaded=True)

Note that I'm modyfing on the old version, so the imports are still there. The problem with the circular imports appear when I try do import app from app.py into the script which initializes the database, described below:
from flask import current_app
from flask_mongoalchemy import MongoAlchemy
# from app import app

db = MongoAlchemy(current_app)

class People(db.Document):
    Name = db.StringField()
    Age = db.IntField()
    Password = db.StringField()
    Vms = db.AnythingField()

If I try to use current_app I get the error: RuntimeError: Working outside of application context. which means that the app is not currently initialized, and if I import the app from app.py the circular dependency appears. I'm sorry if I wasn't pretty clear, so feel free to ask for more details.

A: I like to place all extensions on a extensions.py file and create a function to initialize and configurate the app instance
extensions.py
from flask_mongoalchemy import MongoAlchemy

db = MongoAlchemy()

models.py
from extensions import db

class Person(db.Model):
    pass

flaskr.py
from flask import Flask
from extensions import db

def create_app():
    app = Flask(__name__)
    db.init_app(app)

    return app

app = create_app()
app.run()


text:
Q: How can I show that that compact subsets of $\mathbb{R}$ in this topology are finite subsets. Let $\tau$ be the topology on $\mathbb{R}$ which has as base the collection of all sets of the form
 $O \setminus C$ where $O \subset \mathbb{R}$ is an open set in the standard topolgy of $\mathbb{R}$ and
 $C \subset \mathbb{R}$ is a countable subset.
a.Show that $(\mathbb{R},\tau)$ is a connected space which is not locally connected.
b.Find the path component of  $ 0 \in \mathbb{R}$.
c.Show that compact subsets of $\mathbb{R}$ in this topology are finite subsets.

A: For (c) directly, without (a) and (b):
If $X\subseteq \mathbb R$ is infinite, enumerate some countable sequence of elements of $X$: $x_1,x_2,\dots,x_n,\dots$ and define for $d$ a positive integer: $O_d=\mathbb R\setminus \{x_n: d\mid n\}$.  Then $X\subseteq \bigcup_{d} O_d$. But For any finite set $d_1,d_2,\dots,d_k$, $x_{D}\notin \bigcup_{i=1}^k O_{d_i}$, where $D=d_1d_2\cdots d_k$. So there is no finite subcover.

A: I have tried so far on this problem; but I'm not sure my solution.
a.
 Suppose $(\mathbb{R}, \tau )$ is disconnected. So there exist $U,V$ such that
 $U \cup V = \mathbb{R}$, $U \cap V = \emptyset$, $U \neq \emptyset$ ,$U \neq \mathbb{R}$.
 Since $U,V$ open in $\tau$ $U=O_1 \setminus C_1$, $V=O_2 \setminus C_2$
$O_1,O_2$ are open, $C_1,C_2$ are countable in standard topology.
$U\cap V = (O_1 \setminus C_1)\cap (O_2 \setminus C_2)= \emptyset$
$\qquad = (O_1\cap O_2)\cap (C_1\cup C_2)^c$
$(O_1\cap O_2)$ is open and $(C_1\cup C_2)$ is countable.
 Let we say $ O=(O_1\cap O_2)$ and $C=(C_1\cup C_2)$. Then we obtain,
$O \setminus C = \emptyset$
$O=C$. it's a contradiction. So $(\mathbb{R}, \tau )$ is connected space.
$\mathbb{R} \setminus \mathbb{Q}$ is neighbourhood of $\sqrt{2}$ but  $\mathbb{R} \setminus \mathbb{Q}$
 is not connected. And we can not find connected neighbourhood $V$ of $\sqrt{2}$  such that
 $\sqrt{2} \in V \subset \mathbb{R} \setminus \mathbb{Q} $. So R is not locally connected.
b.
 Firstly every open $(a,b)$ is open set in $(\mathbb{R}, \tau )$, C is countable subset.
 İf $(a,b)\cap C = \emptyset$ then $(a,b)\setminus C =(a,b)$ .
For arbitrary $k \in \mathbb{R}$,there exist a continuous
$$f: [0,1]\rightarrow (\mathbb{R}, \tau)$$
 $$x\rightarrow kx$$
$f(0)=0$,$f(1)=k $ then $0\sim k$ , $k \in \mathbb{R}$
Then path component of $0$ is $\mathbb{R}$.
c. Let we prove $(\mathbb{R}, \tau )$ is Hausdorff.
 Since every open $(a,b)$ is open set in $(\mathbb{R}, \tau )$ and
  $\mathbb{R}$ is Hausdorff with standard topology. We are done.
  Let $A\subset \mathbb{R}$ is compact. Then $A$ is closed.
  So I will prove closed subsets of $\mathbb{R}$ is finite. But how?


text:
Q: Man pages for clang unavailable I'm running ubuntu 16.04 LTS and I've installed clang via apt.
When I try to look at the man page, I'm told that the man page is unavailable. Man pages for other things (eg. man gcc) work fine.
What might be going wrong? How can I resolve this? Any pointers on where to look would be appreciated.
ian@ian-VirtualBox:~$ man clang
No manual entry for clang
See 'man 7 undocumented' for help when manual pages are not available.
ian@ian-VirtualBox:~$ man 7 undocumented
No manual entry for undocumented in section 7

ian@ian-VirtualBox:~$ clang --version
clang version 3.8.0-2ubuntu4 (tags/RELEASE_380/final)
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin

Running man clan-3.8 results in:
ian@ian-VirtualBox:~$ man clang-3.8
No manual entry for clang-3.8
See 'man 7 undocumented' for help when manual pages are not available.

The directory /usr/share/man/man1 contains:
ian@ian-VirtualBox:/usr/share/man/man1$ ls | grep clang
clang-apply-replacements-3.8.1.gz
clang-check-3.8.1.gz

The output of ls /usr/bin/clang is:
ian@ian-VirtualBox:/usr/share/man/man1$ ls /usr/bin/*clang*
/usr/bin/clang                         /usr/bin/clang-check-3.8
/usr/bin/clang++                       /usr/bin/clang-cl-3.8
/usr/bin/clang-3.8                     /usr/bin/clang-query
/usr/bin/clang++-3.8                   /usr/bin/clang-query-3.8
/usr/bin/clang-apply-replacements      /usr/bin/clang-rename-3.8
/usr/bin/clang-apply-replacements-3.8  /usr/bin/clang-tblgen
/usr/bin/clang-check

dpkg -L clang-3.8 shows man pages for clang-apply-replacements, clang-check, scan-build and scan-view. I'm able to bring up these man pages OK
Installing clang-3.8-doc installs a lot of things in usr/share/doc but no man pages. Is this what I should be using for clang documentation instead of man?

A: The package clang does not install a manual page. You may want to install clang-3.8-doc which installs documentation in HTML format in /usr/share/doc/clang-3.8-doc/html/; point your browser to /usr/share/doc/clang-3.8-doc/html/index.html.


text:
Q: how to call command line through c# I have this command line:
LSPrintingDialog.exe -f "C:\Program Files\LightScribe Template Labeler\templatelabeler\content\templates\backgrounds\GiftTags.jpg" -n "HP dvd de8a4l rh61 211 (J:)" -i 0 -q draft -p J -c 1 -m 1
With CMD, I am able to call this command line directly, how can I call this command line through C#?

A: You need to call Process.Start(exePath, arguments) and accept answers to your questions.


text:
Q: HAProxy qtime meaning According to the HAProxy documentation the metric qtime represents the average queue time over the last 1024 requests. My question is, does this metric average ALL requests, or just those that have sat in the queue?
For example, if I have received 1000 requests, and 10 of those were queue, does qtime represent the total time spent in queue averaged over all 1000 requests or only the 10 that were actually queued?


text:
Q: Is this possible? Use JSONP to get remote URL data, then convert data to javascript collection for use with javascript code Since Javascript can't make remote URL calls, I can do the following to get around it yes?

*

*Use JSONP to load a remote URL with a search query and then get back data.

*Convert the data to a javascript collection

*Use my normal javascript code that I've already written to work with the collection.
Does anyone see any problems with this? It should work in theory yes? Is it a normal practice or is there a better way?


text:
Q: car loan instalment calculator javascript this is my coding that im working to calculate instalment for car loan. but it seems my calculate button not working. i dont know what is my mistake. if anybody could help that would be nice.
newbie programmer here.

 Car Price (RM):
            <input type = "text" name = "txtPrice" size = "10" onchange="calculate();">

 (Retail Purchase Price)

 Down Payment (RM):
            <input type = "text" name = "txtDownPayment" size = "10" onchange="calculate();">
             (minimum of 10% of car price)

 Interest Rate (%):
            <input type = "text" name = "txtInterest" size = "10" onchange="calculate();">

 Loan Duration:
            <input type = "text" name = "txtDuration" size = "5" onchange="calculate();">
             (year)

<input type = "button" value = "Calculate" onClick = "calculate();">
             RM
            <input type = "text" name = "txtLoanInstallment" size =  "10">


text:
Q: Do c++ static libraries without mfc that are linked to an MFC project throw bad_alloc or CMemoryException*? I'm working on a large, aging code base for an MFC app.  The code has been worked on by many developers over time, and as a result, we have three different ways throughout the code of dealing with the possibility of an allocation failure with new.
The first way is to test for NULL on the result of new.  We don't use nothrownew.obj so this is clearly an error that needs to be cleaned up.
The second is to catch CMemoryException* (yes, C++ exceptions are enabled in the compiler).  From what I understand, MFC overrides the standard operator new, and throws this thing instead.  I am fairly certain that this second method is correct in the MFC application itself.  MFC overrides new, with its strange CMemoryException throwing version.
The last comes from our base of people who are good with C++, but aren't neccessarily MFC programmers.  They are catching const std::bad_alloc&.
What I really don't know is what to expect for static libraries linked into the application.  This is were the vast majority of the code that uses bad_alloc lives.  Assuming these libraries are not compiled with MFC or ATL, and are written in standard C++ only, can they expect to catch bad_alloc?  Or will the presence of MFC in the application they link to infect them with the global new operator and render their attempts to fail cleanly on a bad allocation moot?
If you have an answer, could you explain how this works, or point me to the right reference to sort this out?

A: It will depend on the compile options for the static libraries to be linked to the application.
If the libraries are compiled with a configuration to use the static Standard C++ run-time then I would expect the operator new from the Standard C++ run-time to be called.
If libraries are compiled with a configuration to use the Standard C++ run-time DLL then the resolution of these functions will be delayed until program load and should be resolved to the MFC replacements of operator new.
I also included a link to this Herb Sutter article regarding handle allocation errors that you may find useful.

A: Congratulations -- you seem to have stumped all of us. :-)
In theory, if MFC provides an overload for the global new function, then it should be used by all code in the program. But since the static libraries were compiled without knowing about that, I can't say for certain that it would.
The best I can suggest is to write some test code to find out. (I won't have access to my Windows system for the next few hours, or I'd do so myself and give you an answer.)

A: I've done some MFC-Code-Researches (in VC2010). Here are some facts.

*

*The MFC throws a pointer to a global CMemoryException instance named "_simpleMemoryException" (see also AfxThrowMemoryException())

*it is an CException whose m_bAutoDelete is false.

Idea: If it possible to change the c++-only-static-libraries, you can forward declare class CException; and/or class CMemoryException; into the root namespace.
Add a catch-block with catch (CMemoryException* pEx) {...} and/or catch (CException* pEx) {...} at each place where a std::bad_alloc-catch block is. Since the catched pointer is a pointer to a global object, it is not needed to call pEx->Delete();.
In this way the c++-only-static-libraries are not required to include afx.h or/and link against the MFC. I've tried it in VC2010, and it works fine. (only if RTTI is enabled, and only if nobody changes the MFC-NewHandler with AfxSetNewHandler to something else than the default-MFC-NewHandler AfxNewHandler)

A: You can change the MFC throwing behavior with AfxSetNewHandler(_PNH pfnNewHandler) and provide a pointer to your own NewHandler function. This function should then throw a std::bad_alloc exception.
But now the MFC-program-parts have the problem to catch a std::bad_alloc.


text:
Q: I can't run a Flutter project anymore Yesterday I worked the last time on my Flutter project. Today I only started Android Studio and I tried to launch my project, and I received an Error message. I tried everything and I checked also if there are some updates etc.
What can I do to solve this problem?
Here is the Error Message:
[+13326 ms] C:\Users\******\AndroidStudioProjects\PROJECTNAME\android\app\src\debug\AndroidManifest.xml Error:
[   +1 ms]  uses-sdk:minSdkVersion 16 cannot be smaller than version 23 declared in library [:audioplayers] C:\Users\******\AndroidStudioProjects\PROJECTNAME\build\audioplayers\intermediates\library_manifest\debug\AndroidManifest.xml as the library might be using APIs not available in 16
[        ]  Suggestion: use a compatible library with a minSdk of at most 16,
[        ]      or increase this project's minSdk version to at least 23,
[        ]      or use tools:overrideLibrary="xyz.luan.audioplayers" to force usage (may lead to runtime failures)
[        ] FAILURE: Build failed with an exception.
[        ] * What went wrong:
[        ] Execution failed for task ':app:processDebugManifest'.
[        ] > Manifest merger failed : uses-sdk:minSdkVersion 16 cannot be smaller than version 23 declared in library [:audioplayers] C:\Users\******\AndroidStudioProjects\PROJECTNAME\build\audioplayers\intermediates\library_manifest\debug\AndroidManifest.xml as the library might be using APIs not available in 16
[        ]      Suggestion: use a compatible library with a minSdk of at most 16,
[        ]          or increase this project's minSdk version to at least 23,
[        ]          or use tools:overrideLibrary="xyz.luan.audioplayers" to force usage (may lead to runtime failures)
[        ] * Try:
[        ] Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
[        ] * Get more help at https://help.gradle.org
[        ] BUILD FAILED in 13s
[{"event":"app.progress","params":{"appId":"ab743200-5f09-4853-ae95-0b0cb729d0f0","id":"0","progressId":null,"finished":true}}]
[ +351 ms] Exception: Gradle task assembleDebug failed with exit code 1
[   +2 ms]
           #0      throwToolExit (package:flutter_tools/src/base/common.dart:14:3)
           #1      RunCommand.runCommand (package:flutter_tools/src/commands/run.dart:474:9)
           <asynchronous suspension>
           #2      FlutterCommand.verifyThenRunCommand (package:flutter_tools/src/runner/flutter_command.dart:977:18)
           #3      _rootRunUnary (dart:async/zone.dart:1198:47)
           #4      _CustomZone.runUnary (dart:async/zone.dart:1100:19)
           #5      _FutureListener.handleValue (dart:async/future_impl.dart:143:18)
           #6      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:696:45)
           #7      Future._propagateToListeners (dart:async/future_impl.dart:725:32)
           #8      Future._completeWithValue (dart:async/future_impl.dart:529:5)
           #9      _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:40:15)
           #10     _completeOnAsyncReturn (dart:async-patch/async_patch.dart:311:13)
           #11     RunCommand.usageValues (package:flutter_tools/src/commands/run.dart)
           #12     _rootRunUnary (dart:async/zone.dart:1198:47)
           #13     _CustomZone.runUnary (dart:async/zone.dart:1100:19)
           #14     _FutureListener.handleValue (dart:async/future_impl.dart:143:18)
           #15     Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:696:45)
           #16     Future._propagateToListeners (dart:async/future_impl.dart:725:32)
           #17     Future._completeWithValue (dart:async/future_impl.dart:529:5)
           #18     _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:40:15)
           #19     _completeOnAsyncReturn (dart:async-patch/async_patch.dart:311:13)
           #20     AndroidDevice.isLocalEmulator (package:flutter_tools/src/android/android_device.dart)
           #21     _rootRunUnary (dart:async/zone.dart:1198:47)
           #22     _CustomZone.runUnary (dart:async/zone.dart:1100:19)
           #23     _FutureListener.handleValue (dart:async/future_impl.dart:143:18)
           #24     Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:696:45)
           #25     Future._propagateToListeners (dart:async/future_impl.dart:725:32)
           #26     Future._completeWithValue (dart:async/future_impl.dart:529:5)
           #27     Future._asyncCompleteWithValue.<anonymous closure> (dart:async/future_impl.dart:567:7)
           #28     _rootRun (dart:async/zone.dart:1190:13)
           #29     _CustomZone.run (dart:async/zone.dart:1093:19)
           #30     _CustomZone.runGuarded (dart:async/zone.dart:997:7)
           #31     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
           #32     _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
           #33     _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
           #34     _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:118:13)
           #35     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:169:5)

A: You need to read the official document carefully. As it mentioned, configure your build.gradle file with <uses-sdk tools:overrideLibrary="xyz.luan.audioplayers"/>.

Gradle Build Failing
In order to support the playBytes method, this has a hard requirement on using API >= 23 features, and your build may failure depending on your minimum sdk targeting. To override this, you will need to add < uses-sdk tools:overrideLibrary="xyz.luan.audioplayers"/> to your build.gradle

A: minSdkVersion 16 cannot be smaller than version 23

one of the plugins (xyz.luan.audioplayers) you have used is incompatible with android versions below API23. You need to set your projects minimum SDK Version to 23 or Higher.
go to android folder in your project and open app folder then open build.gradle file.
in that file, under defaultConfig edit the following line as follows
minSdkVersion 23


text:
Q: Efficient Core Data handling using NSTableView with around 500.000 records Good morning guys, I developed an iOS app using Core Data and the TICoreDataSync library (http://timisted.github.io/TICoreDataSync/) to sync between devices, now I would like to create a similar Mac OSX app to sync with the iOS one and I'm looking around the web how to efficiently handle data because I have around 500.000 records. On iOS I used the NSFetchedResultsController to efficiently manage the results returned from a Core Data fetch request to provide data for a UITableView object, but on Mac OSX the NSFetchedResultsController is unavailable, so I read alternatives here:
http://youtu.be/NpDQDjFJ_5Y
How to handle extremely large CoreData store in NSTableView?
NSArrayController without loading a large dataset into an array
But reading the comments it seems that someone consider these ways still laggy. What do you suggest me to do?
Thanks a lot in advance.

A: You can use Core Data incremental Store to sync data to you Mac OSX in background.
https://developer.apple.com/library/ios/documentation/DataManagement/Conceptual/IncrementalStorePG/Introduction/Introduction.html
To load data on your table view, you can use delegate source method to fetch the data in batches from the local core data store use
- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row;

Or else if you don't want to use Core Data Incremental Store(it will be tough to use), then in the delegate method, call the service to get your data and show it on the UI. We have successfully tested and handled this for around 200000+ records.


text:
Q: file read in ruby getting output as spaces in character I have an function to read data from file but I have problem with reading data
input in file:
1,S1-88,S2-53,S3-69,S4-64
File.open(file_path).each do |line|
    p line.gsub(/\s+/, "")
end

Output:
   "1,S1 -88,S2 -53,S3 -69,S4 -64 \n"
The problem is, it adding an extra space after s1 -integer,s2 -integer like so, I have tried .gsub(/\s+/, "") to remove white space from string but it is not working, Please can any one help me why this happenning, How I can override this issue Or it may be file encoding issue?

A: If you binread, essentially you have UTF-8 characters in between
irb(main):013:0> f = File.binread('f2.txt')
=> "1,S1\xC2\xAD-88,S2\xC2\xAD-53,S3\xC2\xAD-69,S4\xC2\xAD-64"

\xC2\xAD are essentially whitespace characters
This may be because you have copied it from somewhere incorrectly or it was introduced in your text because of God. Don't know. You an check here, it shows there are hidden characters in between your text.
This will remove all characters not wanted.
File.foreach('f2.txt') do |f|
 puts f.gsub(/[^\\s!-~]/, '')
end

=> 1,S1-88,S2-53,S3-69,S4-64


text:
Q: How can I determine the delimiter being used in an infobox-data table on Wikipedia using R? I am trying to scrape the infobox data for an Indonesian film from Wikipedia using R. In the infobox, there are several fields that contain multiple lines of data. For example, the "Pemeran" (or "Cast") field for the film "Kutunggu di Sudut Semanggi" https://id.m.wikipedia.org/wiki/Kutunggu_di_Sudut_Semanggi looks like this in the HTML:

  Pemeran

    Marisa Tompunu

    Berliana Febrianti

    Hanna Wijaya

    Slamet Rahardjo

    Dwi Asih Setiawati

    Tengku Firmansyah

I have written the following code to extract the data from this field and split it into separate lines:
# Scrape the Wikipedia page for the film
url <- "https://id.wikipedia.org/wiki/Kutunggu_di_Sudut_Semanggi"
page <- read_html(url)

# Extract the infobox
infobox <- html_nodes(page, "table.infobox")

# Extract the "Pemeran" field from the infobox
anchors <- html_nodes(infobox, "th:contains('Pemeran') + td")

# Extract the names of the cast members from the anchor elements
pemeran <- html_text(html_nodes(anchors, "a"))

# Split the text into separate lines
lines <- strsplit(pemeran, "
")[[1]]

# Create a new row for each line
rows <- data.frame(Pemeran = lines)

# Check the rows
print(rows)

However, when I run this code, the resulting data frame rows only contains one line of data, like this:
         Pemeran
1 Marisa Tompunu

I expected the data frame to contain one row for each cast member, like this:
        Pemeran
1 Marisa Tompunu
2 Berliana Febrianti
3 Hanna Wijaya
4 Slamet Rahadrjo
5 Dwi Asih Setiawati
6 Tengku Firmansyah

I suspect that the issue may be with the delimiter that I am using to split the text into separate lines. Currently, I am using
 as the delimiter, but it looks like the infobox-data tables in Wikipedia use a different delimiter.
What delimiter is being used in an infobox-data table on Wikipedia, and how can I split the text into separate lines using that delimiter in R?

A: library(tidyverse)
library(rvest)

tibble(
  Pemeran = "https://id.m.wikipedia.org/wiki/Kutunggu_di_Sudut_Semanggi" %>%
    read_html() %>%
    html_elements("tr:nth-child(5) a") %>%
    html_text2()
)

#> # A tibble: 6 × 1
#>   Pemeran
#>   <chr>
#> 1 Marisa Tompunu
#> 2 Berliana Febrianti
#> 3 Hanna Wijaya
#> 4 Slamet Rahardjo
#> 5 Dwi Asih Setiawati
#> 6 Tengku Firmansyah

Created on 2022-12-23 by the reprex package (v2.0.1)


text:
Q: How to use streams with interfering methods and constructors, and why not use .peek()? I'll show a simplified example of my problem to help demonstrate it.
let's say I'm trying to convert an old java code to java 8 code for style and parallelization purposes (Which i do).
this is the code:
    public static boolean deleteTester(List<Integer> keys) {
        DHeap dHeap = new DHeap(d, keys.size());
        DHeap_Item[] DHeap_ItemArray = keysListToDHeap_ItemArray(keys);
        dHeap.arrayToHeap(DHeap_ItemArray);

        for (int i = 0; i < keys.size(); i++) {
            keys.set(i, null);
            dHeap.delete(DHeap_ItemArray[i]);
            if (!someTest(keys, dHeap.getList()))
                return false;
        }
        return true;
    }

There are several issues in the conversion:

*

*I need to check every iteration, so i can't reduce/collect and then check.

*I am accessing an array and a data structure object (which the tester is for), meaning it isn't non-interfering, and isn't  stateless operation.

Here is my attempt at replacing the for loop:
    return IntStream.range(0, keys.size())
            //.parallel()
            .peek(idx -> keys.set(idx, null))
            .peek(idx -> dHeap.delete(DHeap_ItemArray[idx]))
            .allMatch(e -> someTest(keys, dHeap.getList()));

which is much shorter and readable, however "breaks the rules" and in result unable to parallel.
So my questions are:

*

*Why am I unable to use .parallal()? (I get a null pointer ex.)

*Why shouldn't we use peek()? because in this code i see no other way around it.

*What should I do when accessing outside elements?

*How should I "transfer" the code to java 8 streams?

*What am I missing?

I guess that the answers are intertwined.
I just started to learn java 8 so thanks a lot for all the help because I'm really stuck.

A:
Q: Why am I unable to use .parallal()?
Q: What should I do when accessing outside elements?

you can use it in a parallel stream, there is no problem when the action doesn't modify shared state there, for example:
stream.peek(System.out::println).allMatch(...);

If the action modifies shared state, it is responsible for providing the required synchronization, for example:
stream.peek(it->{synchronized(lock){ keys.set(idx, null); }}).allMatch(...);

Q: Why shouldn't we use peek()?

you can using the peek() method, but you should avoiding using peek() if you can't control the stream, for example:
boolean foo(){ stream.peek(...).allMatch(..); }

//a violate rule
Stream<?> foo(){
  /*you need avoiding using peek() here since you can't control the stream*/
}

Q: How should I "transfer" the code to java 8 streams?

there is a detailed description how to operates a stream in its package summary java.util.stream.

A: You absolutely should not use peek like this.  Streams API documentation does not specify that elements will pass through peek only until the test in allMatch fails.  All bets are off the the stream is parallel as anyMatch is not required to be evaluated in order and one thread is allowed to keep executing peek even after another thread has encountered a condition that violates anyMatch.
Even if the stream is sequential, peek can execute an unexpected number of times in certain cases.  Consider the following code:
List<List<Integer>> data = Arrays.asList(
    Arrays.asList(1,2),
    Arrays.asList(3,4,5),
    Arrays.asList(6,7));

data.stream()
    .flatMap(List::stream)
    .peek(System.out::println)
    .allMatch(x -> x < 4);

You might think that it will print numbers up to 3, but in fact it will print numbers up to 5.


text:
Q: PHP query - on 1st, 5th, 9th record add a class Im wondering if its possible with PHP to add a class to X record returned. I know I can do this with JS only I'd like it to have the class added as the records are returned.
I have the following loop in my PHP, From what I've found in google I need to add a counter to do this only I've been unsuccessful so far...
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
        echo '
' . $row['First_Name'] . ' ' . $row['Surname'] . "";
        echo '';
        echo 'seen in ' . ucwords($row["Location_County__Seen"]) . 'View Profile
';
    }

A: In front of your while, add $c = 1
Before the end of your while loop, add $c++;
Then, modify your first line:
echo '
'
To
echo '
'

For the final result:
$c = 1;
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
    echo '
' . $row['First_Name'] . ' ' . $row['Surname'] . "";
    echo '';
    echo 'seen in ' . ucwords($row["Location_County__Seen"]) . 'View Profile
';

    $c++;
}


text:
Q: (ncurses) - Does mvwaddch() make calls to wrefresh()? I'm working on a small game project and by mere curiosity I commented the line that makes a refresh to the main WINDOW object.
while(game->state)
    {
      //Move into player
      params->mov = player_1;
      params->x = player_1->pos_x;
      params->y = player_1->pos_y;
      params->game = game;
      //curs_set(FALSE);
      player_1->key_move(params);

      //Move into player
      mvwprintw(p_info,y, x, "TERRAIN: [%c]", player_1->inplace);

      //wrefresh(main_scene);           /* THE LINE I DELETED */
      wrefresh(p_info);
      sleep(TICK);

    }

The game ran without problems and player updated its position graphically. player_1->key_move(params) eventually calls wgetch(), mvwaddch(), and mvinch(), nothing else (from ncurses). wrefresh(p_info) was commented after and, as expected, that WINDOW object never updated. I'm wondering if that function calls wrefresh() at some point. There's no direct indication of this in the manual.
If it does, are there alternatives to mvwaddch() that doesn't update the WINDOW object?

A: According to man wgetch, and I quote:

If the window is not a pad, and it has been moved or modified since the last call to wrefresh, wrefresh will be  called  before another character is read.

Because this is a game, inside the loop, and more concrete in the routine call to player_1->key_move(params) there are modifications to the WINDOW object. This is why the program is causing such behaviour.
I realised that game logic was depending on state from the WINDOW, so several reads/writes would potentially come in the future. All game logic is to be handled separately.


text:
Q: ModuleNotFoundError: No module named 'windows' I'm working on a project and I need to use the PyMouse module.
pip install pymouse
installed pymouse correctly, so I assumed all was fine.
However, when importing PyMouse:
from pymouse import PyMouse
I got the following error running my program:
Traceback (most recent call last):
  File "4opeenrij.py", line 1, in <module>
    from pymouse import PyMouseEvent
  File "C:\Users\lcdew\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pymouse\__init__.py", line 92, in <module>
    from windows import PyMouse, PyMouseEvent
ModuleNotFoundError: No module named 'windows'

I can't seem to figure out what might cause this error message. Any help would be much appreciated.
Additional info:
I'm using Python 3.7 32 bit
Current pip version: 18.1
I have Windows 10
working on a 64-bit operating system

A: I had I look into this and became puzzled at first, so looked deeper.
It turns out that pymouse is absolutely full of errors. More that I bothered to find.
The error you got is just one of many errors caused by bad coding.
The code says:
from windows import PyMouse, PyMouseEvent

And it should say:
from .windows import PyMouse, PyMouseEvent

Also, PyUserInput, a sister package that is free from the pymouse errors, requires pyhook, which is unsupported by python 3. After a lot of looking around, the conclusion that there is no way around the problems found, except maybe installing a really early version.
You could also try the keyboard module.

A: You might want to take a look at pynput module. It works on python 3.8, doesn't have any incompatible dependencies, and doesn't seem to have any errors. Once you have the module installed, this page gives some good examples of various ways to manage the mouse.


text:
Q: How to show relative division over absolute division? There are two divisions with class name a and b.

.a {
  height: 120px;
  width: 120px;
  background: #E08027;
  border-radius: 50% 50% 10px 10px;
  position: relative;
}

.b {
  position: absolute;
  height: 49px;
  width: 49px;
  background: #F2AD43;
  border-radius: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

I want to hide the part of division b which is over division a while show the rest.
*z-index is not working.

A: You could use z-index: -1; on the child element :
This answer provides interesting informations about the stacking order.

.a {
  height: 120px;
  width: 120px;
  background: #E08027;
  border-radius: 50% 50% 10px 10px;
  position: relative;
}

.b {
  position: absolute;
  height: 49px;
  width: 49px;
  background: #F2AD43;
  border-radius: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: -1;
}


text:
Q: Solr how to improve query speed time after too many atomic update I'm using solrCloud 7.4 with 3 instance (16GB RAM each instance) and have 1 collection with 10m data. For starter it really fast, almost no query more than 2 seconds.
Then i have updated with transaction (i.e popularity) data in other oracle database to make my collection more relevant. I just simply loop transaction then using solr atomic update like set and inc about 1~10 fields (almost all field type float n long). But transaction has more than 300m data. So the process i set and inc every 10k transaction data to collection in solr.
The update part of 300m data only process once, After that maybe take 50k/day and processing at 0am.
In the end. the collection still have 10m data, but looks like my query has slow down almost up to 10 seconds.
I look in shard overview, each shard have 20+ segment and half of them are deleted document:

*

*Have i do something miss here, why my query time drop?

*How do i speed up again like before?

*Should i copy and creating new collection n reindex my 10m collection after atomic update (from 300m transc) to the new collection?

A: The issue is caused by a large number of segments being created, mostly consisting of deleted documents. When you're doing an atomic update, the previous document is fetched, the value is changed, and the new document (with the new value) is indexed. This leaves the old document as deleted, while the new document is written to a new file.
These segments are merged when the mergeFactor value is hit; i.e. when the number of segments gets high enough, they're merged into a new segment file instead of having multiple files around. When this merges happens, deleted documents are expunged (no need to write documents that no longer exists to a new file).
You can force this process to happen by issuing an optimize, and while you usually can rely on mergeFactor to do the job for you (depending on the value of mergeFactor and your indexing strategy), datasets where everything is updated in one go, such as once at night, issuing an optimize afterwards works fine.
The down side is that it'll require extra processing (but that would happen anyway if you just relied on mergeFactor, but not everything at the same time), and up to 2x the current size of the index as temporary space.
You can perform an optimize by calling the update endpoint for your collection: http://localhost:8983/solr/collection/update?optimize=true&maxSegments=1&waitFlush=false
The maxSegments value tells Solr how many segments its acceptable to end up with. The default value is 1. For most use cases that'll be fine.
While calling optimize has gotten a bad rep (since mergeFactor usually should do the work for you, and people tend to call optimize far too often), this is a perfectly fine use case for optimize. There are also optimization enhancements for the optimize command in 7.5, which will help avoid the previous worst case scenarios.


text:
Q: API for Doxygen Execution I wanted to automate the execution of Doxygen whenever I insert my source code to my code repository. Is there any api/interface for doxygen that I can use in my java code to start its execution?

A: Doxygen itself is started by executing a command-line command, so you only need a way of executing a command when a check in occurs. You don't say anything about the SCC tool, Dev Environment or OS you are working with, so it's hard to give a specific answer.
The usual way to do this would be using a build server running Continuous Integration. That is, when you check in code, the build server will notice the check in, get the new code, and then execute a build (in this case of Doxygen documentation). There are many tools available that will automate a PC to make a build server. Which one to use would depend on things like the OS and Source Control package you're using. (If you don't have/want a dedicated build server you could also run a tool like this on your own PC in the background).
If you just want the build to occur on your own PC when you check in, then you could investigate your source control software to see if you can be notified of the check-in. Some SCCs may offer an ability to execute a script or command for certain events, so it may be possible to get it to execute the command for you.
Lastly, many people just set up a tool/macro within their development environment that executes Doxygen, and then they run it manually. In visual Studio (for example) you could even write a macro that would do both the Check in and execute Doxygen from a single keypress.

A: If you want more control with doxygen, you have to generate also xml files and create a program that analyze the xml output files to check all your constraints, and stop the build if a constaint is violated.
this technique needs some developement effort but it's the only way that i know to do what you want with doxygen.


text:
Q: Strange Angular Material MAT Dialog Issue I played a while back around with MAT_DIALOG to be able to display forms above each other and used the mat_dialog Module. I read that to bring up an existing form the form needs to be specified in the entryComponents Array. Now here comes the intresting part. In my code i have a form that does is not specified as an entryComponent and it works fine. So my question is there another place where i can specify or set something so a form can be used in that matter. I just want to make sure i take the right aproach
Here is a StackBlitz Sample


text:
Q: protobuf-net - backticks, Dictionaries & .proto files I'm trying to talk to a C# program that uses protobuf-net from an iphone using http://code.google.com/p/metasyntactic/wiki/ProtocolBuffers
Unfortunately the .proto file I've been given (generated from the C# source code) includes an a line that protoc is rejecting:
repeated Pair_Guid_List`1 Local = 6;

It appears that this is because the source data is a C# Dictionary, with a Guid key and a class as the value. Is there a way to cope with this better?
The protobuf-net version in use is r278.zip.
(The C# sending and receiving these protobufs all works fine, it's just when we add the iphone into the mix that this becomes an issue.)
UPDATE: all working now thanks to Marc!
The object on the C# side turned out to be:
[ProtoMember(7)]
public Dictionary<Guid, List<Pages>> ReceivedPages { get; set; }

which worked fine using the following in the .proto:
message PagesDict {
  required bcl.Guid guid = 1;
  repeated Pages Pages = 2;
}

with the message in question containing:
  repeated PagesDict ReceivedPages = 7;

A: Firstly - are you trying to use protobuf-net on the iPhone? v1 is not expected to work via monotouch; v2 does work (that was a big driver for the v2 work), but is not yet released (it is usable but incomplete at the moment). Let me know if you are trying to do this, as it would matter ;-p
I expect they've obtained that .proto by calling Serializer.GetProto<T>, which is unfortunately not fool-proof, especially when things like Dictionary<,> are involved (I'll add a TODO to try to fix that in v2).
The good news is that it models Dictionary<TKey,TValue> as repeated someType, where someType should be:
message someType {
    required keyType key = 1;
    required valueType value = 2;
}

And Guid is modelled as bcl.Guid (bcl.proto), which is:
message Guid {
  optional fixed64 lo = 1; // the first 8 bytes of the guid
  optional fixed64 hi = 2; // the second 8 bytes of the guid
}

Note, however, that no "proto" is needed at all if working .NET-to-.NET; just compatible types.


text:
Q: Edit value in datatable variable in asp.net(vb) I have a variable that contains a datatable, and I have condition if the value is 0 which I want to change into a "No" string.
Here is my original code
dt = BrowseServiceTypeMaster(ServiceTypeName)
lvServiceType.DataSource = dt

For i As Integer = 0 To dt.Rows.Count - 1
    If dt(i)("exception").ToString = "0" Then
        dt(i)("exception") = "No"
    End If
Next

and here's what I've changed it to:
For i As Integer = 0 To dt.Rows.Count - 1
    If dt(i)("exception").ToString = "0" Then
        dt(i)("exception").Fill = "No"
    End If
Next

It still gives me an error, can anybody help me?

A: If you only want to conditionally change the value of a field in row in a DataTable then use something like this:
For Each row As DataRow In dt.Rows
    If row("exception") = "0" Then
        row("exception") = "No"
    End If
Next

Edit
I'm afraid what you're trying to do is not possible.  The exception you show in your comment tells why:

Input string was not in a correct format. Couldn't store  in
  exception Column. Expected type is Int64.

This exception is telling you that you're trying to store a String value in a DataTable column that is set to accept Int64's (Long).  You can't do that.
There are a number of controls you can use that offer customizable templates that allow you to specify at runtime what text to display to the user based on the value bound to an element of that control.
For example if you were binding your DataTable to a ListView you would bind your 'exception' column to an ItemTemplate and use code like this to display 'No' when a record's value was 0 and display the field's value in all other cases:
<%#IIf(Eval("exception") = 0, "No", Eval("exception").ToString())%>


text:
Q: vb.net cboboxes select a value from one and auto select the index number from the other Hey all i am trying to auto select the email value from a 2nd cbobox when the user selects a name from the first cbobox using the first cbobox's index. (the values all line up with each other just fine)
This is my current code:
Private Sub cmbAnalyst_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbAnalyst.SelectedIndexChanged
    theAName = cmbAnalyst.Text
    Dim intSelectedIndex = cmbAnalyst.SelectedIndex

    cboEmails.SelectedValue = intSelectedIndex
End Sub

I get the index just fine (intSelectedIndex) but i am unable to have it select the email in the second cbobox. Nothing ever selects when i choose a name.
Any help would be great! :o)
David

A: You must use SelectedIndex on the 2nd combobox too.
Private Sub cmbAnalyst_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbAnalyst.SelectedIndexChanged
    theAName = cmbAnalyst.Text
    Dim intSelectedIndex = cmbAnalyst.SelectedIndex

    cboEmails.SelectedIndex = intSelectedIndex
End Sub


text:
Q: What is the difference between socket.io client and socket.io server? Alternatives to socket.io? I have been breaking my head on understanding what exactly is socket.io and its role in the whole persistent communication between client and server in general. Some fundamental questions that keep coming up in my mind are :

*

*Are node.js and socket.io server different ways of doing the same thing ? Like lighthttpd and apache ?

*Why should I use socket.io server if I have node.js ?

*Can I use socket.io client with another server side programming language like PHP ?

*Are there alternatives to using socket.io client ?

*Is socket.io client just another javascript library for websocket communication ?

Thanks :)

A: The Socket.IO server accepts connections from Socket.IO clients.  This is not any different than any other server (such as a web server like Apache) accepting a connection from a client (such as a web browser like Internet Explorer).
Node.js is a platform built on top of the V8 JavaScript engine, which comes with a convenient library usually used for web and network applications.  Socket.IO is a web-socket-like communication wrapper and RPC which enables servers and clients to communicate over a variety of transports (every thing from long-polling JSON to real Web Sockets).  Generally, the Socket.IO server code runs in your JavaScript application running on top of Node.js, and the Socket.IO client runs in your JavaScript on a web browser.  (Note that you can run the Socket.IO client in your Node.js application to, which I have used in the past as a quick RPC between multiple Node.js applications.)
There are Socket.IO clients available for many languages, and yes I believe there is one for PHP but I haven't used it personally.
If you want to communicate with a Socket.IO server, you must use a Socket.IO client.  It is a protocol all on its own.

A:
Are node.js and socket.io server different ways of doing the same thing ? Like lighthttpd and apache ?

Socket.io is a framework/library for node.js

Why should I use socket.io server if I have node.js ?

It's a framework designed for two-way communication, use it if you want

Can I use socket.io client with another server side programming language like PHP ?

Technically yes. But then you would have to reimplement socket.io server in that other language to match it.

Are there alternatives to using socket.io client ?

Lots of, google for websocket/real time communication in [here put your language]

Is socket.io client just another javascript library for websocket communication ?

Socket.io client is a JavaScript library compatibile with socket.io server (which is JavaScript library as well, only on the server side, i.e. Node.js)

A:
Are node.js and socket.io server different ways of doing the same thing ?

SocketIO is actually a I/O engine that permits realtime communication between client and server, unlike classic HTTP requests.

Why should I use socket.io server if I have node.js ?

Since both are differents, we can't compare.

Can I use socket.io client with another server side programming language like PHP ?

No, because socketIO server run in NodeJS environment.
Client first make a HTTP request, then socketIO send a static JS script to client.
This script establish the two-way communication.
But you can use socketIO server with different socketIO client implementation.

Are there alternatives to using socket.io client ?

Any socketIO client implementation can do the job since they connected to server.
But beware of asynchronous way of communication, like in Java or PHP.

Is socket.io client just another javascript library for websocket communication ?

Yes it is, but socketIO aims on reliability and easy to use, and also do best effort : It choose the best transport available for client.
Hope it helps !


text:
Q: Pointer to an array in Objective-C function call I want to pass an array of long long to an objective c function. I would like the array to be passed as a pointer, if possible, so that copying is not done. I wrote this code:
+ (int) getIndexOfLongLongValue: (long long) value inArray: (long long []) array size: (int) count
{
    for (int i =0; i < count; i++)
    {
       if (array[i] == value)
           return i + 1;
    }
    return 0;
}

to which I pass
long long varname[count];

as the second argument. I am wondering if I can pass this array as a pointer or if this method is fine. I don't need pointers to long longs but pointers to the array.

A: C arrays always decay to pointers when passed to a function or a method, so it is not copied in your example. A pointer to long long is automatically a pointer to an array of long long, by virtue of the operator [] being applicable to all pointers. Since your method does not modify the array, you may want to add const to highlight this fact in your API; other than that, your method is fine.

A: It is being passed in as a pointer (language pedantry notwithstanding); nothing's getting copied. type[] is, for the most part, the same thing as type*.
To confirm this, check out sizeof(array) in the method. You'll see it's the same size as sizeof(void*).
If you really want a pointer to the array, i.e. a pointer to a pointer to the long longs, you'll need to use something like type**; but the only reason to want to do this is if you want to modify the underlying array pointer from the method, which is hardly ever the case.

A: Objective-C is just an extremely thin wrapper around regular C, so this is handled the same as it would be handled in C: passing by reference.
+ (int)getIndexOfLongLongValue:(long long)value inArray:(long long *)array size:(int)count
{
    for (int i = 0; i < count; i++)
    {
        if (array[i] == value)
            return i + 1;
    }
}

Then in the code that calls the function:
int myIndex = [object getIndexOfLongLongValue: aValue inArray: varname size: count];


text:
Q: How to have HttpContext in a Background Process I'm running hangfire background process. Now part of the function being called is using MediaService which also needs HttpContext because when I try to execute mediaService.Save(media) it throws an error of
 System.ArgumentNullException
 Value cannot be null. Parameter name: httpContext

      System.ArgumentNullException: Value cannot be null.
      Parameter name: httpContext

From what I was reading it needs to be a normal http request and not a background process.
How can we fake or fix the httpcontext issue inside my background service?
public void saveMedia()
{
        var mediaService = ApplicationContext.Current.Services.MediaService;
        string[] filePaths = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "uploads");

        foreach (string filePath in filePaths)
        {
            using (Stream stream = System.IO.File.OpenRead(filePath))
            {
                string filename = Path.GetFileName(filePath);
                string mediaType = Constants.Conventions.MediaTypes.File;
                string ext = Path.GetExtension(filename);

                IMedia media = mediaService.CreateMedia(filename, Constants.System.Root, mediaType);
                media.SetValue("umbracoFile", filename, stream);
                mediaService.Save(media); // HTTPCONTEXT error here
                media = null;
            }

            System.IO.File.Delete(filePath);
        }
}

A: You will have to find a way to serialize the HttpContext that you are trying to use in your Hangfire background job. HTTP request scope is not passed as argument when you run a method (with HttpContext or most of its component) in Hangfire. Since methods are serialized and then executed outside of the HTTP request scope, you will have to find a different way to fake the HttpContext in your methods.
See here for an example on how to create a fake HttpContext in your methods that are executed by Hangfire..
Another post from Hangfire Developer on what you can do to get "some" of the properties from HttpContext by deserializing it before the job execution.


text:
Q: Socket Host Echo not 'responding' I am having this weird problem with the Socket programming I picked up recently. I understand that the Socket can be used for a client to communicate with a host. This project requires ISO8583 as well. I already got a working code and I am modifying to work on my own testing host.
All is well and my code actually work but 1 problem I faced was that I got no response at all. The request sent from my computer to the host works. Host displays the correct messages and sends the response back to my computer. But I do not know why at that point, my app will just hang there. Even in debug mode, it is executing the line (which I will show you which line its executing) continuously without returning any value. This is my code below. It is quite messy and I am attempting lots of methods of trying to get a response value.
byte dataSmall[] = {0x00, 0x43, 0x60, 0x00, 0x02, 0x00, 0x00, 0x08, 0x00, 0x20, 0x00, 0x01, 0x00, 0x00, (byte) 0xC0,
            0x00, 0x00, 99, 0x00, 0x00, 0x00, 0x02, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
            0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31};

    try {
        Socket echoSocket = new Socket("IP Address", port number);
        ObjectOutputStream os = new ObjectOutputStream(echoSocket.getOutputStream());
         String responseLine;
         Client client = new Client(echoSocket);
        Thread reader = new Thread(client, "j8583-client");
        PrintWriter pw = new PrintWriter(os, true);

            reader.start();
            os.writeObject(dataSmall);
            os.flush();

            ObjectInputStream ois = new ObjectInputStream(echoSocket.getInputStream());
            //convert ObjectInputStream object to String
            String message = (String) ois.readObject(); // this is the continuous execution
            System.out.println(message);

            System.out.println("waiting for response");
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    echoSocket.getInputStream()));
            responseLine = in.readLine().toCharArray().toString();

            System.out.println("still waiting for response");
            System.out.println(responseLine);
        os.close();
        in.close();
        echoSocket.close();
        client.stop();
        reader.interrupt();

I have tried .readObject() and .readLine() hopefully to get the response output and both perform the same problem. Executing with no end to it. Unfortunately I am out of ideas on how I should approach this. It is very important that I get the response from my test host. So I appreciate any help you guys can give. Thanks in advance.

A: If the server you're talking to isn't written in Java or doesn't use Object Serialization, this code cannot possibly work. I don't see any reason here to use Object streams. Try it with the actual socket streams.

A: ISO8583 messaging is usually done in asynchronous mode, and the way to read/write ISO messages is to put the length of the message first, encoded as a 16-bit unsigned integer.
So first you need to put your ISO message in a byte buffer, measure it, then write that length, and then the message (and flush the stream).
To read the response, first you read 2 bytes, interpret those as a 16-bit unsigned integer, then create a buffer of that size and read the rest of the message. You need a dedicated thread to read responses continuously and pass them to some other worker for parsing and processing.

A: If the same code works on a different host and NOT on yours then you may need to look for port (s) contention. Whenever a client connection is created, an arbitary port is opened on the server to communicate with the client. Your firewall/antivirus may be blocking it and hence you are not able to send the response back.


text:
Q: Static fields or const functions for util methods? I need to create a set of reusable validators.
Is it better to declare them as static const functions ?
export const emailValidator: ValidatorFn =
  function(control: AbstractControl): {[key: string]: any} | null {
    return [...];
  };

export const anotherValidator: ValidatorFn =
  function(control: AbstractControl): {[key: string]: any} | null {
    return [...];
  };

or as static methods of a non-instantiable class ?
class CustomValidators {

  static emailValidator =
    function(control: AbstractControl): {[key: string]: any} | null {
      return [...];
    }

  static anotherValidator =
    function(control: AbstractControl): {[key: string]: any} | null {
      return [...];
    }
}

The 2nd solution looks nice because I will be able to use CustomValidators.* and autocomplete but it seems "ugly" to create a class that will actually never be instantiated. I use it more as a namespace.
Also, does it have consequences on tree shaking ? Will unused validators be suppressed at build time ?

A: The static objects will always remain on the javascript emitted bundle to be readily available for use as objects. if you want you can write those in util functions which may create the validators on demand instead of preinitializing them as static objects.
The other way is instead create a namespace and initialize on demand.


text:
Q: How to create json using rapidjson::Writer without creating document in C++? I am trying to create json using rapidjson::Writer without creating document but it just give json text but don't create full json output like below,
{ "data": { "dataIn": { "hello":"world", "t":true, "f":false }, "dataOut": { "n":null, "i":123, "pi":3.1416 } } }

On rapidjson documents as well not enough info given. Can please help with it. How I can achieve this?

A: On rapidjson documents as well not enough info given. Can please help with it. How I can achieve this? - That is not true if I correctly understood your intentions.
At RapidJSON:Sax look for paragraph Writer - example given there is almost the same as the one you're asking for.
I wrote It myself to check if it is working .. and it is:
#include <iostream>
#include <rapidjson/writer.h>

// {
//     "data":
//     {
//         "dataIn":
//         {
//             "hello":"world",
//             "t":true,
//             "f":false
//         },
//         "dataOut":
//         {
//             "n":null,
//             "i":123,
//             "pi":3.1416
//         }
//     }
// }

int main(int argc, char** argv)
{
    rapidjson::StringBuffer lStringBuffer;
    rapidjson::Writer lWriter(lStringBuffer);

    lWriter.StartObject();
    lWriter.Key("data");
        lWriter.StartObject();
        lWriter.Key("dataIn");
            lWriter.StartObject();
            lWriter.Key("hello");
            lWriter.String("world");
            lWriter.Key("t");
            lWriter.Bool(true);
            lWriter.Key("f");
            lWriter.Bool(false);
            lWriter.EndObject();
        lWriter.Key("dataOut");
            lWriter.StartObject();
            lWriter.Key("n");
            lWriter.Null();
            lWriter.Key("i");
            lWriter.Int(123);
            lWriter.Key("pi");
            lWriter.Double(3.1416);
            lWriter.EndObject();
        lWriter.EndObject();
    lWriter.EndObject();

    std::cout << lStringBuffer.GetString() << std::endl;

    return 0;
}

The output is:
{"data":{"dataIn":{"hello":"world","t":true,"f":false},"dataOut":{"n":null,"i":123,"pi":3.1416}}}

But if you want to get such a JSON string you might also use raw strings like:
    std::string lRawString = R"(
    {
        "data":
        {
            "dataIn":
            {
                "hello":"world",
                "t":true, "f":false
            },
            "dataOut":
            {
                "n":null,
                "i":123,
                "pi":3.1416
            }
        }
    }
    )";

and then pass it to rapidjson::Document:
rapidjson::Document lDocument;
lDocument.Parse(lRawString.c_str());


text:
Q: Multiple Sequence Alignment with Unequal String Length I need a methodology for creating a consensus sequence out of 3 - 1000 short (10-20bp) nucleotide ("ATCG") reads of varying lengths.
A simplified example:
"AGGGGC"
"AGGGC"
"AGGGGGC"
"AGGAGC"
"AGGGGG"

Should result in a consensus sequence of "AGGGGC".
I have found modules that do multiple sequence alignment (MSA) in the BioPython library, but only for sequences of the same length.  I am also familiar with (and have implemented) Smith-Waterman style alignment for two sequences of any length.  I imagine there must be a library or implementation that combine these elements (MSA over unequal lentghs), but after hours of scouring the web and various documentation haven't found anything.
Any advice on existing modules/libraries (Python preferred) or programs I can incorporate into a pipeline that do this?
Thanks!

A: Add gap characters at the end of your sequences so that they all have the same length. Then you can process them with your program of choice, e.g. MUSCLE:
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Align.Applications import MuscleCommandline

sequences = ["AGGGGC",
             "AGGGC",
             "AGGGGGC",
             "AGGAGC",
             "AGGGGG"]

longest_length = max(len(s) for s in sequences)
padded_sequences = [s.ljust(longest_length, '-') for s in sequences]
records = (SeqRecord(Seq(s)) for s in padded_sequences)

SeqIO.write(records, "msa_example.fasta", "fasta")

from Bio.Align.Applications import MuscleCommandline
cline = MuscleCommandline(input="msa_example.fasta", out="msa.txt")
print cline


text:
Q: How do i center the custom svg icon on the road I just want to ask i have svg icon it will not center on the road it shows always on the side of the road unlike the predefined path (arrow) by google map it shows on the center of the map.how can i make it center on the road just like on the predefined path by google map.
here is my jsfiddle
example
var iconcar = {
   path: "M17.402,0H5.643C2.526,0,0,3.467,0,6.584v34.804c0,3.116,2.526,5.644,5.643,5.644h11.759c3.116,0,5.644-2.527,5.644-5.644 V6.584C23.044,3.467,20.518,0,17.402,0z M22.057,14.188v11.665l-2.729,0.351v-4.806L22.057,14.188z M20.625,10.773 c-1.016,3.9-2.219,8.51-2.219,8.51H4.638l-2.222-8.51C2.417,10.773,11.3,7.755,20.625,10.773z M3.748,21.713v4.492l-2.73-0.349 V14.502L3.748,21.713z M1.018,37.938V27.579l2.73,0.343v8.196L1.018,37.938z M2.575,40.882l2.218-3.336h13.771l2.219,3.336H2.575z M19.328,35.805v-7.872l2.729-0.355v10.048L19.328,35.805z",

   scale: .8
    }
    var carPolyline = new google.maps.Polyline({
        map: map,
        geodesic : true,
        strokeColor : '#FF0000',
        strokeOpacity : 1.0,
        strokeWeight : 2,
        icons: [{
          icon: iconcar,
            scale: .8,
          offset: '100%'
        }],
    });
    var carPath = new google.maps.MVCArray();
    for ( var i = 0; i < path_start.length; i++) {
        if(i === 0) {
            carPath.push(path_start[i]);
            carPolyline.setPath(carPath);
        } else {
            setTimeout((function(latLng) {
                return function() {

                    carPath.push(latLng);
                    map.setCenter(latLng);
                };
            })(path_start[i]), 100 * i);
        }
    }

A: You can set different anchor point, for example:
var iconcar = {
       anchor: new google.maps.Point(10, 50),
       path:
   ...

updated fiddle
This anchors it a the front center of the "car":
      anchor: new google.maps.Point(10, 0),

anchored at the front center of the car


text:
Q: 41 +primorial is prime I noticed that $41$ plus primorials is prime when I add $2$ to $41=43$, then $6$ to $41= 47$, then $30+41=71$ all the way up to $41+9699690=9699731$.  Hence I can add the first $8$ primorials to get primes.  Do you know if there is a different prime that will allow the addition of more than the first $8$ primorials?

A: I just wrote a little Maple script to find some examples of primorially separated primes, as I will call them. Here are some results:
p=3 is the smallest prime which has a run of 1 primorially separated primes after it.
p=5 is the smallest prime which has a run of 2 primorially separated primes after it.
p=11 is the smallest prime which has a run of 3 primorially separated primes after it.
p=17 is the smallest prime which has a run of 4 primorially separated primes after it.
p=41 is the smallest prime which has a run of 8 primorially separated primes after it.
p=86351 is the smallest prime which has a run of 10 primorially separated primes after it.
Finding a run of 11 or more is turning out to take quite some time, but if my script finds anything I will update further.


text:
Q: Powerline patched font not working on Terminal.app I am on Mac OS X 10.10.2 (14C2513).
I am using Inconsolata patched font from here. But I also tried to patch the font myself.
The result is the following:

I am able to see the glyphs but zsh (see the glyph next to the branch name develop for a git repository) and also vim fail to display them on Terminal.app
Am I missing any configuration step?
Update
Using Input Mono v1.100 I have the same problem:

A: Let me suggest you to install Input Mono font, comes with full support to powerline.
In order the following to work, Input Mono font must be version 1.1. You can check the font version by going to Font Book → View → Show Font Info, and look at the version number.
With Terminal.app works out of the box. Just select the font and you are ready.
With iTerm2, you have to modify a couple of things:

*

*Go to Preferences → Profiles → Text and uncheck `Use a different font for non-ASCII text.

*Just above, click on Change Font and select Input Mono. Additionally you have to change Character Spacing → Vertical to 110%. Seems that Terminal and iTerm2 render character spacing in a different way.

A: For zsh:
I found that the theme I was using was defining the branch glyph in a wrong way. In particular, I corrected defining on my theme file the variable ZSH_THEME_GIT_PROMPT_PREFIX=" %{$FG[075]%}<glyph> " where <glyph> is the symbol you want to use to represent git branch.
For vim:
I found the solution in this question.

because 0x2B60 and the others do not exist anymore you just have to update autoload/Pl/Parser.vim to look something like this:

    \ 'fancy': {
        \   'dividers': [ [0xe0b0], [0xe0b1], [0xe0b2], [0xe0b3] ]
        \ , 'symbols' : {
                \   'BRANCH': [0xe0a0]
                \ , 'RO'    : [0xe0a4]
                \ , 'FT'    : [0xe0a2, 0xe0a3]
                \ , 'LINE'  : [0xe0a1]
        \ },
    \ }


text:
Q: PHP str_replace scraped content with wild card? I'm looking for a solution to strip some HTML from a scraped HTML page. The page has some repetitive data I would like to delete so I tried with preg_replace() to delete the variable data.
Data I want to strip:
Producent:Example
Groep:Example1
Type:Example2
....
...

Must be like this afterwards:
Producent:Example
Groep:Example1
Type:Example2

So a big piece is the same except the word within the data-title piece. How could I delete this piece of data?
I tried a few things like this one:
$pattern = '//';
$tech_specs = str_replace($pattern,"", $tech_specs);

But that didn't work. Is there any solution to this?

A: Just use a wildcard:
$newstr = preg_replace('//', '', $str);

.*? means match anything but don't be greedy

A: Assuming that the string looked like this:
$string = 'Producent:Example';

You could get the beginning and the end of the string with this:
preg_match('/^(\w+:).*\>(\w+)/', $string, $matches);

echo implode([$matches[1], $matches[2]]);

Which, in this case, will throw Producent:Example. So, then you could add this output to another variable/array you intend to use.
OR, since you mentioned replacing:
$string = preg_replace('/^(\w+:).*\>(\w+)/', '$1$2', $string);

But then again, checking as it would probably come in a variable number of lines:
$string = 'Producent:Example
Groep:Example1
Type:Example2';

$stringRows = explode(PHP_EOL, $string);

$pattern = '/^(\w+:).*\>(\w+)/';
$replacement = '$1$2';
foreach ($stringRows as &$stringRow) {
    $stringRow = preg_replace($pattern, $replacement, $stringRow);
}

$string = implode(PHP_EOL, $stringRows);

Which will then output the string like you expect.
Explaining my regex:
the first group catches the first word until the two dots :, then another group to catch the last word. I had previously specified anchors for both ends, but when breaking each line this wouldn't work as expected, so I kept only the beginning.
^(\w+:) => the word in the beginning of the string until two dots appear
.*\>    => everything else until smaller symbol appears (escaped by slash)
(\w+)   => the word after the smaller than symbol

A: Well maybe my question wasn't that good written. I had a table which I needed to scrape from a website. I needed the info in the table, but had to cleanup some parts as mentioned. The solution I finally made was this one and it works. It still has a little work to do with manual replacements but that is because of the stupid " they use for inch. ;-)
Solution:
   \\ find the table in the sourcecode
   foreach($techdata->find('table') as $table){

    \\ filter out the rows
    foreach($table->find('tr') as $row){

    \\ take the innertext using simplehtmldom
    $tech_specs = $row->innertext;

    \\ strip some 'garbage'
    $tech_specs = str_replace("  \t\t\t\t\t\t\t\t\t\t\t","", $tech_specs);

    \\ find the first word of the string so I can use it
    $spec1 = explode('	', $tech_specs)[0];

    \\ use the found string to strip down the rest of the table
    $tech_specs = str_replace("",":", $tech_specs);

    \\ manual correction because of the " used
    $tech_specs = str_replace("",":", $tech_specs);

    \\ manual correction because of the " used
    $tech_specs = str_replace("",":", $tech_specs);

    \\ strip some 'garbage'
    $tech_specs = str_replace("\t\t\t\t\t\t\t\t\t\t","\n", $tech_specs);
    $tech_specs = str_replace("	","", $tech_specs);
    $tech_specs = str_replace("  ","", $tech_specs);

    \\ put the clean row in an array ready for usage
    $specs[] = $tech_specs;
    }
  }


text:
Q: Image resize - maintain aspect ratio How could I resize an image and still keep it's aspect ratio?
This is the method that I use :
private static BufferedImage resizeImage(BufferedImage originalImage,
            int type) {
        BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT,
                type);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
        g.dispose();

        return resizedImage;
    }

The type variable :
BufferedImage original = ImageIO.read(new File(imagePath));
int type = original.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
                    : original.getType();

The problem is that some images are correctly resized but others lose their aspect ratio because of the IMG_WIDTH and IMG_HEIGHT.
Is there a way to get the original image dimensions and then apply some kind of proportion resize to maintain the aspect ratio of the resized image?

A: Why don't you use originalImage.getWidth() and originalImage.getHeight()? Then you can easily calculate aspect ratio. Don't forget that int/int = int, so you need to do
double ratio = 1.0 * originalImage.getWidth() / originalImage.getHeight();

or

double ratio = (double) originalImage.getWidth() / originalImage.getHeight();

Regarding the additional math, you can calculate
int height = (int) IMG_WIDTH/ratio;

int width = (int) IMG_HEIGHT*ratio;

Then see which one fits your needs better and resize to (IMG_WIDTH, height) or (width, IMG_HEIGHT)

A: To get the image size, see getWidth()/getHeight().  The rest is just some relatively simple math.
Presuming the IMG_WIDTH & IMG_HEIGHT represent the largest size desired:

*

*Find which is going to hit the limit first.

*Calculate the ratio between the natural size and that maximum size.

*Multiply the other image dimension by the same ratio.


text:
Q: solution of x and y for non standard eclipse equation with my basic math knowledge and search I found out that for a standard eclipse equation $x^2 / a^2 + y^2/b^2 = 1$, we can find out $x$ and $y$ by setting $y$ and $x$ intercept $0$.
But if the equation is of the form $x^2 + xy + 41y^2 = n$, how do we make a standard formula for $x$ and $y$ ?

A: Note that in a more general form, your equation is of the form:
$${\alpha _1}{x_1}^2 + 2{\alpha _2}{x_1}{x_2} + {\alpha _3}{x_2}^2 = {\alpha _0}$$
which using the matrix notion, may be written as:
$$\left[ {\begin{array}{*{20}{c}}
  {{x_1}}&{{x_2}}
\end{array}} \right]\left[ {\begin{array}{*{20}{c}}
  {{\alpha _1}}&{{\alpha _2}} \\
  {{\alpha _2}}&{{\alpha _3}}
\end{array}} \right]\left[ \begin{gathered}
  {x_1} \hfill \\
  {x_2} \hfill \\
\end{gathered}  \right] = {\alpha _0}$$
Now, assuming a general linear transformation of the form $Y = LX$, where $X = \left[ \begin{gathered}
  {x_1} \hfill \\
  {x_2} \hfill \\
\end{gathered}  \right]$, one may re-write the original equation as:
$${Y^{\text{T}}}{\left( {{L^{ - 1}}} \right)^{\text{T}}}\left[ {\begin{array}{*{20}{c}}
  {{\alpha _1}}&{{\alpha _2}} \\
  {{\alpha _2}}&{{\alpha _3}}
\end{array}} \right]{L^{ - 1}}Y = {\alpha _0}$$
Using eigen-decomposition, the symmetric coefficient matrix could be re-written as:
$$\left[ {\begin{array}{*{20}{c}}
  {{\alpha _1}}&{{\alpha _2}} \\
  {{\alpha _2}}&{{\alpha _3}}
\end{array}} \right] = PD{P^{\text{T}}}$$
where $D$ is a diagonal matrix. Substituting in the equation on has:
$${Y^{\text{T}}}{\left( {{L^{ - 1}}} \right)^{\text{T}}}PD{P^{\text{T}}}{L^{ - 1}}Y = {\alpha _0}$$
By factoring, one may write the above as:
$$\left( {{P^{\text{T}}}{L^{ - 1}}Y} \right)D\left( {{P^{\text{T}}}{L^{ - 1}}Y} \right) = {\alpha _0}$$
Since in the final form, no cross terms (e.g. ${y_1}{y_2}$) are allowed, one must enforce:
$${P^{\text{T}}}{L^{ - 1}} = I$$
which leads to:
$$L = {P^{\text{T}}}$$
So in summary, you should decompose your coefficients matrix, and the linear transformation matrix which is simply ${P^{\text{T}}}$ would transform your equation into your desired canonical form.


text:
Q: why do I get a single field value in Django formset_factory? when I checked formset_factory validation and get fields to value from formset it returns only one field value from formset. But I can not find any problem in my code. please help me to solve the problem.
My form.py:
class SbTitleForm(forms.Form):
    sb_title = forms.CharField(required=False)
    sb_permission = forms.BooleanField(required=False)

SbTitleFormSet = formset_factory(SbTitleForm, extra=0)

My view.py:
def menuuser(request):
    sbtitle = SbTitle.objects.all().values()
    sbtitle_form = SbTitleFormSet(initial=sbtitle)
    if request.method == 'POST':
        sbtitle_form = SbTitleForm(request.POST, initial=sbtitle)
        if sbtitle_form.is_valid():
            print(sbtitle_form.cleaned_data)

    context = {
        'sbtitle_form':sbtitle_form,
    }
    return render(request, 'admins/user_role/user_permission.html', context)

My HTML:
{% extends 'base/base.html' %}
{% load static %}
{% block content %}

    <form class="form-horizontal" action="" method="post">
    {% csrf_token %}
    {{ sbtitle_form.management_form }}
    {{ sbitleelement_form.management_form }}

                        Sidebar Title

                    {% for field in sbtitle_form %}

{{ field.sb_title.value }} {{ field.sb_permission }}
{{ field.errors.as_text }}

                    {% endfor %}

            <button class="btn btn-lg btn-primary" type="submit">Save</button>

    </form>

{% endblock %}

when I try to print(sbtitle_form.cleaned_data) its return only one field value like as {'sb_title': '', 'sb_permission': False}. I can not get other field value in formset. please help me to solve the problem.

A: sbtitle_form = SbTitleForm(request.POST, initial=sbtitle)
shoud be:
sbtitle_form = SbTitleFormSet(request.POST, initial=sbtitle)
def menuuser(request):
    sbtitle = SbTitle.objects.all().values()
    sbtitle_form = SbTitleFormSet(initial=sbtitle)
    if request.method == 'POST':
        sbtitle_form = SbTitleFormSet(request.POST, initial=sbtitle) # <----
        if sbtitle_form.is_valid():
            print(form.cleaned_data)
    context = {
        'sbtitle_form':sbtitle_form,
    }
    return render(request, 'admins/user_role/user_permission.html', context)

If you want to access to each of forms:
def menuuser(request):
    sbtitle = SbTitle.objects.all().values()
    sbtitle_form = SbTitleFormSet(initial=sbtitle)
    if request.method == 'POST':
        sbtitle_form = SbTitleFormSet(request.POST, initial=sbtitle)
        if sbtitle_form.is_valid():
            for form in sbtitle_form.forms:  # <----
                print(form.cleaned_data)
    context = {
        'sbtitle_form':sbtitle_form,
    }
    return render(request, 'admins/user_role/user_permission.html', context)


text:
Q: Message level secutiy with SSL in WCF I am trying to use WCF to design web service over internet. The requirement is that we need to
provide the TLS (Transport Layer Security) and MLS (Message Layer Security). For this purpose, we are using "ws2007HttpBinding" with security mode as "TransportWithMessageCredential". Here, I find that the request is transferred over SSL but when using Fiddler (for https) I find that the soap body is in clear text format.
For the transport level security, I have used ClientCredentialType as "None" and for message level security, I have used "Certificate" as ClientCredentialType.
I am using .net framework 3.5.
For your information, I am using different certificate for SSL & server.
My Web.config for Server is as follows.
<system.serviceModel>
    <services>
        <service behaviorConfiguration="API_WCF.Service1Behavior" name="API_WCF.API">
            <endpoint address="https://localhost/API_WCF/API.svc" name="API" binding="ws2007HttpBinding" bindingConfiguration="customWsHttpBinding" contract="API_WCF.IARDAPI">
                <identity>
                    <dns />
                </identity>
            </endpoint>
            <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
        </service>
    </services>
    <bindings>
        <ws2007HttpBinding>
            <binding name="customWsHttpBinding">
      <!-- For http  -->
      <!--
      <security mode="Message">
        <message clientCredentialType="Certificate" negotiateServiceCredential="false" establishSecurityContext="false"/>
      </security>
      -->
      <!-- For https  -->
        <security mode="TransportWithMessageCredential">
        <transport clientCredentialType="None"/>
                    <message clientCredentialType="Certificate" negotiateServiceCredential="false" establishSecurityContext="false"/>
                </security>
            </binding>
        </ws2007HttpBinding>
    </bindings>
    <behaviors>
        <serviceBehaviors>
            <behavior name="API_WCF.Service1Behavior">
                <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
                <serviceMetadata httpsGetEnabled="true" httpsGetUrl="https://localhost/API_WCF/API.svc/API"/>
                <serviceCredentials>
                    <serviceCertificate findValue="CN=WSE2QuickStartServer" storeLocation="LocalMachine" x509FindType="FindBySubjectDistinguishedName" storeName="My"/>
                    <clientCertificate>
                        <authentication certificateValidationMode="ChainTrust" revocationMode="NoCheck"/>
                    </clientCertificate>
                </serviceCredentials>

                <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
                <serviceDebug includeExceptionDetailInFaults="true"/>

            </behavior>
        </serviceBehaviors>
    </behaviors>
    <diagnostics wmiProviderEnabled="true" performanceCounters="ServiceOnly">
        <messageLogging logEntireMessage="true" logMalformedMessages="true" logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" maxMessagesToLog="3000"/>
    </diagnostics>
</system.serviceModel>

Kindly guide how to achieve to message level security with transport layer security in WCF over internet.

A: If you need to run fiddler in HTTPS mode to view your WCF messages, then you are already using TLS!
If the messages are encrypted while using fiddler in HTTP mode this indicates that your messages are being secured before being sent over the wire. See: How to: Use Transport Security and Message Credentials
The use of TransportWithMessageCredential means that in a HTTP scenario your service will be protected through HTTPS and you can opt to have an additional in-message credential(MLS).

A: If you want SSL and message level encryption (rather than just message level authentication) then you need to use a custom binding. For example (actual config depends on what you want):
<textMessageEncoding messageVersion="Soap11" />
<security authenticationMode="MutualCertificate" messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"></security>
<httpsTransport />


text:
Q: Memory management error on persistent store error I am getting an error that seems pretty clearly to be a message to a deallocated object, but I cannot figure out where I am managing memory wrong. This is my code to create the persistent store coordinator. It's based on the Core Data application template. I might have changed it a bit, but not much I think.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }

    /* Reminder: in Simulator this is in /Users/<username>/Library/Application Support/iPhone Simulator/User/Applications/<bundleid>/Documents/Wordfare.sqlite */
    NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"Wordfare.sqlite"]];

    NSError *error;
    persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
        [persistentStoreCoordinator release];
        persistentStoreCoordinator = nil;
    }

    return persistentStoreCoordinator;
}

The problem happens when I get an error from addPersistentStore, because I changed my model and I'm trying to open a store that was created with the previous model. Of course one answer is, "Don't do that." I won't, but I want the code to be robust. The above code runs without complaint, but then when I press the home button, the app crashes with this error:

2011-11-02 16:39:53.751 Wordfare[11137:207] -[__NSCFArray tryLock]: unrecognized selector sent to instance 0x5a122f0
2011-11-02 16:39:53.783 Wordfare[11137:207] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray tryLock]: unrecognized selector sent to instance 0x5a122f0'
* Call stack at first throw:
(
0   CoreFoundation                      0x012ed5a9 __exceptionPreprocess + 185
1   libobjc.A.dylib                     0x01441313 objc_exception_throw + 44
2   CoreFoundation                      0x012ef0bb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3   CoreFoundation                      0x0125e966 forwarding + 966
4   CoreFoundation                      0x0125e522 _CF_forwarding_prep_0 + 50
5   CoreData                            0x010d9ef0 -[_NSSQLCoreConnectionObsever _purgeCaches:] + 112
6   Foundation                          0x00370669 _nsnote_callback + 145
7   CoreFoundation                      0x012c59f9 __CFXNotificationPost_old + 745
8   CoreFoundation                      0x0124493a _CFXNotificationPostNotification + 186
9   Foundation                          0x0036620e -[NSNotificationCenter postNotificationName:object:userInfo:] + 134
10  UIKit                               0x0060aa0b -[UIApplication _handleApplicationSuspend:eventInfo:] + 554
11  UIKit                               0x00614039 -[UIApplication handleEvent:withNewEvent:] + 4127
12  UIKit                               0x0060babf -[UIApplication sendEvent:] + 71
13  UIKit                               0x00610f2e _UIApplicationHandleEvent + 7576
14  GraphicsServices                    0x03851992 PurpleEventCallback + 1550
15  CoreFoundation                      0x012ce944 CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION + 52
16  CoreFoundation                      0x0122ecf7 __CFRunLoopDoSource1 + 215
17  CoreFoundation                      0x0122bf83 __CFRunLoopRun + 979
18  CoreFoundation                      0x0122b840 CFRunLoopRunSpecific + 208
19  CoreFoundation                      0x0122b761 CFRunLoopRunInMode + 97
20  GraphicsServices                    0x038501c4 GSEventRunModal + 217
21  GraphicsServices                    0x03850289 GSEventRun + 115
22  UIKit                               0x00614c93 UIApplicationMain + 1160
23  Wordfare                            0x00002224 main + 102
24  Wordfare                            0x000021b5 start + 53
)
terminate called after throwing an instance of 'NSException'

Sorry for the double-spacing. I couldn't figure out the formatting.
It looks like an __NSCFArray has happened to move in after the persistent store coordinator was deallocated, but something still has a pointer to the persistent store and is trying to call its tryLock.
It's really hard to tell what that could be. I allocate the persistent store coordinator, call addPersistentStore, then release it and set it to nil. Nothing in my code could have got a reference to it outside that method. The only thing I can imagine getting a reference to it would be the managedObjectModel. I tried releasing that too but that got a different error.
If I comment out the line that releases persistentStoreCoordinator, and just set it to nil, then it runs fine, but that can't be right. persistentStoreCoordinator is an instance variable of course. I allocated it; I should release it if I'm discarding the reference to it.
How am I supposed to clean up a persistent store coordinator after an error?
Additional: I have confirmed that the unrecognized selector is getting sent to the memory address of the persistent store coordinator.

A: Not a Core Data answer, but you should run with zombies enabled (in recent Xcodes, just hit the checkbox in the Debug part of the scheme).


text:
Q: Is it okay to just add a page or two PHP page to add some functionality to a Drupal site? I'm not familiar with Drupal, really.  I can dig around the admin interface and navigate the directories and find the files that I need to just fine as well.
What I'm really not familiar with is adding modules or extending modules.  The site currently takes an order and sets up recurring payments through Ubercart and uses Authorize.net as a gateway.  Right now, when a payment fails, a single e-mail gets sent out to the admin.  We'd like to extend it to send an e-mail to the user and let them change their payment information through another page on the site.
Authorize has a service called Silent Post URL that basically just posts a carbon copy in XML to whatever URL you give it.  We'd like to accept that XML, deserialize it, parse the data, send a notice to the user and give them the page for updating their information.
So, I guess it'll be two PHP pages.  One for the XML API call from Authorize.net, and then one for the page for the users' to update their payment information.
Could I just create two simple pages each handling their own tasks, or should I check out properly extending a module?  If it's appropriate for me to write up the pages and not have to hook them into the module, what would be the best way to handle setting up what needs to get done?
(The most experience I've had with extending a PHP site has been hacking away at someone else' poorly constructed, custom framework, so if anyone has any good resources perhaps on PHP best practices that they could share through a PM or a comment, I'd appreciate It)
(Also, I'm still getting the hang of Stack Exchange, so if this isn't appropriate please let me know.  I'll delete it.)

A: If the new page doesn't use users from Drupal site, doesn't rely on any pages in your Drupal site, doesn't use the theme of your Drupal site and doesn't otherwise have any interaction with the site, you might want to do it that way.
I still wouldn't.
Part of using any platform is learning to work within it so you can use all the parts of it to your advantage.  You're already using Drupal users and messaging which means you're using the database.  You can either figure out how to use Drupal to access them or you can go build your own page with its own database settings, it's own security, figure out how to manually tie into Drupal users and messaging and hope that you don't break anything while you're in there.

A: The problem is always the maintenance. Are you willing to patch the page every time Drupal gets patched? Are you willing to re-integrate it every time something changes?
It's a better plan to find a module that does what you need, that's still under active development. Anything else, and you're making a commitment to maintenance that will last as long as the site.

A: I am not too familiar with drupal either but from my experience so far many modules are built with flexibility in mind. I don't know how your site is setup but my approach would be to research and setup a test implementing a automated emailing system that links up to the admin's payment warning.There should be a module for each step.
Not sure if clear:-> I would try and fit in modules that have been shown to work before you modify or make your own. Many modules can work together (think Legos). I don't want to link to specific modules with a simple plan as I am not confident in my knowlege.
Vague Plan: use (module) Parsing API + (module) Email API + (module) Payment API though you should have it reroute to your current payment system.
So Three modules with some customization and you could have a decent solution without code.
Hope that isn't to convoluted.