text:
Q: Create UITextRange from NSRange I need to find the pixel-frame for different ranges in a textview. I'm using the - (CGRect)firstRectForRange:(UITextRange *)range; to do it. However I can't find out how to actually create a UITextRange.
Basically this is what I'm looking for:
- (CGRect)frameOfTextRange:(NSRange)range inTextView:(UITextView *)textView {

    UITextRange*range2 = [UITextRange rangeWithNSRange:range]; //DOES NOT EXIST
    CGRect rect = [textView firstRectForRange:range2];
    return rect;
}

Apple says one has to subclass UITextRange and UITextPosition in order to adopt the UITextInput protocol. I don't do that, but I tried anyway, following the doc's example code and passing the subclass to firstRectForRange which resulted in crashing.
If there is a easier way of adding different colored UILables to a textview, please tell me. I have tried using UIWebView with content editable set to TRUE, but I'm not fond of communicating with JS, and coloring is the only thing I need.
Thanks in advance.

A: To the title question, here is a Swift 2 extension that creates a UITextRange from an NSRange.
The only initializer for UITextRange is a instance method on the UITextInput protocol, thus the extension also requires you pass in UITextInput such as UITextField or UITextView.
extension NSRange {
    func toTextRange(textInput textInput:UITextInput) -> UITextRange? {
        if let rangeStart = textInput.positionFromPosition(textInput.beginningOfDocument, offset: location),
            rangeEnd = textInput.positionFromPosition(rangeStart, offset: length) {
            return textInput.textRangeFromPosition(rangeStart, toPosition: rangeEnd)
        }
        return nil
    }
}

A: It is a bit ridiculous that seems to be so complicated.
A simple "workaround" would be to select the range (accepts NSRange) and then read the selectedTextRange (returns UITextRange):
- (CGRect)frameOfTextRange:(NSRange)range inTextView:(UITextView *)textView {
    textView.selectedRange = range;
    UITextRange *textRange = [textView selectedTextRange];
    CGRect rect = [textView firstRectForRange:textRange];
    return rect;
}

This worked for me even if the textView is not first responder.

If you don't want the selection to persist, you can either reset the selectedRange:
textView.selectedRange = NSMakeRange(0, 0);

...or save the current selection and restore it afterwards
NSRange oldRange = textView.selectedRange;
// do something
// then check if the range is still valid and
textView.selectedRange = oldRange;

A: Swift 4 of Andrew Schreiber's answer for easy copy/paste
extension NSRange {
    func toTextRange(textInput:UITextInput) -> UITextRange? {
        if let rangeStart = textInput.position(from: textInput.beginningOfDocument, offset: location),
            let rangeEnd = textInput.position(from: rangeStart, offset: length) {
            return textInput.textRange(from: rangeStart, to: rangeEnd)
        }
        return nil
    }
}

A: You can create a text range with the method textRangeFromPosition:toPosition. This method requires two positions, so you need to compute the positions for the start and the end of your range. That is done with the method positionFromPosition:offset, which returns a position from another position and a character offset.
- (CGRect)frameOfTextRange:(NSRange)range inTextView:(UITextView *)textView
{
    UITextPosition *beginning = textView.beginningOfDocument;
    UITextPosition *start = [textView positionFromPosition:beginning offset:range.location];
    UITextPosition *end = [textView positionFromPosition:start offset:range.length];
    UITextRange *textRange = [textView textRangeFromPosition:start toPosition:end];
    CGRect rect = [textView firstRectForRange:textRange];
    return [textView convertRect:rect fromView:textView.textInputView];
}

A: Swift 4 of Nicolas Bachschmidt's answer as an UITextView extension using swifty Range<String.Index> instead of NSRange:
extension UITextView {
    func frame(ofTextRange range: Range<String.Index>?) -> CGRect? {
        guard let range = range else { return nil }
        let length = range.upperBound.encodedOffset-range.lowerBound.encodedOffset
        guard
            let start = position(from: beginningOfDocument, offset: range.lowerBound.encodedOffset),
            let end = position(from: start, offset: length),
            let txtRange = textRange(from: start, to: end)
            else { return nil }
        let rect = self.firstRect(for: txtRange)
        return self.convert(rect, to: textInputView)
    }
}

Possible use:
guard let rect = textView.frame(ofTextRange: text.range(of: "awesome")) else { return }
let awesomeView = UIView()
awesomeView.frame = rect.insetBy(dx: -3.0, dy: 0)
awesomeView.layer.borderColor = UIColor.black.cgColor
awesomeView.layer.borderWidth = 1.0
awesomeView.layer.cornerRadius = 3
self.view.insertSubview(awesomeView, belowSubview: textView)

A: - (CGRect)frameOfTextRange:(NSRange)range inTextView:(UITextView *)textView {
    UITextRange *textRange = [[textView _inputController] _textRangeFromNSRange:range]; // Private
    CGRect rect = [textView firstRectForRange:textRange];
    return rect;
}

A: Here is explain.

A UITextRange object represents a range of characters in a text
  container; in other words, it identifies a starting index and an
  ending index in string backing a text-entry object.
Classes that adopt the UITextInput protocol must create custom
  UITextRange objects for representing ranges within the text managed by
  the class. The starting and ending indexes of the range are
  represented by UITextPosition objects. The text system uses both
  UITextRange and UITextPosition objects for communicating text-layout
  information. There are two reasons for using objects for text ranges
  rather than primitive types such as NSRange:
Some documents contain nested elements (for example, HTML tags and
  embedded objects) and you need to track both absolute position and
  position in the visible text.
The WebKit framework, which the iPhone text system is based on,
  requires that text indexes and offsets be represented by objects.
If you adopt the UITextInput protocol, you must create a custom
  UITextRange subclass as well as a custom UITextPosition subclass.

For example like in those sources


text:
Q: Issue with softlink I deleted symbolic link which was pointing to x binary, recreated a same link pointing to y binary i.e. now it's pointing to y binary instead of x binary.
When I am running binary from its location it's giving correct result. Let say the binary is at location
$/tmp/value>./y
Output is correct
If  I go to another directory,
/abd/def>/tmp/value/y
Its giving me output of x binary
Can anyone tell me why I am getting some issue.

A: Perhaps value dir inside tmp dir is itself a symlink that changed inbetween? We're guessing here.
ls -la /tmp
ls -la /tmp/value
ls -la /abc/def

A: Psychic debugging suggests you moved the directory that was current directory for your shell (or one of its parents) and are therefore now very confused.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Random UDP message received needs to be parsed to python file through rsyslog omprog I'm setting up a python script that will parse the inputs received via UDP from another server. Since the message or number of messages can be received randomly, I'm trying to rsyslog omprog to parse the inputs. However, I'm unable to read the message on UDP and unable to send the input received as parameter to python using omprog
Receiving syslog message from particular server will be stored in /var/log/pcrf_notification.log Therefore, I configured the rsyslog.conf like below:
         [root@PORSG1NT101A]# vi /etc/rsyslog.conf
         $ModLoad imudp
         $UDPServerRun 514

         $template RemoteLogs,"/var/log/%HOSTNAME%/pcrf_notification.log"
         *.* ?RemoteLogs

The content withing the pcrf_notification.log will be:
 Mar 15 16:27:30 PORPF0MP1 Policy Syslog: 5540149665,123,5000001,2019-03-15T16:27:30.290

 Mar 15 16:27:52 PORPF0MP1 Policy Syslog: 5540149665,123,5000001,2019-03-15T16:27:52.895

Now i need to send each line when received to a python script. This is I'm failing at.
For example, I need to send
 "Mar 15 16:27:52 PORPF0MP1 Policy Syslog: 5540149665,123,5000001,2019-03-15T16:27:52.895"

to a python script.
I created a pcrf_scripting.conf file in rsyslog.d folder
 [root@PORSG1NT101A rsyslog.d]# vi /etc/rsyslog.d/pcrf_scripting.conf
                   $ModLoad omprog
                  :inputname, isequal, "imudp" action(type="omprog"
                   binary="/tmp/hello.py --param1 a --param2 b"
                   template="RSYSLOG_TraditionalFileFormat")

I need to replace --param1 a --param2 b with each line.

A: This minimal example worked for me (rsyslogd version 8.30.0). In /etc/rsyslog.conf we have
$ModLoad imudp # UDP listener
$UDPServerRun 514
$ModLoad omprog
:inputname, isequal, "imudp"  action(type="omprog"
  binary="/tmp/prog.py" template="RSYSLOG_TraditionalFileFormat")

In /tmp/prog.py we have
#!/usr/bin/python3
import sys
with open("/tmp/output","w",encoding='utf8',errors='ignore') as fd:
    for data in sys.stdin:
        print("got data: %s" % data[:-1], file=fd, flush=True)

When a udp packet arrives it is passed through to the python program which prints it to file /tmp/output. Make sure to chmod a+rx /tmp/prog.py.


text:
Q: Почему при передаче параметра в массиве POST, условие не срабатывает? <?php error_reporting(-1);
header('Content-Type: text/html; charset=utf-8');
ini_set('display_errors', 'On');

if(isset($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
    echo 'Всё ок!';
}

?>

<form action="" method "post">
    <input type="text" name="email">
    <input type="submit">
</form>

Ничего не отображается, я уже облегчал, убрал, то что идёт после && и всё рано не работает, почему у меня постоянно не работают такие простые вещи?

A: Вы неправильно указали атрибут method формы:
<form action="" method="post">
    <input type="text" name="email">
    <input type="submit">
</form>

А по умолчанию форма отправляет данные методом get, и в php искать его надо было в $_GET.

A: У Вас просто не хватает знака равно...
method="post"
... очень сильно помогает дампить код:
var_dump($_POST['email']);
die();


text:
Q: How to implement ACID Transaction in Java? I have to perform 2 actions, one to save data in db, one to save bytes on filesystem, and I would like these 2 actions to be executed atomically.
Basically, if action 1 fails, the whole process fails, and if action 2 fails, same thing and db action is rollbacked.
public void doAction() {
   this.saveData();
   this.saveFile();
}

How is it possible to perform ACID transaction which involves database and filesystem in Java ?

A: In general this is just impossible.
File systems are not a transactional resource (unless you're consciously and deliberately on a journaled filesystem or so) and even if they were there would still be the requirement that they can engage in a 2PC transaction, together with the db transaction, under an "external" transaction controller (who can steer and control the two-phase-commit process that will be required).  Your chances are slim.
You can try to do all sorts of thing yourself, e.g. keep a log of the pre-write state of any file (or file portions) written to, but basically you are then recreating a journaled file system yourself and unless you do so fully and completely (not an easy task), your system will still have (serious) holes in it.

A: ACID requires not only to be able to rollback changes when one of the operations fail, it also requires isolation from other transaction. As soon as you store data to a file, changes get visible to others. Either committing the database before or after is a violation of the ACID rules.
However, you may still find a solution for the actual problem you have to solve. E.g. by synchronizing file access with database data (store file names and whether data is ready, for instance).
Also consider storing the data in a blob instead of a file.
Another more complicated way is to lock access to the data by the file system, so when a transaction is writing, all others are blocked from reading and writing of the file and the corresponding database data at the same time. E.g. Use an empty lock file (original-filename.lock) that blocks others from reading / writing the data in that file. This only works if you have a 1-to-1 relation to database data and if you don't do any complex querying (you should not read the data while it is locked). And of course it only works if you have control over everything that accesses the file or the database. It may not be very efficient. You still need to implement a rollback mechanism for the file changes (usually copy-rename stuff).
There are a couple of other solutions or workarounds, depending on your specific system. This questions is probably "too broad".


text:
Q: Getting relative source/destination in Gulp task Let's say I have a file at /Users/me/app/src/scripts/foo.js. I set up a gulp tasks that writes this file to /Users/me/app/dist/scripts/foo.js:
gulp.src('src/scripts/foo.js', base: 'src')
.pipe(...)
.pipe(gulp.dest('dist'))

I'm writing a simple plugin and need to know scripts/foo.js. I was expecting file.relative to be this partial path, but instead it provides foo.js. I don't see a way to get scripts/foo.js from any combination of file.path, file.cwd, file.base, etc.
How can I get the part of the path I need?

A: Assuming that you want the path relative to your specified base, you would want to use something like node's path module to do the extraction:
var path = require('path');
// this is how you get the relative path from a vinyl file instance
path.relative(path.join(file.cwd, file.base), file.path);

Here is an example gulpfile using your example:
var path = require('path'),
    gulp = require('gulp'),
    through = require('through2');

function parsePath() {
    return through.obj(function (file, enc, cb) {
        console.log(file.base);
        console.log(file.cwd);
        console.log(file.path);
        console.log(path.relative(path.join(file.cwd, file.base), file.path))
        cb();
    });
}

gulp.task('default', function () {
    gulp.src('src/scripts/foo.js', { base: 'src'})
        .pipe(parsePath())
        .pipe(gulp.dest('dist'));
});

Here is the output when I run this gulpfile:
src
/Volumes/Data/Project/sandbox/gulp-ex
/Volumes/Data/Project/sandbox/gulp-ex/src/scripts/foo.js
scripts/foo.js

Here is the project folder structure
gulp-ex/
    |_ gulpfile.js
    |_ src/scripts/foo.js
    |_ dist


text:
Q: MBP Headphone Jack Doesn't Work in OS X but does in Windows I bought a brand new Mid-2012 MacBook Pro 13" from Apple. Ever since I've had it, it's had this quirky bug where headphones are only recognized if they're plugged in before the computer is woken up: the computer has to be either turned off or put to sleep every time I want to plug in my headphones. I called Apple Support and went through all the usual stuff and some not-so-usual stuff, but the problem still persists. I, along with multiple tech support guys from Apple, finally just concluded it was a hardware issue. I never bothered to take it into the store to get fixed, and the problem never went away (no surprise there).
Today, after living with this and doing nothing about it for months, I installed a fresh copy of Windows 7 Enterprise using BootCamp, and in Windows, headphones work perfectly all the time. I've just been living with this issue since I've had a workaround, but this makes me think there must be some way of making the jack work properly in OS X, too.
Any ideas on what could be causing this problem or how to fix it? What would be different about Windows 7 that would make it act differently?

Here's what I've already tried:

*

*Resetting the PRAM and SMC

*Ensuring that no weird audio drivers or services were installed (the Apple Support guy and I went through my /Library and ~/Library with a fine-tooth comb)

*Re-installing the OS fresh (in fact, since then, I've changed hard drives and installed fresh a second time)

*Cleaning out the headphone jack itself

*Using a different set of headphones (any of them that use the 1/8th inch jack don't work in OS X but do in Windows; Bluetooth and USB headphones work fine)

*Ensuring that everything is attached correctly inside the MBP (no frayed wires, no loose connections, etc.)

A: It's entirely likely you have a situation where the drivers on Windows are not detecting a faulty hardware condition and thus continue to send signal to the copper ports. Your Mac may be sending the audio to the TOSlink (optical) portion of the jack.
See this other question for details and a similar answer by @chico on his experience getting around this hardware failure by using different OS / drivers.

A: I have experience with the same issue and think it's Apple fault in how OS X handles the dual function of its audio output. My solution was to install Ubuntu, it doesn't mute it anymore.
Since using Ubuntu 13.04 now on my macbook pro early 2011, it never suffers from the infamous headphone jack problem. Removing the headphones, the internal speakers work, plug it in, the headphone works.
Here're some articles that explain what's up with the headphone jack, and the root cause of this behavior:

*

*Continuing issues (and solutions) for the MBP's silent speaker problem - 4/2012

*Getting Sound Back on a Macbook Pro (when the headphone is stuck on Optical) - 8/2012

*Apple's finicky headphone jacks frustrate MacBook owners - 2/2009
On OS X, it just doesn't work. If I dare plugging in the headphones, I know that when I take it out, internal speakers will stop working, they will be muted, and not come back after a while. I've stopped plugging stuff in and out trying to make it work.
I just installed a new OS that works. I suspect Ubuntu, maybe, just ignores all the stuff about the dual mode of the headphone jack.
Hardware resolutions for this problem span from cleaning the output to replacing the logic board. IMO, its Apple fault to produce such a delicate hardware device and not provide means for controlling the dual-mode of the audio output through software, which, as can be seen, can be done.


text:
Q: What is the point of @JoinColumn in hibernate? I know that @JoinColumn is used for creating the foreign key column, but my question is little bit another.
I noticed that if I have main entity with mapped by and dependent entity with no @JoinColumn, than the hibernate creates two tables correctly anyway.
For example, I have Passport ans Person:
@NoArgsConstructor
@AllArgsConstructor
@RequiredArgsConstructor
@Data
@Entity

public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @NonNull
    private String name;
    @NonNull
    private int age;
    @OneToOne(mappedBy = "person")
    Passport passport;
}

Passport entity:
@NoArgsConstructor
@AllArgsConstructor
@RequiredArgsConstructor
@Data
@Entity

public class Passport {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @NonNull
    private int series;
    @NonNull
    private int number;

    @OneToOne
//    @JoinColumn(name = "person_id") //with or without this line the hibernate creates person_id in the Passport table
    @ToString.Exclude
    Person person;

}

In the both ways (with or without @JoinColumn annotation) hibernte creates the following tables:
Person table:
###################
id ## name ## age #
###################

Passport table:
#####################################
id ## series ## number ## person_id #
#####################################

So what's the point of @JoinColumn annotation if there's no difference?

A: @JoinColumn indicates that this entity is the owner of the relationship, that the corresponding table has a column with a foreign key to the referenced table.
@JoinColumn annotation is not mandatory. If you will not specify it framework will perform default configuration instead. Hibernate and JPA follows convention over configuration. This means that the developer only needs to specify not standard aspects some custom definitions.
In case of @JoinColumn, the default column name will be generated like: [field_name]_[id_column_name].
In your case:
[field_name] - is person field of Passport entity.
[id_column_name] - is @Id column of related entity. It is id field of Person entity.
According to documentation:

2.2.5. Mapping entity associations/relationships
If no @JoinColumn is declared on the owner side, the defaults apply. A
join column(s) will be created in the owner table and its name will be
the concatenation of the name of the relationship in the owner side, _
(underscore), and the name of the primary key column(s) in the owned
side.

So if you need to override the default convention then that's exactly what @JoinColumn is for.
It covering:

*

*specify the name of the foreign key column

*specify the name of the column referenced by this foreign key column

*specify column definition

*specify or control the generation of a foreign key definition

*specify the name of the table that contains the column

*whether the property is a unique key

*whether the column is included in SQL UPDATE statements generated by the persistence provider


text:
Q: How do I use a range of numbers in if, elif, else functions in Python Here's my code.
def function():
    rng = randint(1,10)
    if rng == 1 or 2 or 3 or 4 or 5:
        print "option 1"
    elif rng == 6:
        print "option 2"
    elif rng == 7:
        print "option 3"
    else:
        print "option 4"

In the blank space in the if statement, I want the code to consider if rng equals a range of integers from 1 to 5. When I run this function, it always prints out "option 1", leading me to believe there's something wrong with the if statement, causing the code to automatically print option 1 and discard all other code. Is there another way to express "if rng == 1 to 5"?


text:
Q: How to create new activity in android studio I am completely new to Android Studio and I was wondering when I create a new class, it doesn't contain the method public void onCreate. For example in my main_activity you have the super.onCreate(savedInstanceState) that would let you connect to your layout and then do things with fields or buttons. My question is how can I do the same when I create a new class. Do I just copy the public void onCreate into the new class and go about it that way. Or do I extend from main_activity. Really confused and trying to understand this.

A: You can, but it will be complicated.
Simplest Way: What you can do is right click on the java folder, located on the left side in Android Studio. Then, go to "New" on the top. Look downwards and you will see "Activity". Hover on that and it will give you some different types of activities that you can create. By clicking on one of them, it automatically adds that activity to your AndroidManifest and it also creates the Java class, and XML file for the activity.
Longer Way: As you mentioned, you can copy and paste the onCreate method into the class. You would also have to add extends AppCompatActivity. Then, you will have to add the class to AndroidManifest by doing
   <activity
        android:name=".ActivityName"
        android:label="My Activity"
        android:theme="@style/MyAppTheme" />

Next, you will have to create an XML file. To the top of your file, you should add:
  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    **tools:context=".ActivityName"**>

Finally, you will have to go to your Java class and add the following in onCreate:
 super.onCreate(savedInstanceState);
 setContentView(R.layout.mylayoutfile);

These are two ways that you can create an activity.

A: Have a look at the resource link : Create New Activity
This will create java class and the xml interface at the same time and it will add necessary lines to manifest.xml too


text:
Q: Subpanel Edit View I have custom code on my Contacts Edit View via the file custom/modules/Contacts/views/view.edit.php. I want the same code to work for the Contact subpanel in other modules. How should I do this?
Below is the code I used:
In custom/modules/Contacts/view/view.customedit.php
require_once 'include/MVC/View/views/view.edit.php';

class ContactsViewEnjayedit extends ViewEdit
{
    public function __construct()
    {
        parent::ViewEdit();
        $this->useForSubpanel = true;
        $this->useModuleQuickCreateTemplate = true;
    }

    protected function _displayJavascript()
    {
        echo '<script type="text/javascript" src="custom/modules/Contacts/js/jquery-1.11.0.min.js"></script>';
        echo '<script type="text/javascript" src="custom/modules/Contacts/js/NjContact.js"></script>';
        parent::_displayJavascript();

    }
}

A: This took me way too long to figure out as well and I am happy to share the quite easy answer with you!
In your custom view.edit.php file add the following line inside the __construct() method:
$this->useForSubpanel = true;

That should do the trick!


text:
Q: Time estimation samples in big companies I need some real time estimation samples from big companies like google, facebook and apple etc.
I need the task description, time estimation for task, team members count and after all, the real time consumed for design, develop, test and deployment of result.
Is there any real data available? All documents about time estimation just talking about it without any real data.

A: The problem with this data is that everyone tries to keep thier tasks short. 1 day or less.
So then you are judging the description of the task. How much work is involved. But the descriptions will usually only have meaning in the context if the system.

*

*'fix the bug with the pricing in this edge case'

Unless you know the system at the time, judging the size of the task is impossible. It could be 2 min or 2 weeks.
Ok we can look at projects rather than tasks. The descriptions will be easier to judge, but then we have to consider requirements change, interaction with other ongoing projects, quality of the final product etc. No two projects will be comparable and that information isn't available.
You'll probably find that on average projects take 1 quarter of a year because that's the financial reporting period and they are sized accordlingly


text:
Q: How to modify the duplicate form in the database manager? I want to add some other field to this form that can be accessed from the Database Manager in Odoo

The data is sent to this controller:
@http.route('/web/database/duplicate', type='http', auth="none", methods=['POST'], csrf=False)
def duplicate(self, master_pwd, name, new_name):
    try:
        if not re.match(DBNAME_PATTERN, new_name):
            raise Exception(_('Invalid database name. Only alphanumerical characters, underscore, hyphen and dot are allowed.'))
        dispatch_rpc('db', 'duplicate_database', [master_pwd, name, new_name])
        return http.local_redirect('/web/database/manager')
    except Exception as e:
        error = "Database duplication error: %s" % (str(e) or repr(e))
        return self._render_template(error=error)

But the form is plain html, so I cannot inherit and modify any template:

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Duplicate Database

        <form id="form-duplicate-db" role="form" action="/web/database/duplicate" method="post">

            {{ master_input() }}

                Database Name
                <input id="name" type="text" name="name" class="form-control" required="required" readonly="readonly"/>

                New Name
                <input id="new_name" type="text" name="new_name" class="form-control" required="required" pattern="{{ pattern }}" title="Only alphanumerical characters, underscore, hyphen and dot are allowed"/>

            <input type="submit" value="Continue" class="btn btn-primary pull-right"/>

        </form>

I found a python code where this html is rendered
class Database(http.Controller):

    def _render_template(self, **d):
        d.setdefault('manage',True)
        d['insecure'] = odoo.tools.config.verify_admin_password('admin')
        d['list_db'] = odoo.tools.config['list_db']
        d['langs'] = odoo.service.db.exp_list_lang()
        d['countries'] = odoo.service.db.exp_list_countries()
        d['pattern'] = DBNAME_PATTERN
        # databases list
        d['databases'] = []
        try:
            d['databases'] = http.db_list()
            d['incompatible_databases'] = odoo.service.db.list_db_incompatible(d['databases'])
        except odoo.exceptions.AccessDenied:
            monodb = db_monodb()
            if monodb:
                d['databases'] = [monodb]
        return env.get_template("database_manager.html").render(d)

Should I modify this code in order to use another template? Or is there another more appropriate solution?
Is modifying the original code directly in the web module the only way to achieve this? Is there a way to change all this behaviour by inheriting the web module?

A: Sure, you can done it by a custom module.First You have to define your own html template as per your need , and then have to rewrite the controller which render the html file.
You can refer the following code to rewrite the controller.
from odoo.addons.web.controllers.main import Database  # importing base controller class

class MyDatabase(Database):
    def _render_template(self, **d):
       d.setdefault('manage',True)
       d['insecure'] = odoo.tools.config.verify_admin_password('admin')
       d['list_db'] = odoo.tools.config['list_db']
       d['langs'] = odoo.service.db.exp_list_lang()
       d['countries'] = odoo.service.db.exp_list_countries()
       d['pattern'] = DBNAME_PATTERN
       #additional parameters if any
       d['databases'] = []
       try:
           d['databases'] = http.db_list()
           d['incompatible_databases'] = odoo.service.db.list_db_incompatible(d['databases'])
       except odoo.exceptions.AccessDenied:
           monodb = db_monodb()
           if monodb:
               d['databases'] = [monodb]

       return env.get_template("your_modified_template.html").render(d)  #render your modified html template.

If you have any doubts have a look in to the code of This module.

A: Yes, you would need to overwrite the _render_template method of the web module.
And also you would need to create your own HTML template for that and pass it for the rendering.
from odoo.addons.web.controllers.main import db_monodb, Database as DB, env
import jinja2

loader = jinja2.PackageLoader('odoo.addons.your_custom_module_name', "views")
env = jinja2.Environment(loader=loader, autoescape=True)
env.filters["json"] = json.dumps

class Database(DB):
def _render_template(self, **d):
    d.setdefault('manage',True)
    d['insecure'] = odoo.tools.config['admin_passwd'] == 'admin'
    d['list_db'] = odoo.tools.config['list_db']
    d['langs'] = odoo.service.db.exp_list_lang()
    d['countries'] = odoo.service.db.exp_list_countries()
    d['pattern'] = DBNAME_PATTERN
        # databases list
        d['databases'] = []
        try:
            d['databases'] = http.db_list()
        except odoo.exceptions.AccessDenied:
            monodb = db_monodb()
            if monodb:
                d['databases'] = [monodb]
        return env.get_template("your_html_template_file_name.html").render(d)

This is an example from v10. You can just copy and paste the method from the Odoo module of the version you are working on.


text:
Q: How to Group By a column - SQL Server I need to group by an UniqueIdentifier column, the table also contains the XML column.
Table schema: StudentMark:
CREATE TABLE [dbo].[StudentMark]
(
    [StudentMarkId] [int] IDENTITY(1,1) NOT NULL,
    [StudentId] [uniqueidentifier] NULL,
    [SubjectId] [uniqueidentifier] NULL,
    [ScoreInfo] [xml] NULL,
    [GeneratedOn] [datetime2](2) NOT NULL,

    CONSTRAINT [PK_StudentMark]
       PRIMARY KEY CLUSTERED ([StudentMarkId] ASC)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Sample seed data
INSERT INTO [dbo].[StudentMark] ([StudentId], [SubjectId], [ScoreInfo], GeneratedOn])
VALUES ('FC3CB475-B480-4129-9190-6DE880E2D581', '0D72F79E-FB48-4D3E-9906-B78A9D105081', '<StudentMarkAttribute xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></StudentMarkAttribute>', '2017-08-10 10:20:15'),
       ('0F4EF48C-93E3-41AA-8295-F6B0E8D8C3A2', '0D72F79E-FB48-4D3E-9906-B78A9D105081', '<StudentMarkAttribute xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></StudentMarkAttribute>', '2017-08-10 10:20:15'),
       ('0F4EF48C-93E3-41AA-8295-F6B0E8D8C3A2', 'AB172272-D2E9-49E1-8040-6117BB6743DB', '<StudentMarkAttribute xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></StudentMarkAttribute>', '2017-08-16 09:06:20'),
       ('FC3CB475-B480-4129-9190-6DE880E2D581', 'AB172272-D2E9-49E1-8040-6117BB6743DB', '<StudentMarkAttribute xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></StudentMarkAttribute>', '2017-08-16 09:06:20');

Requirement: I need to group by [dbo].[StudentMark].[StudentId] and take the latest record.
I tried the following SQL query but it is causing an error
SELECT
    MAX([StudentMarkId]), [StudentId], [SubjectId], [ScoreInfo], [GeneratedOn]
FROM
    [dbo].[StudentMark]
GROUP BY
    [StudentId]

Error:

Column 'dbo.StudentMark.SubjectId' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I refereed the following question but I can't fix it: Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause
Kindly assist me.

A: Use ROW_NUMBER to calculate position within group:
SELECT *
FROM (
    SELECT *,
      ROW_NUMBER() OVER(PARTITION BY StudentId ORDER BY StudentMarkId DESC) AS rn
    FROM [dbo].[StudentMark]) sub
WHERE sub.rn = 1;

A: An alternative solution works best if you have a Students table:
select sm.*
from students s cross apply
     (select top 1 sm.*
      from studentmark sm
      where sm.studentid = s.studentid
      order by sm.generatedon desc
     ) sm;

A: You cannot group by XML or TEXT columns, you would first need to convert to varchar(max):
SELECT
    MAX([StudentMarkId]), [StudentId], [SubjectId],
    CONVERT(XML, CONVERT(VARCHAR(MAX), [ScoreInfo])) DetailXML,
    [GeneratedOn]
FROM
    [dbo].[StudentMark]
GROUP BY
    [StudentId], [SubjectId],
    CONVERT(VARCHAR(MAX), [ScoreInfo]), [GeneratedOn]

On the first line, it is converted to varchar(max) to match the GROUP BY clause, and later it is re-cast back to XML.


text:
Q: Adding user to MySql using iOS I am using the code below to add user to MySql, but record not added. Have a look to my Table on my server:

And her is my PHP file:
<?php
header( 'Content-type: text/xml');
mysql_connect( 'localhost', '********', '********');
mysql_select_db('*********');

    mysql_query("INSERT INTO user VALUES ( null, '".
    mysql_real_escape_string( $REQUEST['user']).
    "', '".
    mysql_real_escape_string( $_REQUEST['email']).
    "','".
    mysql_real_escape_string( $_REQUEST['contact']).
    "','".
    mysql_real_escape_string( $_REQUEST['description']).
    "','".);
    $data = array();
    $data['result'] = mysql_insert_id();
    header('userid: '.$data['result']);
    return json_encode($data);

?>

<success> />

And her is my Xcode:
 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    //    if ([defaults stringForKey:@"user_preference"]) {
    [defaults setValue:[usernameTextFieldObj text] forKey:@"user_preference"];
    //    }
    NSString *url = [NSString stringWithFormat:
                     @"http://MyWebSite/Folder/chat/adduser.php"];

    NSLog(@"url %@", url);

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
                                    init] ;
    [request setURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];

    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"user=%@&contact=%@&description=%@&email=%@",
                       usernameTextFieldObj.text,
                       contactNumberTextFieldObj.text,descriptionTextViewObj.text,emailidTextFieldObj.text] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:body];

- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
    NSDictionary *responseHeaders = ((NSHTTPURLResponse *)response).allHeaderFields;

    NSLog(@"headers: %@", responseHeaders.description);
    [[NSUserDefaults standardUserDefaults]setValue:[responseHeaders valueForKey:@"userid"] forKey:@"UserId"];
}

- (void)connection:(NSURLConnection *)connection
    didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if (chatParser)
        chatParser = nil;

    chatParser = [[NSXMLParser alloc] initWithData:receivedData];
   // [chatParser setDelegate:self];
    [chatParser parse];

    //    [receivedData release];

}

I am not good enough to sort out this problem. I hope to find the problem with you guys.


text:
Q: (Restify,ReactJS,Node.js) Socket.io client state is disconnected, server logs the connection I want to try to connect to my Node.js socket.io server from a ReactJS client.
The server logs that the user connects / disconnects, however the client seems to timeout (its states say is disconnected).
Here are the relevant snippets:
server
    var server = restify.createServer()
const socketio = require('socket.io')
const io= socketio.listen(server)
io.sockets.on('connection', function(socket){
  console.log('a user connected');
  socket.emit('server event',{'foo':'bar'})

  socket.on('disconnect',function(){
     console.log('user disconnected');
 });
 socket.on('client event',function(data){
    console.log(data)
 })
})

server.listen(8999, function () {
  console.log('%s listening at %s', server.name, server.url)
})

Then I open the app, it logs the 'user connected' event, however the client side seems to be not aware of the connection.
React client side:
   componentDidMount(){

    try {
    this.socket= io.connect('localhost:8999')
    this.socket.on('connected',function(socket){
        console.log('connected')
    })
    this.socket.emit('client event',{value: 'valami tortent'})
    }catch(error){
        console.log(error)
    }
    this.socket.on('server event',function(data){
        console.log(data)
    })
}

I tried debugging the client side, it seems it never receives the packet for connect confirmation.
What seems to be the problem? I tried every connection url types on the client side.
The weird thing is that the server is aware of the connection and disconnection.

A: The problem was, that for restify you have to pass the
socketio:true parameter when creating the restify server.
So you have to create it like that:
var server = restify.createServer({
    socketio:true
})

Source:
https://github.com/restify/node-restify/issues/717

A: You don't seem to have defined io variable in client side. You have to include client side module for socket io. I hope it works fine once you do so.


text:
Q: java.lang.RuntimeException: java.lang.NoSuchMethodException: jdk.proxy2.$Proxy7.proxyClassLookup() public Login(AndroidDriver<AndroidElement> driver)
{
    PageFactory.initElements(new AppiumFieldDecorator(driver), this);
}

@AndroidFindBy(xpath="//android.widget.Button[@text='NONE OF THE ABOVE']")
private MobileElement None;
public MobileElement clickNone(){
return None;


text:
Q: How to automate the ajax testing? I have a city field in a form that suggest city names on input, I want to test this scenario using selenium webdriver.

A: Be specific to what you want to do with it like if you want to validate whether the right suggestions are retrieved or you just want to check if its working.
You may have some good reference from here:
Link1
Link2
Link3


text:
Q: django: How to use ModelForm with dynamic 0-n possibilities? The Quetion
Hello. I'm trying to figure out the best way to use one form to create one parent object and then create 0-n sub objects. I'm assuming ModelForms are what I need to do, but I'm having a hard time understanding how to structure the template and view. Would someone be willing to explain how to create n number of sub objects?
The Research
I've read several other articles and posts relating to this:

*

*django model/modelForm - How to get dynamic choices in choiceField?

*https://stackoverflow.com/questions/5575560/how-do-i-create-a-drop-down-menu-in-django-using-a-modelform-with-dynamic-values

*http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/

*Overriding the save method in Django ModelForm
To name a few.
The Details
I have two models like so:
// models.py
class DataItem(models.Model):
    name = models.CharField(max_length=255)
    date_created = models.DateTimeField(auto_now_add=True)
    date_last_updated = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User, blank=False)

    def __unicode__(self):
        return self.name

class DataItemSet(models.Model):
    item = models.ForeignKey(DataItem, blank=False)
    type_ind = models.IntegerField()

And I've created two ModelForms to correspond:
// forms.py
class CreateDataItemForm(forms.ModelForm):

    class Meta:
        model = DataItem
        exclude = ('owner',)

    def save(self, user, commit=True):
        item = super(CreateDataItemForm,self).save(commit=False)
        item.owner = user
        if commit:
            item.save()
        return item

class CreateDataItemSetForm(forms.ModelForm):

    class Meta:
        model = DataItemSet
        exclude = ('item',)

    def save(self, parent, commit=True):
        set = super(CreateDataItemSetForm,self).save(commit=False)
        set.item = parent
        if commit:
            set.save()
        return set

And in my view, I'm trying to have one form submit the creation of a new DataItem and 1-n DataItemSets which are owned by the DataItem. Here is an example of the output of the form:

And the template:
<form action="." method="post">
    {% csrf_token %}

        {{ create_form.as_table }}

            What to track:

                <select>
                    <option value="1">Number</option>
                    <option value="2">Currency ($)</option>
                    <option value="3">Date</option>
                    <option value="4">Day</option>
                    <option value="5">Time</option>
                </select>

            What to track:

                <select>
                    <option value="1">Number</option>
                    <option value="2">Currency ($)</option>
                    <option value="3">Date</option>
                    <option value="4">Day</option>
                    <option value="5">Time</option>
                </select>

                <button type="button">+</button>

        <button type="submit">Create</button>

</form>

And lastly, the view:
// views.py
@login_required
@csrf_protect
def create_data_item(request):
    create_form = CreateDataItemForm()
    c = {'create_form':create_form}
    c.update(csrf(request))
    if request.method == 'POST':
        data = request.POST.copy()
        form = CreateDataItemForm(data, instance=DataItem())
        item_sets = [CreateDataItemSetForm(request.POST, prefix=str(x), instance=DataItemSet()) for x in range(0,9)]
        if form.is_valid():
            # create new data item
            new_item = form.save(request.user)
            #create new set of stuff to track
            for item_set in item_sets:
                new_item_set = item_set.save(new_item)
            # return to the add entry page
            return redirect('/add')
    else:
        return render_to_response('internal/create_data_item.html',c)

I'm missing how to allow for dynamic extraction of 0-n DataItemSets from the form. I can't figure it out with ModelForm.
Thanks for any help!

A: This is what model formsets - specifically, inline formsets - are for.


text:
Q: Sandboxie or an alternative to macOS I use Sandboxie on Windows, is there such a program for Macbook Pro M1? I can't find anything. I want the program for safe internet browsing.
Thank you.

A: The only true equivalent of Sandboxie on MacOS is using a VM.
The built-in
App Sandbox
can restrict access to sensitive resources on a per-app basis
You may also use Time Machine to return the computer to its state before
you installed or used a new application.
You may use AppCleaner
to clean up after an installed app, but it cannot undo modifications
done by that application.


text:
Q: Kotlin non-local return from lambda passed as interface that extends `kotlin.jvm.functions.Function0` TL;DR
In Kotlin 1.3.61 (or newer), is there any way to make a non-local return from a lambda that is passed as the argument for a function parameter whose type is an interface that extends kotlin.jvm.functions.Function0<Unit>?
Details
In the following Kotlin 1.3.61 code, I get compilation errors on the code lines after the comments that specify the errors.
It looks like I cannot make a non-local return from an enclosing function if the return is in a lambda passed to an inline function that accepts an interface that extends Function0<Unit>.
It works, however, if the receiving function accepts a Function0<Unit> (or a () -> Unit) instead of the sub-interface.
Is there any way to make a non-local return work from an interface that extends Function0<Unit>?
If not, is this either a bug in the Kotlin compiler, or is this a feature that is not yet supported by Kotlin?
If the latter, is there any existing request for enhancement?
If no request exists, is this a feature that could / should be supported by Kotlin?
inline fun a(x: () -> Unit) {
    x()
}

fun b(): Int {
    a {return 1}
    return 2
}

inline fun c(x: Function0<Unit>) {
    x()
}

fun d(): Int {
    c {return 3}
    return 4
}

interface F: Function0<Unit>

inline fun e(x: F) {
    x()
}

fun f(): Int {
    // ERROR
    // 'return' is not allowed here
    // Type mismatch: inferred type is () -> [ERROR : Return not allowed] but F was expected
    e {return 5}
    return 6
}

fun g(): Int {
    // ERRORS
    // Interface F does not have constructors
    // 'return' is not allowed here
    e(F {return 7})
    return 8
}

fun h(): Int {
    // ERROR
    // 'return' is not allowed here
    e({return 9} as F)
    return 0
}

println(b()) // properly prints 1 if code with errors is commented out
println(d()) // properly prints 3 if code with errors is commented out
println(f()) // should print 5
println(g()) // should print 7
println(h()) // should print 9


text:
Q: Define a generic type constraint to be of the same type as the implementation I wonder if it is possible to force constraint on interface or abstract class generic type to be the same as the concrete class that implements it specially for it.
Lets say we want to check a fitness of certain entity to task and make it comparable to others in their proficiency
abstract class Entity
{
    public abstract int Fitness(); //Bigger the number - more fit the entity is

    public int MoreFitThan(Entity other)
    {
        return Fitness().CompareTo(other.Fitness());
    }
}

class Fish : Entity
{
    public int swimSpeed { get; set; }

    public override int Fitness()
    {
        return swimSpeed;
    }
}

class Human : Entity
{
    public int testPoints { get; set; }

    public override int Fitness()
    {
        return testPoints;
    }
}

But now we can compare fish's speed with human's test passing capability, which doesn't make sense.
static void Main()
        {
            Human human = new Human() {testPoints = 10};
            Fish fish = new Fish() { swimSpeed = 20 };
            fish.MoreFitThan(human);
        }

So is there a general way make some kind of class or interface that would force it's children classes to implement only own type to own type comparison?
Like so we could only compare people with people and fish to fish, but without explicitly specifying the type of comparable entity?

A: You can force the type being passed to MoreFitThan to match the inheriting class by using generics in the following way.
abstract class Entity<T> where T : Entity<T>
{
    public abstract int Fitness(); //Bigger the number - more fit the entity is

    public int MoreFitThan(T other)
    {
        return Fitness().CompareTo(other.Fitness());
    }
}

class Fish : Entity<Fish>
{
    public int swimSpeed { get; set; }

    public override int Fitness()
    {
        return swimSpeed;
    }
}

class Human : Entity<Human>
{
    public int testPoints { get; set; }

    public override int Fitness()
    {
        return testPoints;
    }
}

Then the following would be a compilation error
Human human = new Human() {testPoints = 10};
Fish fish = new Fish() { swimSpeed = 20 };
fish.MoreFitThan(human);

because Human is not a Fish.  However this would allow a class that inherits from Fish to be compared to a Fish.
class Trout : Fish
{
    public int size { get; set; }

    public override int Fitness()
    {
        return size;
    }
}

The following works because a Trout is a Fish.
Trout trout = new Trout() {size = 10};
Fish fish = new Fish() { swimSpeed = 20 };
fish.MoreFitThan(trout);

A: My suggestion would be to create classes of comparable types, say: Swimmer, Runner, Learner that implement your interface, then in those classes also implement IComparable and enforce the constraint on that class type. Then you can extend those classes with Human for Learner, Fish for Swimmer, etc...
There are other ways to do it, but this should work fine for your needs.


text:
Q: Angular 5 - Http post method error I have migrated my project from angular 4 to 5. As part of the migration i have changed HttpModule to HttpClientModule.
Now i am getting the following error
: Argument of type '(res: Response) => any' is not assignable to parameter of type '(value: ArrayBuffer, index: number) => any'

The code is as follows
 apiResponse(auth, apiType) {
      return this.http.post(auth.url, auth.data, auth.options)
                    .map((res: Response) => res.json()).subscribe(
        response => {
          console.log(response)
        }
      );
  }

Any idea on how to fix this?

A: With the HttpClientModule you dont have to manually extract the JSON. So a service which was looking like that:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { UserModel } from './user.model';

    @Injectable()
    export class UserService {

      constructor(private http: Http) {}

      list(): Observable<UserModel> {
        return this.http.get('/api/users')
          .map(response => response.json())
      }
    }

Can be rewritten as:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { UserModel } from './user.model';

@Injectable()
export class UserService {

  constructor(private http: HttpClient) {}

  list(): Observable<UserModel> {
    return this.http.get('/api/users');
  }
}

A: Try the following
apiResponse(auth, apiType) {
      return this.http.post(auth.url, auth.data, auth.options).subscribe(response => {
          console.log(response)
        }
      );
  }


text:
Q: NSClassFromString() security concerns I'm trying to create a factory class structure where my abstract base class, PDObject, instantiates an instance the proper subclass based on information passed to it in an NSDictionary. Here's my init method for PDObject:
- (id)initWithDictionary:(NSDictionary *)dictionary inEnvironment:(PDEnvironment *)environment {
    NSString *className = [dictionary objectForKey:@"objectType"];
    if (className) {
        Class objectClass = NSClassFromString(className);
        if ([objectClass isSubclassOfClass:[PDObject class]]) {
            self = [[objectClass alloc] initWithDictionary:dictionary inEnvironment:environment];
        } else {
            NSLog(@"tried to instantiate an object of the wrong object type");
            self = nil;
        }
    } else {
        NSLog(@"tried to instantiate an object without an object type");
    }
    return self;
}

I'm wondering if anyone knows of any security concerns with this pattern. I'm worried that something malicious could be passed in in the dictionary and instantiate something unexpected. I have a check to make sure that it is a proper subclass of PDObject. Is there anything I should be concerned about here, or am I just being paranoid?

A: It is unlikely to be a security hole, but passing potentially random strings to runtime functions isn't really something the runtime is hardened against.   The risk isn't instantiating random classes, but causing the app to potentially crash or execute random code.
In general, I wouldn't go beyond minimal effort.  To that ends, I would suggest using NSScanner to scan the class name to see if it has any characters that are obviously out of bounds.  I would think scanning for alphanumericCharacterSet would be sufficient.

A: Dynamism is good and I don't see anything particularly risky here. If you want to avoid crashes, you can check for the particular object a. not being nil (just in case) and b. responding to any selector you want to send it. Also note that whichever kind of protection you use, who wants to mock with your app will always be able to do so using library interposition (meet the infamous DYLD_INSERT_LIBRARIES environment variable) and the Objective-C runtime.


text:
Q: Why do i get a null connection to twitter with Spring Boot / Spring Social guide example? I followed the instructions on the spring.io site:   http://spring.io/guides/gs/accessing-twitter/
And I'm not getting a connection.  The "findPrimaryConnection()" call is returning null.  I'm not seeing any exceptions thrown.  I did set the appId and appSecret in the .properties file.
Here is the controller code:
@Controller
@RequestMapping("/")
public class HelloController {

    private Twitter twitter;

    private ConnectionRepository connectionRepository;

    @Inject
    public HelloController(Twitter twitter, ConnectionRepository connectionRepository) {
        this.twitter = twitter;
        this.connectionRepository = connectionRepository;
    }

    @RequestMapping(method=RequestMethod.GET)
    public String helloTwitter(Model model) {

        if (connectionRepository.findPrimaryConnection(Twitter.class) == null) {
            System.out.println("******** no connection yet: " + connectionRepository.findPrimaryConnection(Twitter.class));
            return "redirect:/connect/twitter";
        }
        System.out.println("******** connection found");
        model.addAttribute(twitter.userOperations().getUserProfile());
        CursoredList<TwitterProfile> friends = twitter.friendOperations().getFriends();
        model.addAttribute("friends", friends);

        return "hello";
    }

}

Here is the HTML form:
<form action="/connect/twitter" method="POST">

You aren't connected to Twitter yet. Click the button to connect this application with your Twitter account.

<button type="submit">Connect to Twitter</button>

        </form>

A: You need to set the Callback URL in your Twitter's application settings - that should be said in Spring guides.
For instance, I have my app working with this callback url:
http://127.0.0.1:3000/auth/twitter/callback

It is explained right below the input field:

Callback URL: Where should we return after successfully authenticating? OAuth 1.0a applications should explicitly specify their oauth_callback URL on the request token step, regardless of the value given here. To restrict your application from using callbacks, leave this field blank.


text:
Q: Apply a filter to a specific area of a DisplayObject? Is there any way of applying a ColorMatrixFilter to one rectangular area of a DisplayObject, leaving the rest untouched?  The DO is a container, and the user interacts with objects in it, so taking snapshots to change its appearance isn't an option.

A: One potential method of pulling the off would be to have two copies of the object, one above the other. The top object would have the filter applied to it and also have it's scrollRect property set so as to mask it out to the rectaglw you wish. The rear object would then show the rest of the object in it's unaltered form.

A: No can do... see this:
Apply Filter to Everything in AS3
UPDATE:
As the referenced post explains, you could either put everything you need to apply the filter to in a different container than the rest, or (and I think this is more usefull in your case) put a Bitmap on top of all you interface, and draw/applyFilter it when something changes.
The Bitmap won't interrupt mouse events (it's not an InteractiveObject), and you would be able to control how, when and what sub-area of you filtered area to update... specially with ColorMatrixFilter, as it doesn't affect sorrounding pixels. Its a bit of work to setup, but it pays off ;)
Good luck!


text:
Q: Not able to read XML using CFHTTP in Coldfusion 2016 I am trying to read XML feed from this URL using cfhttp tag in coldfusion
and i an using this code for it
<cfhttp url="https://architechsfortheweb.com/blogfeed/" method="GET" resolveurl="Yes" >
    <cfhttpparam type="header" name="Content-Type" value="application/xml ">
    <cfhttpparam type="header" name="mimetype" value="application/xml" />
    <cfhttpparam type="header" name="Accept" value="application/xml ">
</cfhttp>

<cfset feedData = CFHTTP.FileContent>
<cfset xmlData = XMLParse(feedData)>
<cfdump var="#xmlData#">

please help me with this, already wasted so much time on this
please help me and et me know what is my mistake

A: Your existing code works fine as-is. You're getting a 404 issue that I'm not getting. The suggestions of the header would be valid if I wasn't using the same header and didn't get a 404. Can you reach that URL in your browser? Maybe the site has blocked you for some reason?
Using James' suggestion of <cffeed> makes it easier. It converts the XML to a struct that is easier to parse.
<cffeed source="https://architechsfortheweb.com/blogfeed/" name="xFeed" />
<cfdump var="#xFeed#">


text:
Q: Issues with php require and file path I have a website using php, html and css. Since some of the content will be repeated numerous times on the pages, I have created a seperate file which contains the code that's being repeated. I am then refering to this file from all the pages I need by using
require('page.html')

The problem now is that I have pages in folders and subfolders, and if I refer to the pages like above, it wont show the content since it can't find "page.html" anymore. I fixed this by changing it to:
require('../page.html')

However that ain't enough since a lot of the content on "page.html" now uses paths that doesn't work anymore like images. Is there a better way to do this? Or will I have to live with a single folder containing 50 files to avoid dubplicated code?
Thanks in advance.

A: simply use a set_include_path (http://de2.php.net/set_include_path) at the beginning of your script and set the path to the directory where your including file exists.
Example: You use the index.php as the entry point for the application and it is located in /var/www/yoursite/web, your files you want to (e.g. page.html) include exists in /var/www/yoursite/lib, then simply add the following to your index.php:
set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '../lib/');

In your file you want to include the page.html you have to execute:
include('page.html');

That's it :)


text:
Q: SwiftUI text field orphan on macOS I have a text field like this
Text("Hello, one two three four five six seven eight!")
                .frame(width:270)
                .border(.blue)

When it renders it decides to put seven and eight on the second line even though there is space for seven on the first line. Worse it decides to indent the truncated top line so it is centred within the frame.

How do I fix this so it wraps the text properly without taking into account the orphan?
Edit: Forgot to mention that I wanted this on macOS. I have tried to port it to the Mac. It does correctly left align the text but it doesn't wrap to the second line. The height of the box does get calculated accordingly though.

Here is my updated code:
struct NonOrphanedText: View
{
    var text: String

    @State private var height: CGFloat = .zero

    var body: some View
    {
        InternalLabelView(text: text, dynamicHeight: $height)
            .frame(maxHeight: height)
    }

    struct InternalLabelView: NSViewRepresentable
    {
        var text: String
        @Binding var dynamicHeight: CGFloat

        func makeNSView(context: Context) -> NSTextField
        {
            let label = NSTextField()
            label.isEditable = false
            label.isBezeled = false
            label.drawsBackground = false
            label.isSelectable = false
            label.maximumNumberOfLines = 5
            label.usesSingleLineMode = false
            label.lineBreakStrategy = .init()
            label.lineBreakMode = .byWordWrapping
            label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
            return label
        }

        func updateNSView(_ nsView: NSTextField, context: Context)
        {
            nsView.stringValue = text

            DispatchQueue.main.async
            {
                dynamicHeight = nsView.sizeThatFits(CGSize(width: nsView.bounds.width, height: CGFloat.greatestFiniteMagnitude)).height
            }
        }
    }
}

A: We need lineBreakStrategy but it is unavailable for now in SwiftUI, so possible solution is to use UILabel.
Here is a possible solution. Tested with Xcode 13.2 / iOS 15.2

struct LabelView: View {
    var text: String

    @State private var height: CGFloat = .zero

    var body: some View {
        InternalLabelView(text: text, dynamicHeight: $height)
            .frame(maxHeight: height)
    }

    struct InternalLabelView: UIViewRepresentable {
        var text: String
        @Binding var dynamicHeight: CGFloat

        func makeUIView(context: Context) -> UILabel {
            let label = UILabel()
            label.numberOfLines = 0
            label.lineBreakStrategy = .init()          // << here !!
            label.lineBreakMode = .byWordWrapping
            label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)

            return label
        }

        func updateUIView(_ uiView: UILabel, context: Context) {
            uiView.text = text

            DispatchQueue.main.async {
                dynamicHeight = uiView.sizeThatFits(CGSize(width: uiView.bounds.width, height: CGFloat.greatestFiniteMagnitude)).height
            }
        }
    }
}


text:
Q: Customizing divs inside a div through CSS I'm trying to achieve something similar to this:
Image Example
, but i encounter some problems.
This is my code from jsfiddle: https://jsfiddle.net/4cd77zvk/
HTML code:

        Info: X

        Current price: $

        Time until expired: X

        Offer avilable for more: X

        Place: X

    <button class="sendprice" onclick="location.href='#'">Place bid</button>

If you can explain to me please what I'm doing wrong ill be very thankful!

A:     try this:
   #itembox
    {
        margin-top:5px;
        margin-left: 3px;
        position: relative;

        border-style: solid;
        border-width: 2px;
        height:auto;
        width:230px;

        overflow:hidden;
        float:left;
    }
    #itempicture
    {
        background-image: url('');
        background-color:black;
        height:100px;
    width:100%;

    }
    #iteminfo
    {
        font-family:arial;
        font-size:14px;
      bottom: 0;
        height:auto;
        width:100%;

    }
    #itembox .sendprice
    {
        position: relative;
        height:50px;
        width:100%;
        bottom: 0;
        clear:both;
    }

A: Using display: inline-flex brought you on the wrong path.


text:
Q: Chown doesn't work on files in an external drive? I first mounted an WD Elements drive by
sudo mount /dev/sdb1 /media/elements

Then, created a test file under the mounted drive by
touch test

And got
-rwxrwxrwx 1 zhijia zhijia  0 2013-03-09 02:53 test

Then I tried to change its owner by
sudo chown mysql:mysql test

But the owner didn't change at all. What's the reason? How to solve it?
Below is the mount:
/dev/sda1 on / type ext4 (rw,errors=remount-ro)
proc on /proc type proc (rw,noexec,nosuid,nodev)
none on /sys type sysfs (rw,noexec,nosuid,nodev)
none on /sys/fs/fuse/connections type fusectl (rw)
none on /sys/kernel/debug type debugfs (rw)
none on /sys/kernel/security type securityfs (rw)
none on /dev type devtmpfs (rw,mode=0755)
none on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620)
none on /dev/shm type tmpfs (rw,nosuid,nodev)
none on /var/run type tmpfs (rw,nosuid,mode=0755)
none on /var/lock type tmpfs (rw,noexec,nosuid,nodev)
none on /lib/init/rw type tmpfs (rw,nosuid,mode=0755)
none on /var/lib/ureadahead/debugfs type debugfs (rw,relatime)
binfmt_misc on /proc/sys/fs/binfmt_misc type binfmt_misc (rw,noexec,nosuid,nodev)
gvfs-fuse-daemon on /home/zhijia/.gvfs type fuse.gvfs-fuse-daemon (rw,nosuid,nodev,user=zhijia)
/dev/sdb1 on /media/Elements type fuseblk (rw,nosuid,nodev,allow_other,blksize=4096,default_permissions)
/dev/sdb1 on /media/elements type fuseblk (rw,nosuid,nodev,allow_other,blksize=4096)

A: To linux there is no difference on external/internal hard drive, all that matters is the filesystem. Forget about chown and chmod, these only work if the filesystem supports unix style permissions, and as you've found out, Windows filesystems do not.

A: Don't use mount, use ntfs-3g:
sudo ntfs-3g /dev/sdb1 /media/elements
you may need to install ntfs-3g with apt-get or the like (yum).


text:
Q: Finding general forms of sums in Mathematica A general form can be obtained for some sums with binomial coefficients.
Mathematica is able to find these general forms for some of the simplest sums. For others the output contains for instance some ugly DifferenceRoot.  My question is how to help Mathematica find general forms of more complicated sums.
Examples

*

*This equation $\sum_k\binom{2k}{k}\binom{4n-2k}{2n-k}=2^{4n}$ Mathematica is able to handle.

*However, one can rewrite the above equation to: $\sum_{k=-n}^{k=n}\binom{2n+2k}{n+k}\binom{2n-2k}{n-k}=2^{4n}$. This one produces the output with the mentioned DifferenceRoot.

*An obvious trick working for some simpler sums is FullSimplify. The example is $\sum_{k=0}^g \binom{4g+2}{g}=2^{4g}$.

What are more sophisticated tricks and techniques or how to handle the output to make it eatable?


text:
Q: How can I run Qemu with the "-nographic" option in Mac OS X? Does anyone know how to run Qemu with the -nographic option in Mac OS X? The idea is to use the native Terminal for a text based operation instead of running inside Qemu's own window.
The -nographic option starts Qemu with no output at all, there's also a -chardev option that can be used with "serial" and path=/dev/tty*. However I haven't been able to pull any of these options off to get it to work. The serial option specifically want's a unique id, but I have no idea what the id is supposed to be. The syntax is also a bit peculiar with a mix of commas and equal signs behind a group of options. From the man page of -chardev for example: -chardev serial ,id=id ,path=path.
Google has given some hints how it can be done, but those examples have all been Linux specific.


text:
Q: Java - UnixFileSystem - how does list sort children? In Windows code new File("").list() sorts files by name.
In Linux (when java.io.UnixFileSystem is used) - files are sorted in some strange (but not random) way.
Is this behaviour adjustable? Or at least - which alghorithm is used to sort files ?
I cannot sort files in my code because I use some standard library that I cannot (or don't want) to modify - therefore don't offer to do this, please.
There are results for tomcat lib directory:
jsp-api.jar
catalina-ant.jar
tomcat-i18n-fr.jar
catalina.jar
jasper.jar
ecj-4.2.2.jar
catalina-tribes.jar
servlet-api.jar
tomcat-jdbc.jar
tomcat-coyote.jar
tomcat-api.jar
tomcat-util.jar
postgresql-9.2-1003.jdbc3.jar
tomcat-i18n-ja.jar
catalina-ha.jar
tomcat-dbcp.jar
annotations-api.jar
jasper-el.jar
el-api.jar
tomcat-i18n-es.jar

A: I guess that under the hood it's using readdir (or similar). So this answer also applies here, basically it points to this blog-post


text:
Q: java.lang.NoClassDefFoundError: javax/el/ValueExpression i am using tomcat 5.5.12
i have this code in a jsp file :
<jsp:useBean id="abbreviationlist" class="lexicon.contents.types.AbbreviationListType"/>
<jsp:setProperty name="abbreviationlist" property="id"/>

  <c:forEach items="${abbreviationlist.list}" var="abbreviation">

  </c:forEach>

i get this error message -

javax.servlet.ServletException: javax/el/ValueExpression
      org.apache.jasper.servlet.JspServlet.service(JspServlet.java:272)
      javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
root cause
          java.lang.NoClassDefFoundError:
  javax/el/ValueExpression

i tried downloadin jstl 1.1 (standard.jar, jstl.jar)
and putting them inside catalina/commun/lib and inside the WEB-INF/lib directory.
that didnt help either.
any help will be appreciated.

A: In my project we have el-api.jar that contains javax/el/ValueExpression. Do you have that jar in classpath?


text:
Q: Setting up multi-release JAR unit tests I have a project that uses a lot of reflection, also on "new" Java features such as records and sealed classes. I'm writing a class like this:
public class RecordHelper {
    public static boolean isRecord(Class<?> type) {
        return type.isRecord();
    }
}

Of course, this only works in Java 16 and higher, so I'm trying to set up a multi-release JAR file, with a default implementation like this:
public class RecordHelper {
    public static boolean isRecord(Class<?> type) {
        return false;
    }
}

I've been able to set that up with Maven using this post on Baeldung, and it works great. It's nice, because it doesn't rely on separate profiles for various versions, which keeps my pom file clean.
But now I need to write tests.
I want to be able to run the test suite on all platforms that I want to support, which means everything from JDK 8 and up. (I don't mind compiling on a different JDK before I run the tests.) Of course, on JDK 16 and up, I also want to test records-related things (and on 17 and up, sealed classes), so that means that I have to compile some records, which means I will inevitably have some class files that won't work on older JDKs.
In my mind, it would make sense to have something like a multi-release JAR file for tests as well, where the records tests get placed in the appropriate place in META-INF/versions, but of course tests aren't usually packaged in a JAR, so that doesn't work.
Is there a way to get this working in a single-module Maven project without too much repetition?
Of course, it would have to 'accumulate' test classes as the JDK version goes up, e.g. on JDK 8 I only have the 'regular' test classes, on JDK 16 I have the regular ones and the java16 ones, and on JDK 17 I have the regular ones, the java16 ones and the java17 ones. I haven't found a way yet to express this kind of thing in Maven in a concise way, but I'm not a Maven expert.
Or am I looking in the wrong direction, and is it preferable to make a multi-module Maven project, with the main code in one module, and the tests in another, and then generate a multi-module jar for the tests as well? If so, how would I run this jar file on different JDKs?

A: To test a MRJAR the classes must be packaged as a jar, so don't use surefire with target/classes, but instead use failsafe during the verify phase.
And you must run it at least twice, once per targeted Java version.
I would write a unittest, that works for all Java versions, but might skip certain tests.
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;

import org.junit.jupiter.api.Test;

class RecordHelperTest
{

    @Test
    void isNotARecord()
    {
        assertFalse( RecordHelper.isRecord(Object.class));
    }

    @Test
    void isARecord() throws Exception
    {
        assumeTrue( Integer.parseInt( System.getProperty( "java.specification.version" ) ) >= 16 );

        Class c = Class.forName( "jdk.net.UnixDomainPrincipal" );
        assertTrue( RecordHelper.isRecord(c));
    }

}

How to run it twice, that's up to you, e.g. configure the failsafe plugin twice with different a Toolchain, or rely on a CI server, that builds the project with both JDKs.
https://maven.apache.org/plugins/maven-compiler-plugin/multirelease.html describes several options with their pros and cons as there is no one-fits-all solution.

A: TL;DR
A Maven multi-module solution like the one from @jqno and @khmarbaise should be preferred over this solution. The Maven Invoker Plugin should be used only when a multi-module setup is not an option.
Detailed Answer
The Maven Invoker Plugin could be used for this purpose.
Following the standard directory layout suggested by the plugin and assuming versions 8, 11, and 16 as JDK targets, JDK specific tests should be structured in separate directories:

*

*src/it/jdk-8 for tests targeting the JDK 8.

*src/it/jdk-11 for tests targeting the JDK 11.

*src/it/jdk-16 for tests targeting the JDK 16.

Each group should have its own POM where the Java version is specified in the maven-compiler-plugin configuration, for example by using the maven.compiler.release property.
Each test group can run on multiple Java versions without duplicating the test classes. For example, to run JDK 11 tests on both Java 11 and 16 executions:

*

*A test JAR should be created in the JDK 11 related POM using the maven-jar-plugin

*The test JAR should be installed in the local Maven repository used by the invoker (can be done setting invoker.goals = install for the test specific group)

*The test JAR should be declared as a dependency and added to the Maven Surefire Plugin configuration of the JDK 16 related POM, using the dependenciesToScan parameter.

Pros

*

*Single-module projects do not need to switch to a multi-module setup only for test executions.

*All the complexity is locked into src/it.

Cons

*

*Files under src/it are not IDE friendly, e.g., the src/it/jdk-*/pom.xml files are not detected as Maven projects and the src/it/jdk-*/src/test subdirectories are not detected as test sources root.

A full example is available at https://github.com/scordio/invoker-plugin-example.

A: I ended up creating a multi-module build, as @khmarbaise suggests in one of the comments below the question. He also provides an example.
With modules named core, m16, m17, etc. I can place the bulk of the tests in the core module, and the JDK specific tests in the corresponding modules. I can even test the integration of the JDK-specific code with the rest of the core module, because apparently in this setup, Maven picks the implementation of a class in m17 over the implementation of the same class in core, thereby simulating what happens in a real multi-release jar file. I'm not 100% certain if this is programming by coincidence or not, but it works
Another advantage of a multi-module approach, is that if I use new language features in the JDK-specific submodules, my IDE will just understand it. With the approach in the Baeldung article I cited in the question, that doesn't work and I see squiggles everywhere.
In order to test the build on different JDKs, I use profiles that activate on the JDK version, and that select appropriate submodules, like this:
        <profile>
            <id>modules-jdk8</id>
            <activation>
                <jdk>[1.8,11)</jdk>
            </activation>
            <modules>
                <module>core</module>
            </modules>
        </profile>

        <profile>
            <id>modules-jdk16</id>
            <activation>
                <jdk>[16,17)</jdk>
            </activation>
            <modules>
                <module>core</module>
                <module>m16</module>
            </modules>
        </profile>

        <profile>
            <id>modules-jdk17</id>
            <activation>
                <jdk>[17,)</jdk>
            </activation>
            <modules>
                <module>core</module>
                <module>m16</module>
                <module>m17</module>
                <module>release</module>
            </modules>
        </profile>

(Maybe an approach using Toolchains would have been better.)
Note that there must also be a release module, which has dependencies on all other modules, and which uses the Maven Assembly plugin to actually create the jar file, and which places the JDK-specific classes in the appropriate directories in the jar.
I have added a <maven.install>true</maven.install> property to all modules except the release module, so that only the actual multi-release jar file will be installed into my local repostory. This is important, because I also want to publish to Maven Central, and I don't want to litter it with all kinds of half-product jar files.


text:
Q: Pandas dataframe export to excel causes TypeError I am trying to export a dataframe from pandas to excel doing so :
writer = pd.io.excel.ExcelWriter(args.out_file, engine='xlsxwriter', options={'constant_memory': True})
summary_data.to_excel(writer, sheet_name='summary', na_rep='NA', index=False)

But I am getting that message :
"cannot convert the series to {0}".format(str(converter)))
TypeError: cannot convert the series to <type 'float'>

there is nothing wrong with my dataframe so I am a little bit confused about this error messag, it dosent happen when the dataframe contain less than 1000 rows, but as soon as it becomes larger, this error occurs
Any idea ?
Thanks
Update summary_data.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 2176 entries, 0 to 2175
Data columns (total 27 columns):
chrom                                   2176 non-null object
coord                                   2176 non-null int64
ref_base                                2176 non-null object
var_base                                2176 non-null object
normal_ref_counts                       2176 non-null int64
normal_var_counts                       2176 non-null int64
VOA867-A1_S43_merged_ref_counts         2176 non-null object
VOA867-A1_S43_merged_var_counts         2176 non-null object
VOA867-A1_S43_merged_somatic_status     2176 non-null object
VOA867-E02_S73_merged_ref_counts        2176 non-null object
VOA867-E02_S73_merged_var_counts        2176 non-null object
VOA867-E02_S73_merged_somatic_status    2176 non-null object
VOA867-F03_S76_merged_ref_counts        2176 non-null object
VOA867-F03_S76_merged_var_counts        2176 non-null object
VOA867-F03_S76_merged_somatic_status    2176 non-null object
VOA867-F04_S75_merged_ref_counts        2176 non-null object
VOA867-F04_S75_merged_var_counts        2176 non-null object
VOA867-F04_S75_merged_somatic_status    2176 non-null object
VOA867-F09_S74_merged_ref_counts        2176 non-null object
VOA867-F09_S74_merged_var_counts        2176 non-null object
VOA867-F09_S74_merged_somatic_status    2176 non-null object
VOA867-T_S41_merged_ref_counts          2176 non-null object
VOA867-T_S41_merged_var_counts          2176 non-null object
VOA867-T_S41_merged_somatic_status      2176 non-null object
VOA867xeno_S18_merged_ref_counts        2176 non-null object
VOA867xeno_S18_merged_var_counts        2176 non-null object
VOA867xeno_S18_merged_somatic_status    2176 non-null object
dtypes: int64(3), object(24)None

and here is the function that generates it
def get_summary_data(data, normal_sample):
    summary_data = []
    for index, normal_row in data[normal_sample].iterrows():
        out_row = {'chrom': index[0],
                   'coord': index[1],
                   'ref_base': normal_row['ref_base'],
                   'var_base': normal_row['var_base'],
                   'normal_ref_counts': normal_row['ref_counts'],
                   'normal_var_counts': normal_row['var_counts'],
                   }

        normal_variant_status = normal_row['variant_status']

        normal_depth = out_row['normal_ref_counts'] + out_row['normal_var_counts']

        if normal_depth > 0:
            normal_var_freq = out_row['normal_var_counts'] / normal_depth
        else:
            normal_var_freq = 0

        for sample in data:
            if sample == normal_sample:
                 continue

            sample_row = data[sample].ix[[index]]

            out_row['{0}_ref_counts'.format(sample)] = sample_row['ref_counts']

            out_row['{0}_var_counts'.format(sample)] = sample_row['var_counts']

            sample_variant_status = str(sample_row['variant_status'].iget(0))

            sample_somatic_status = call_somatic_status(normal_variant_status,
                                                        sample_variant_status,
                                                        normal_var_freq,
                                                        args.min_normal_germline_var_freq)

            out_row['{0}_somatic_status'.format(sample)] = sample_somatic_status

        summary_data.append(out_row)

    columns = ['chrom', 'coord', 'ref_base', 'var_base', 'normal_ref_counts', 'normal_var_counts']

    for sample in data:
        if sample == normal_sample:
            continue

        columns.append('{0}_ref_counts'.format(sample))

        columns.append('{0}_var_counts'.format(sample))

        columns.append('{0}_somatic_status'.format(sample))

    summary_data = pd.DataFrame(summary_data, columns=columns)

    return summary_data

count is supposed to be int but I can see it is considered as string here, probably because it was extracted from another dataframe ?

A: .to_excel only takes columns that are type: object.  The quick way to fix this is to force all of the columns to object types before writing with:
summary_data = summary_data.astype(object)

Then you can write it without crashing:
summary_data.to_excel(writer, sheet_name='summary', na_rep='NA', index=False)

There is some munging to do here as in some cases I have to copy the columns over as object type. Wierd. The other option is to just drop the columns that are the problem.


text:
Q: System.ExecutionEngineException in wp8 i am getting this exception while debugging my wp8 app on the device. System.ExecutionEngineException . Upon searching the net, i found suggestions to disable concurrent garbage collection and include that in app.config file. How can i do this on windows phone 8. I don't see that in my project. Where should i include this configuration.
<configuration>
<runtime>
     <gcConcurrent enabled="false"/>
</runtime>
</configuration>

Kindly help on this.

A: That configuration should go an the app.config file. If your project doesn't have one, then you can add it.
I seriously doubt, though, that this will fix your problem.


text:
Q: RadGrid with MasterTableView I want to know how do I write the code behind for RadGridTransactions_ItemDataBound
 <telerik:RadGrid ID="RadGridTransactions" runat="server"
    OnItemDataBound="RadGridTransactions_ItemDataBound" CellSpacing="-1" GridLines="Both"  Height="70px" >
<MasterTableView AutoGenerateColumns="false"  AllowFilteringByColumn="false" ShowFooter="false"
        DataKeyNames="TransactionID" Visible ="true">
        <Columns>
            <telerik:GridTemplateColumn HeaderText="">
                <ItemTemplate>
                    <asp:RadioButton ID="RadioButtonTransaction" runat="server" AutoPostBack="true" OnCheckedChanged="RadioButtonTransaction_CheckedChanged" HeaderText="Closing Book Transaction" Visible ="true" />
                </ItemTemplate>
            </telerik:GridTemplateColumn>
            <telerik:GridBoundColumn DataField="TransactionID" UniqueName="TransactionID" meta:resourcekey="TransactionID" Visible ="true" HeaderText="Transaction ID">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="practiceAreaText" UniqueName="practiceAreaText" meta:resourcekey="practiceAreaText" Visible ="true" HeaderText="Practice Area">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="mattertypecategory" UniqueName="mattertypecategory" meta:resourcekey="mattertypecategory" Visible ="true" HeaderText="Matter Type Category">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn DataField="matterTypeText" UniqueName="matterTypeText" meta:resourcekey="matterTypeText" Visible ="true" HeaderText="Matter Type">
            </telerik:GridBoundColumn>
            <telerik:GridDateTimeColumn DataField="ClosingDate" UniqueName="ClosingDate" meta:resourcekey="ClosingDateTransaction" DataFormatString="{0:MM/dd/yyyy}" Visible ="true" HeaderText="Closing Date">
            </telerik:GridDateTimeColumn>
             <telerik:GridTemplateColumn meta:resourcekey="DealSheetStatus" Visible ="true" HeaderText="Deal Sheet Status">
                <ItemTemplate>
                   <asp:Image runat="server" ID="RowImage" ImageUrl="../Images/cancel.png" />
                </ItemTemplate>
            </telerik:GridTemplateColumn>
            <telerik:GridImageColumn Visible="true" DataType="System.String" DataImageUrlFields="DealSheetStatus" meta:resourcekey="DealSheetStatus"
                DataImageUrlFormatString="../Images/{0}"
                ImageAlign="Middle" >
            </telerik:GridImageColumn>
            <telerik:GridBoundColumn DataField="ClosingBooks" UniqueName="ClosingBooks" meta:resourcekey="ClosingBooks" Visible ="true" HeaderText="Closing Book">
            </telerik:GridBoundColumn>

            <telerik:GridHyperLinkColumn
                Target="blank" UniqueName="MatterID" DataNavigateUrlFields="MatterID" DataNavigateUrlFormatString ="http://semtlweb1:8091/matterdetails.aspx?matterid={0}"
                Text="EDIT" meta:resourcekey="LinkDealSheet" HeaderText="Link To Data Sheet">
            </telerik:GridHyperLinkColumn>
        </Columns>
    </MasterTableView>
</telerik:RadGrid>


text:
Q: ¿C++ incapaz de crear un cuadro mágico de 4x4 con rand()? buenas noches.
Estoy dando mis primeros pasos en C++. Nos pidieron crear un programa que sea capaz de crear un cuadro mágico de 3x3 y un cuadro mágico de 4x4. Por suerte, ya había visto a alguien hacer este ejercicio, así que seguí la misma ruta de la persona que lo resolvió: hacerlo usando rand() con comprobaciones lógicas por el camino para asegurar que el cada número no está en la matriz y al  final hacer las sumas respectivas para ver si la matriz representa un cuadro mágico o no.
El problema es que, por alguna razón, C++ pareciera incapaz de generar un cuadro mágico de 4x4 siguiendo el siguiente proceso, que es el mismo que usé para el cuadro de 3x3.
Haciendo pruebas vi que es capaz de crear cuadros que, o sumen en todas sus filas 34, o sumen en todas sus columnas 34, o sumen en sus diagonales 34, pero en cuanto le pido cumplir al menos dos de esas condiciones, ya no puede hacerlo y se queda generando cuadros infinitamente. ¿A alguien se le ocurre cuál es el error de mi semántica o por qué sucede esto?
¿Hay forma de generar el cuadro por este método o debería buscar un método diferente?
Gracias por su atención.
Adjunto el código en cuestión:
//Declaro librerías
#include <iostream>                     //cout <<
#include <cstdlib>                      //srand()/rand()
#include <ctime>                        //time()

//Evito escribir std:: cada vez
using namespace std;

//Prototipo funciones
void format(int cuadro[4][4]);          //Asigna 0 a todos los elementos de la matriz
void crear(int cuadro[4][4]);           //Asigna un número diferente a cada elemento
bool check(int temp, int cuadro[4][4]); //Revisa si el número ya está en la matriz
bool nomagic(int cuadro[4][4]);         //Revisa si la matriz no es un cuadro mágico
void mostrar(int cuadro[4][4]);         //Muestra la matriz

int main(){
    //Semilla aleatoria
    srand(time('\0'));

    //Declaración de varibles
    int cuadro[4][4]={0};

    //Generación del cuadro
    do{
        format(cuadro);
        crear(cuadro);
    }while(nomagic(cuadro));

    //Impresión de datos
    mostrar(cuadro);

    cin.ignore();

    return 0;
}

//Desarollo funciones
void format(int cuadro[4][4]){
    for(int i=0; i<4; i++)              //Se repite para cada elemento de la matriz
        for(int j=0; j<4; j++)
            cuadro[i][j]=0;             //Asigna 0 al elemento
}

void crear(int cuadro[4][4]){
    int temp=0;                         //Crea un número temporal
    for(int i=0; i<4; i++)              //Se repite para cada elemento de la matriz
        for(int j=0; j<4; j++){
            do
                temp=rand()%16+1;       //Asigna un número aleatorio entre 1 y 16
            while(check(temp, cuadro)); //Revisa si el número ya está en la matriz
            cuadro[i][j]=temp;          //Asigna el número al elemento
        }
}

bool check(int temp, int cuadro[4][4]){
    for(int i=0; i<4; i++)
        for(int j=0; j<4; j++)          //Se repite para cada elemento de la matriz
            if(temp==cuadro[i][j])      //Compara el número con el elemento
                return 1;               //Si son el mismo, devuelve 1.
    return 0;                           //Si no encuentra el número, devuelve 0.
}

bool nomagic(int cuadro[4][4]){
    int sum=0;                          //Crea una variable para la sumatoria
    for(int i=0; i<4; i++){             //Se repite para cada fila de la matriz
        sum=0;                          //Reinicia la sumatoria
        for(int j=0; j<4; j++)          //Se repite para cada elemento de la fila
            sum+=cuadro[i][j];          //Suma el valor del elemento a la sumatoria
        if(sum!=34)
            return 1;                   //Si no suman 34, devuelve 1.
    }
    for(int i=0; i<4; i++){             //Se repite para cada columna de la matriz
        sum=0;
        for(int j=0; j<4; j++)          //Se repite para cada elemento de la columna
            sum+=cuadro[j][i];
        if(sum!=34)
            return 1;
    }
    sum=0;
    for(int i=0; i<4; i++)              //Se repite para cada elemento de la diagonal
        sum+=cuadro[i][i];
    if(sum!=34)
        return 1;
    sum=0;
    for(int i=0; i<4; i++)              //Se repite para cada elemento de la diagonal
        sum+=cuadro[i][3-i];            //complemento a 3 para invertir las filas
    if(sum!=34)
        return 1;
    return 0;                           //Si todo suma 34, regresa 0.
}

void mostrar(int cuadro[4][4]){
    for(int i=0; i<4; i++){             //Se repite para fila de la matriz
        cout <<" ";                     //Imprime un cuadro de sangría
        for(int j=0; j<4; j++){         //Se repite para cada elelemento de la fila
            if(cuadro[i][j]<10)         //Se imprime un espacio antes de los elementos mayores a
                cout <<" ";             //10 para mantener la cuadrícula.
            cout <<cuadro[i][j]<<" ";   //Imprime el elemento seguido de un espacio
        }
        cout <<endl;                    //Salta línea al terminar la fila.
    }
}

A: No he repasado tu código, pero asumiendo que no hayas introducido algún bug al redimensionar el cuadrado, lo que veo es que el algoritmo "funciona" pero no ha encontrado un cuadrado mágico, por dos cuestiones no excluyentes:
No has tenido suerte.
Con las cosas aleatorias es lo que pasa. Igual el primer cuadrado generado es mágico y acaba en unos milisegundos, igual el programa está probando millones de cuadrados que son inválidos y no acaba.
Las probabilidades son mucho menores
Con tácticas de fuerza bruta (probar valores hasta que uno funciona) los tiempos de respuesta pueden alargarse muchísimo si el tamaño del problema cambia. Así que conviene documentarse.
Para un cuadrado de 3x3, hay un único cuadrado mágico1, para uno de 4x4, 880.
Pero hay 9! = 362880 posibles formas de organizar los números del 1 al 9 en un cuadrado de 3x3, y 16! = 2.092279e+13, más de 20 billones de formas de organizar los números del 1 al 16 en un cuadrado de 4x4.
Es decir, la probabilidad de que un cuadrado de 3x3 aleatorio sea mágico es proporcional2 a 1/362880. La probabilidad de que un cuadrado de 4x4 aleatorio sea mágico es proporcional a 880/2.092279e+13 que aproximadamente es 1/23775897600. Es decir, es como 65.000 veces más improbable.
Además de que de media necesitarás generar más cuadrados de 4x4 para encontrar uno mágico, para generar un cuadrado 4x4 tienes que hacer muchas más operaciones (generar más números, comprobar que los números generados no estén ya en el cuadrado) así que cada prueba es más lenta.
Por eso tu programa se queda sin responderte, porque todavía no ha encontrado un cuadrado mágico.
La respuesta correcta es usar un algoritmo mejor para generar cuadrados mágicos.

1Hay que multiplicar por posibles rotaciones y reflexiones.
2De nuevo porque hay que contar rotaciones y reflexiones.

A:
¿A alguien se le ocurre cuál es el error de mi semántica o por qué sucede esto?

Tienes una matriz de 4x4 y la rellenas aleatoriamente con números del 1 al 16, para una fila o columna cualquiera esto suponen 16^4=65536 combinaciones diferentes. Éstas combinaciones ofrecerán sumas que van del 4 al 64, siendo el valor medio, 34, que es el que buscas... estadísticamente es el más probable, pero que sea el más probable no implica que sea un valor seguro. Concretamente la probabilidad de obtener 34 es del 3.14%. Y eso para una fila o columna. (hay que tener en cuenta que no puede haber dos números iguales)
Para que todas las columnas sumen 34 la probabilidad es aún más baja, dado que son sucesos independientes la probabilidad aquí es inferior a 0.00009721%
Si ya seguimos añadiendo condiciones, como que la suma de las 4 columnas y las 2 diagonales sumen igualmente 34, la probabilidad resultante resulta ínfima.
Este no es el camino para encontrar una solución ... puede que en algún momento después de años de cálculo consigas dar con una solución, pero desde luego no es un mecanismo práctico.
Puedes intentar construir tu algoritmo generador de números mágicos aplicando las matemáticas.
Podemos empezar por asignarle a cada celda del cuadrado una letra:
a b c d
e f g h
i j k l
m n o p

Con esto obtenemos las siguientes ecuaciones:
a + b + c + d = 34
e + f + g + h = 34
i + j + k + l = 34
m + n + o + p = 34
a + e + i + m = 34
b + f + j + n = 34
c + g + k + o = 34
d + h + l + p = 34
a + f + k + p = 34
d + g + j + m = 34

El sistema tiene 16 incógitas y 10 ecuaciones, luego existen infinitas soluciones al problema. El número de soluciones se reduce si añadimos la restricción de que los valores de las variables deben estar en el rango 1-16
Si ahora juegas con estas ecuaciones podrás relacionar unas variables con otras, de tal forma que la creación del cuadrado sea trivial, por ejemplo:
a+e b+f c+g d+h
c+h d+g a+f b+e
d+f c+e b+h a+g
b+g a+h d+e c+f

Ahora simplemente hay que asignar valores a cada variable (cuidando que la suma total de 34) y ya tendrás tu cuadrado mágico, por ejemplo:
a = 0
b = -1
c = 8
d = 7
e = 2
f = 6
g = 4
h = 8

Lo que nos daría el siguiente cuadrado mágico:
 2  5 12 15
16 11  6  1
13 10  7  4
 3  8  9 14

La solución se podría refinar para tus intereses, yo solamente me limito a mostrarte una posible salida a tu problema


text:
Q: How to plot an unstructured numpy array with a legend? Is it possible, when plotting an n-dimensional unstructured array with matplotlib, to produce a legend label for each dimension?

*

*The solution of a system of ODEs, when using scipy.integrate.odeint, is returned as an array of shape (100, 5) for 5 variables.

*I want to plot the solution from one system as lines, so plt.plot(sol, '-'), reset the color cycle, then plot the same 5 again calculated using another ODE system, using plt.plot(sol_estimate, '--').

*This way, I have the 5 variables in one plot, the exact, as lines, and the approximate, as dashes.

*I can try to play with the opacity later in case the solutions are hard to differentiate

*The primary objective is to get the legend for the 10 lines in an easy way.

*Best would be some loop since we can call them u1, u2, u3, u4, u5, u1_e, u2_e, u3_e, u4_e, u5_e.

*Is this possible in matplotlib?

A: *

*This example only uses a second order ODE, but should get the idea across for how to add a legend.

*

*Using the example from scipy.integrate.odeint

*Convert the unstructured array into a structured array, by adding dtype to the sol array.

from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt

# ode system
def pend(y, t, b, c):
    theta, omega = y
    dydt = [omega, -b*omega - c*np.sin(theta)]
    return dydt

b = np.arange(0.50, 0, -0.25)
c = 5.0
y0 = [np.pi - 0.1, 0.0]
t = np.linspace(0, 10, 101)

ls = ['-', '--']  # list of linestyles
count = 0  # used to index the current linestyle
for i in b:

    sol = odeint(pend, y0, t, args=(i, c))

    type_to_set = 'float64'  # specify the type you need (e.g. 'float64')
    dtype = np.dtype([(f'{x}_ode:{i}', type_to_set) for x in range(sol.shape[1])])  # create names and dtypes list
    sol_updated = sol.astype(type_to_set).view(dtype)  # add names and dtypes to sol

    # plot
    # plt.figure()  # if you want separate plots for each group uncomment this line & put plt.legend in 4 spaces, so it's just after the plotting loop
    for name in sol_updated.dtype.names:
        plt.plot(t, sol_updated[name], linestyle=ls[count], label=name)

    count += 1  # add 1 to the markers indexer
    plt.gca().set_prop_cycle(None)

plt.legend(bbox_to_anchor=(1.04, 0.5), loc='center left', borderaxespad=0)
plt.show()

*

*This is 2 sets of (101, 2) arrays on the same plot with unique line styles for each ode solution group.