text:
Q: How to create 3 thread that will work one by one Is that possible to do without flags? I can use only notify/wait/synchronized.
I want to print: worker1 worker2 worker3 worker1 worker2... But I have a race condition for the wait()/notify() methods.
class ThirdWorker implements Runnable {
        @Override
        public void run(){
            for (int i = 0; i < a; i++) {
                synchronized (mutex3) {
                    System.out.println(Thread.currentThread().getName() + " worker3 " + (i + 1));
                    try {
                        mutex3.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (mutex) {
                        mutex.notify();
                    }
                }
            }
        }
    }

    class SecondWorker implements Runnable{
        @Override
        public void run() {
            synchronized (mutex) {
                new Thread(new ThirdWorker()).start();
            }
                for (int i = 0; i < a; i++) {
                    synchronized (mutex2) {
                        System.out.println(Thread.currentThread().getName() + " worker2 " + (i + 1));
                        synchronized (mutex3){
                            mutex3.notify();
                        }
                        try {
                            mutex2.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

            }
        }
    }

    class FirstWorker implements Runnable{
        @Override
        public void run() {
            synchronized (mutex) {
                new Thread(new SecondWorker()).start();
                for (int i = 0; i < a; i++) {
                    System.out.println(Thread.currentThread().getName() + " worker 1 " + (i+1));
                    try {
                        mutex.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (mutex2){
                        mutex2.notify();
                    }
                }
            }
        }
    }
    new Thread(new FirstWorker()).start();

I know that it would be easy to do it with flags, but I can't.

A: Here there is an example of how you can do it.
Note:
The property turnIsFor is the protected resource.
The threads are created as siblings.
The object used as a monitor (lock) is not used for anything else but that.
There is a while wrapping the lock.wait() with the condition that should enable the thread to run.
Both, lock and notify have to be inside the synchronized block.
Also note that on purpose I started the threads in a random order and still they go one at a time in the expected order given by the shared property nextTurnIsFor.
public class ThreeThreads {

    Thread t1, t2, t3;
    Lock lock = new Lock();
    int turnIsFor = 1;
    public static void main(String ... args) {
        ThreeThreads threeThreads = new ThreeThreads();
        threeThreads.run();
    }

    public ThreeThreads() {

        Runnable printName1 = new Runnable() {

            int turn = 1;

            @Override
            public void run() {
                while(true){
                    try {
                        synchronized(lock) {
                            while(turnIsFor != turn){
                                lock.wait();;
                            }
                            System.out.println( Thread.currentThread().getName());
                            turnIsFor = 2;
                            lock.notifyAll();
                        }
                    }catch(Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Runnable printName2 = new Runnable() {

            int turn = 2;

            @Override
            public void run() {
                while(true) {
                    try {
                        synchronized(lock) {
                            while(turnIsFor != turn){
                                lock.wait();;
                            }
                            System.out.println( Thread.currentThread().getName());
                            turnIsFor = 3;
                            lock.notifyAll();
                        }
                    }catch(Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Runnable printName3 = new Runnable() {

            int turn = 3;

            @Override
            public void run() {
                while(true) {
                    try {
                        synchronized(lock) {
                            while(turnIsFor != turn){
                                lock.wait();;
                            }
                            System.out.println( Thread.currentThread().getName());
                            turnIsFor = 1;
                            lock.notifyAll();
                        }
                    }catch(Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        t1 = new Thread(printName1, "Thread 1");
        t2 = new Thread(printName2, "Thread 2");
        t3 = new Thread(printName3, "Thread 3");

    }

    public void run() {
        t3.start();
        t1.start();
        t2.start();
    }

    private static final class Lock{};

}


text:
Q: How to deploy corda spring boot APIs? I have a corda network running on a VM on Azure with two parties and a notary. I would like to deploy the spring boot APIs, but not sure how to do that and where.
Any link to documentations or help is appreciated.

A: You just need to deploy it anywhere you want - in the same VM of your Corda node or another one. The only thing you need to take care of is the configuration of RPC connection in the node.conf, where you set the RPC settings and users, like this example:
rpcSettings {
    useSsl = false
    standAloneBroker = false
    address = "my-corda-node:10003"
    adminAddress = "my-corda-node:10004"
}
rpcUsers = [
    { username=user1, password=test, permissions=[] }
]

More information here.
If you don't know how to deploy Spring Boot in general, the official documentation of Spring Boot is here.
Remember to also properly set the network configurations in your Azure infrastructure in order to allow RPC traffic between the client and the node.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using neo4django with apache I am trying to use a neo4j database on a django website hosted on a Apache server. I am using neo4django. I have followed the instruction given in http://neo4django.readthedocs.org/en/v0.1.8/index.html. when creating a node, I get the following error:
error at /disk/ [Errno 111] Connection refused Request

My models.py:
import django.db
from neo4django.db import models

class Person(django.db.models.Model):
name = django.db.models.CharField(max_length=50, null=True, blank=True)
username = django.db.models.CharField(max_length=50, null=True, blank=True)
password=django.db.models.CharField(max_length=50, null=True, blank=True)
email=django.db.models.CharField(max_length=50, null=True, blank=True)

    class Meta:
        db_table='lt_profile'

class Pnode(models.NodeModel):
    name=models.StringProperty()
    #more fields

class Anode(models.NodeModel):
    art_type=models.StringProperty(max_length=50)
    mtime=models.StringProperty(max_length=200)

#relation:

My settings.py:
NEO4J_DATABASES = {
    'default' : {
        'HOST':'localhost',
        'PORT': 7474,
        'ENDPOINT':'/var/www/graph_db'
    }
}

DATABASE_ROUTERS = ['neo4django.utils.Neo4djangoIntegrationRouter']

Code where the error happens:
a = Anode.objects.create(art_type='py', mtime=str(file_mtime))
a.save()

I think I need to change something in my port.conf file in Apache ,but I don't know what I should do. I have tried things like:
Listen 7474 in the ports.conf, but no luck. Any help will be appreciated. Thanks

A: @Wes is right in the comments- your endpoint should be set to a relative URL, not a file path.
From the docs, try 'ENDPOINT':'/db/data', which is the default for Neo4j.
EDIT:
Some other bits of advice:
You definitely don't need to add anything in your Apache config. Apache serves up your content from Django, but doesn't control which ports you can access from Django- its config files only cover which ports external users can access. In fact, if Apache is configured to listen on 7474 and it's on the same server as Neo4j, one of them won't be able to use the port.
In your code, you use a = Anode.objects.create(...) followed by a.save(). Anode.objects.create() is a shortcut for
a = Anode(...)
a.save()

so you're actually saving twice. I'd use one or the other to avoid hitting the database more often than necessary.


text:
Q: Django get duration between now and DateTimeField I have a Django model with the following field:
date = models.DateTimeField('start date')

I want to create a duration function that returns the duration between now and the date in the format "hours:minutes"
How can we achieve this?

A: Try this approach:
from django.utils import timezone

class Foo(models.Model):
    date = models.DateTimeField()

    def duration(self):
        _seconds = (timezone.now() - self.date).total_seconds()
        _hours = int(_seconds / 3600)
        _minutes = int((_seconds % 3600) / 60)
        return f"{_hours}:{_minutes}"


text:
Q: When does a package need to use ::: for its own objects Consider this R package with two functions, one exported and the other internal
hello.R
#' @export
hello <- function() {
  internalFunctions:::hello_internal()
}

hello_internal.R
hello_internal <- function(x){
    print("hello world")
}

NAMESPACE
# Generated by roxygen2 (4.1.1): do not edit by hand

export(hello)

When this is checked (devtools::check()) it returns the NOTE
There are ::: calls to the package's namespace in its code. A package
  almost never needs to use ::: for its own objects:
  'hello_internal'

Question
Given the NOTE says almost never, under what circumstances will a package need to use ::: for its own objects?

Extra
I have a very similar related question where I do require the ::: for an internal function, but I don't know why it's required. Hopefully having an answer to this one will solve that one. I have a suspicion that unlocking the environment is doing something I'm not expecting, and thus having to use ::: on an internal function.
If they are considered duplicates of each other I'll delete the other one.

A: You should never need this in ordinary circumstances. You may need it if you are calling the parent function in an unusual way (for example, you've manually changed its environment, or you're calling it from another process where the package isn't attached).

A: Here is a pseudo-code example, where I think using ::: is the only viable solution:
# R-package with an internal function FInternal() that is called in a foreach loop
FInternal <- function(i) {...}

#' Exported function containing a foreach loop
#' @export
ParallelLoop <- function(is, <other-variables>) {
   foreach(i = is) %dopar% {
      # This fails, because it cannot not locate FInternal, unless it is exported.
      FInternal(i)
      # This works but causes a note:
      PackageName:::FInternal(i)
   }
}

I think the problem here is that the body of the foreach loop is not defined as a function of the package. Hence, when executed on a worker process, it is not treated as a code belonging to the package and does not have access to the internal objects of the package. I would be glad if someone could suggest an elegant solution for this specific case.


text:
Q: Spinner listener being called when it should not The Listener is getting called here when I set the selection. The problem here is, I'm setting the selection BEFORE the Listener.
How can I avoid this behavior?
Spinner spCategories = (Spinner) findViewById(R.id.spinnerCategories);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this, R.layout.spinner_item, this.categoryList);
spCategories.setAdapter(aa);
spCategories.setSelection(selectedA);
spCategories.setOnItemSelectedListener(oiclSpCategories);

A: Try to register OnItemSelectedListener with post method:
spCategories.post(new Runnable() {
    public void run() {
        spCategories.setOnItemSelectedListener(oiclSpCategories);
    }
});


text:
Q: Command line works in command prompt but not in VB.NET My command:
c:\temp\abc.exe c:\temp\abc.ini >> c:\temp\log.log

This works fine when executed by the command prompt.
But from VB.NET, it doesn't work (the log file was created but blank, the log file should contain log processes of abc.exe, abc.exe was not executed also).
Dim p as Process = new Process()
Dim pi as ProcessStartInfo = new ProcessStartInfo()
pi.Arguments = "/C c:\temp\abc.exe c:\temp\abc.ini >> c:\temp\log.log "
pi.FileName = "cmd.exe"
p.StartInfo = pi
p.Start()
p.WaitForExit()

Why?
Update: While waiting for an explanation, this is my workaround.
Dim p as Process = new Process()
Dim pi as ProcessStartInfo = new ProcessStartInfo()
pi.Arguments = "c:\temp\abc.ini"
pi.FileName = "c:\temp\abc.exe"
p.StartInfo = pi
p.Start()
Dim output as String = p.StandardOutput.ReadToEnd()
p.WaitForExit()

WriteLog("c:\temp\log.log", output)


text:
Q: Android: how to change selected item color in Preference? On Android 4.x I want to change the default color (here is blue) when an item is pressed in Preference:

How can I do that? Thank you very much guys!

A: You should redefine the color accent for Preferences in your styles.xml for example:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        // your relevant items
        <item name="preferenceTheme">@style/PreferenceTheme</item>
    </style>

   <style name="PreferenceTheme" parent="@style/PreferenceThemeOverlay.v14.Material">
        <item name="colorAccent">@color/colorAccent</item> // here for the ripple color
        <item name="android:textColorPrimary">@color/textColorPrimary</item>
        <item name="android:textColorSecondary">@color/textColorSecondary</item>

    </style>
</resources>

parent="@style/PreferenceThemeOverlay.v14.Material" it is to get a material style like , you can use this parent by addind in your build.gradle :
compile 'com.android.support:preference-v14:25.3.1'
Sorry for my english.
Hope this help .


text:
Q: How do I set this messy placeholder in iPhone? I make this form but when i check in my mobile i.e oppo it's look like this: Image
When I check this in iPhone it looks messy: Image

A: You can try following CSS to fix this issue:
line-height: 1;


text:
Q: How do I add an xml file that I created in the setcontentview() function I have created an xml file in my android project called calc.xml
but im not able to give my xml file in the setcontentview() function
what must be done?

A: Normally this is the way:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.calc);
}

Post some code please, if your problem is still there.


text:
Q: Remove the line break after a  My form is formatted by a 2 column table.
In the left column I use a  and in the right column a <input type="text">.
Some of the input boxes are required.
So the requirement is that for all the compulsary inputs, there should be a red asterisk next to the label.
However a label is designed so that it is always followed by a line break, so the asterisk automatically goes underneath.
What is the best way of making sure this does not happen, and the asterisk goes in the correct place next to the label?
I do not think the
 option would work in a table.
This is the code as requested;

                Company*
                <input style="width: 300px;" id="Subcontractor_CompanyName" name="Subcontractor.CompanyName" value="096 club" type="text" data-val-required="Must enter the Company Name" data-val="true">
                    *

My attempt at using a  failed.

A: If you have the ability to change the markup, you can place the asterisk within the label.
Something like:
Name:*
<input type="text" name="name" />

And CSS:
label sup { color: red; }

Here is the result: http://jsfiddle.net/ByGVE/

A: A label will not, given default browser default CSS and enough width to hold the input next to it, trigger a new line.
You probably have some CSS that sets display: block on the label. Set that on the input instead.

A: Or, if they have given the  as block, you can do this way:
label {display: inline;}

A: Use style="white-space: pre-wrap;"


text:
Q: Invalid JSON primitive on fiddler 4 I am getting "System.ArgumentException: Invalid JSON primitive:" while i am testing my asp.net web api using fiddler4.
Header is as follows
Content-Type: multipart/form-data; boundary=-------------------------acebdf13572468
User-Agent: Fiddler
Host: tr****ro.in
Content-Length: 8976

Body is as follows
---------------------------acebdf13572468
Content-Disposition: form-data; name="json"
Content-Type: application/json
{
"WR_id":"0",
"Com_Id": "5",
"Usr_Id":"22",
"WRC_id":"1",
"App_id":"1",
"Ser_LogNo":"2",
"WR_Comments":"Test",
"WR_date":"2015-12-23 01:30:50.000",
"WR_Location":"test",
"WR_lati":"10.45465",
"WR_longi":"70.23654",
"Status_id":"11"
}
---------------------------acebdf13572468
Content-Disposition: form-data; name="fieldNameHere"; filename="download (1).png"
Content-Type: image/png

<@INCLUDE *C:\Users\MANU\Desktop\cv\download (1).png*@>
---------------------------acebdf13572468
Content-Disposition: form-data; name="fieldNameHere"; filename="download.png"
Content-Type: image/png

<@INCLUDE *C:\Users\MANU\Desktop\cv\download.png*@>
---------------------------acebdf13572468--

Controller as follows
[HttpPost]
public async Task<HttpResponseMessage> PostFormData()
{
    Work_Report_image image = new Work_Report_image();
    Tempsave save = new Tempsave();
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    string root = HttpContext.Current.Server.MapPath("~/App_Data/");
    var provider = new MultipartFormDataStreamProvider(root);

    await Request.Content.ReadAsMultipartAsync(provider);
    try
    {
        if (provider.FormData.AllKeys.AsParallel().Contains("json"))
        {
            //foreach (var val in provider.FormData.GetValues(key))
            //{
            using (var scope = new System.Transactions.TransactionScope())
            {
                string json= provider.FormData.GetValues("json").SingleOrDefault();

                Work_Report Work_Report = js.Deserialize<Work_Report>(json);

and the error I am getting is as follows:
System.ArgumentException: Invalid JSON primitive: "0", "Com_Id": "5", "Usr_Id":"22", "WRC_id":"1", "App_id":"1", "Ser_LogNo":"2", "WR_Comments":"Test", "WR_date":"2015-12-23 01:30:50.000", "WR_Location":"test", "WR_lati":"10.45465", "WR_longi":"70.23654", "Status_id":"11" }. at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer) at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input) at WebApplication.Areas.Json.Controllers.Work_ReportController.d__4.MoveNext()


text:
Q: Recognize links in h:outputText I need to show some text using <h:outputText> tag component. There is this requirement that if the text contains an URLs i.e. http//example.com.co, I need show it as a link.
For example, if user enters Yo quiero www.google.com I need to show Yo quiero www.google.com

A: You need a function which does a regular expression replace on your string. You can use string.replaceAll() for this.
You have multiple options to place this function.

*

*You can create a method in your backing bean.

*You can create a custom jsf tag (example)

*You can create a custom el function (example)

No 1 is the easiest to implement imho.


text:
Q: Pointer Validator I am debugging a large project in C++. There are a few dereferenced pointers causing random crashes. Could you suggest me please best free tool for pointer validation? (Identification of use of invalid pointers)
(Otherwise it will took me ages to go through it manually)
Also I have used Memory Valuator program to get rid of the most memory leaks but it isn't very helpful with pointers being used after being invalidated.
Platform is Windows.
UPDATE:
Before I post I have researched also other posts. And yes, it wasn't helpful. So I would like to share my research.
One of the conditions was a FREE tool and I haven't found any usable, and yes I have tested a dozen of them. Most of the suggested tools are designed for Leaked memory (which is not what I am looking for.) Most of pro tools like IBM's purify do have a free or trial version but all of them are a waste of time (They only reports number of problem but nothing specific).
Other tools like Microsoft Application Verifier are pretty useful for memory or compatibility issues but it wasn't able to identifying my problems.
Now I am testing commercial tools:
Memory Validator – perfect for mem leaks but feature "Detect deleted 'this' pointer" causes my application crash. (and I have spent ages with settings / config.  )
Bug Validator – Much better. It identified some of the problems.  However, it isn't helpful very often. The whole Stack Trace is in crt/src/XString or Mutex initialization or inside some Critical Sections inside C++ libs.
(That's it so far. I hope this info would be helpful.)

A: For Unix, I recommend valgrind.

A: Read Is there a good Valgrind substitute for Windows? , since there's a good chance you're using Windows.

A: Assuming VS2010, Run it under the debugger with the following setting:
Debug->Exceptions->Win32 Exceptions->"c0000005 Access Violation" (set the checkbox)

This would help you to get a first chance exception for pointer dereference issues such as the one in the code below
int main(){
    int buf[2];
    int *p = buf;

    p += 100;
    *p = 2;
}

It really helps as a first level technique! More advanced techniques would require WinDBG.


text:
Q: MSBuild fails on "Invalid command line switch for "LC.exe" Why? I am creating our companies continuous integration server using cc.net, and my original attempted included visual studio being installed on the build server. My manager really wants the build server to not need VS installed, and to just use MSBuild, included in the .net installation.
My current problem though is that I am receiving the following error message:

error MSB6001: Invalid command line switch for "LC.exe". Illegal
  characters in path. [C:\path\to\project.csproj]

With visual studio 2010 installed in my previous attempt, my build works successfully, but now that I do not have visual studio installed in the new build machine, I am receiving this message.
What can I do to get this to work? Thanks in advance for your help!
update 8/13/2012 below is my cc.net msbuild task:
  <msbuild>
    <executable>C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe</executable>
    <workingDirectory>D:\Build</workingDirectory>
    <projectFile>Trunk\BuildSolution.sln</projectFile>
    <buildArgs>/p:Configuration=Debug /t:CLEAN,BUILD</buildArgs>
    <logger>C:\Program Files (x86)\CruiseControl.NET\server\ThoughtWorks.CruiseControl.MSBuild.dll</logger>
    <timeout>600</timeout>
  </msbuild>

A: lc.exe (licence compiler) comes with the .net framework sdk as well as studio.
http://www.microsoft.com/en-us/download/details.aspx?id=19988
Try downloading the right sdk and make sure your path is updated to point to the install directory.
http://msdn.microsoft.com/en-us/library/d9kh6s92(v=vs.80).aspx


text:
Q: Buffer.BlockCopy in WinRT Is there a Buffer.BlockCopy equivalent function or strategy in WinRT? We cannot use Array.Copy because we need to avoid boundaries checking.
We need to port a legacy .Net code that actually copies a byte array to a template array working like a BitConverter. The original code is:
public T GetValue(int index)
{
    T[] vals = new T[1];
    Buffer.BlockCopy(Buffer.ToBytes(), index * UnitSize, vals, 0, UnitSize);
    return vals[0];
}

Kind regards

A: System.Buffer.BlockCopy works just fine in my WinRT app


text:
Q: How to determine if an existing class can be unit-tested? Recently, i took ownership of some c++ code. I am going to maintain this code, and add new features later on.
I know many people say that it is usually not worth adding unit-tests to existing code, but i would still like to add some tests which will at least partially cover the code. In particular, i would like to add tests which reproduce bugs which i fixed.
Some of the classes are constructed with some pretty complex state, which can make it more difficult to unit-test.
I am also willing to refactor the code to make it easier to test.
Is there any good article you recommend on guidelines which help to identify classes which are easier to unit-test? Do you have any advice of your own?

A: While Martin Fowler's book on refactoring is a treasure trove of information, why not take a look at "Working Effectively with Legacy Code."
Also, if you're going to be dealing with classes where there's a ton of global variables or huge amounts of state transitions I'd put in a lot of integration checks.  Separate out as much of the code which interacts with the code you're refactoring to make sure that all expected inputs in the order they are recieved continue to produce the same outputs.  This is critical as it's very easy to "fix" a subtle bug that might have been addressed somewhere else.
Take notes too.  If you do find that there is a bug which another function/class expects and handles properly you'll want to change both at the same time.  That's difficult unless you keep thorough records.

A: Presumably the code was written for a purpose, and a unit test will check if the purpose is met, i.e. the pre-conditions and post-conditions hold for the methods.
If the public class methods are such that you can externally check the state it can be unit tested easily enough (black-box test). If the class state is invisible or if you have to test tricky private methods, your test class may need to be a friend (white-box test).
A class that is hard to unit test will be one that

*

*Has enormous dependencies, i.e. tightly coupled

*Is intended to work in a high-volume or multi-threaded environment. There you would use a system test rather than a unit test and the actual output may not be totally determinate.

A: I written a fair number of blog posts about unit testing, non-trivial, C++ code: http://www.lenholgate.com/blog/2004/05/practical-testing.html
I've also written quite a lot about adding tests to existing code: http://www.lenholgate.com/blog/testing/

A: Almost everything can and should be unit tested. If not directly, then by using mock classes.
Since you decided to refactor your classes, try to use BDD or TDD approach.
To prevent breaking existing functionality, the only way is to have good integration tests, but usually it takes time to execute them all for a complex system.
Without more details on what you do, it is not that easy to give more implementation details. Some are :

*

*use MVP or presenter first for developing gui

*use design patterns where appropriate

*use function and member pointers, or observer design pattern to break dependencies

A: I think that if you're having to come up with some "measure" to test if a class is testable, you're already fscked.  You should be able to tell just by looking at it: can you write an independent program that links to this class alone and makes sure it works?
If a class is too huge so that you can't be sure just by looking at it...chances are it probably isn't testable.  People that don't know how to make small, distinct interfaces generally don't know how to adhere to any other principle either.
In the end though, the way to find out if a class is testable is to try to put it in a harness.  If you end up having to pull in half your program to do it, try refactoring.  If you find that you can't even perform the most basic refactor without having to rewrite the entire program, analyze the expense of doing so.

A: We at IPL published a paper It's testing Jim, but not as we know it which explores the practical problems of testing C++ and suggests some techniques to address them that may well be of use given your question. These techniques are also well supported in Cantata++ - our C/C++ unit and integration testing tool.


text:
Q: Algorithm to determine minimum and maximum spread from total amount So this might sound stupid and i'm really bad at math but i've been trying to solve the following problem:
We have 100 gold
We have 10 orders
We want to spread the gold throughout these 10 orders, the first order having the least amount of gold, and the last one would have the most amount of gold.
i feel the solution is simple but i've been stuck for 3 days dealing with this and not sure how to proceed, thanks


text:
Q: Term::ReadKey in .bashrc command script I'm writing a simple motd-script in perl, that parses messages from specific websites and displays them in the center of the terminal screen.
To get the width of the terminal I use the CPAN module Term::ReadKey.
Now I am calling this script with
command /path/to/script

from my .bashrc to display it on login and opening a terminal.
My script works fine when called while I'm logged in via perl or using
source .bashrc

but on the initial opening of a terminal (which is the actual purpose of the script) I'm getting this Error message:
Can't locate Term/ReadKey.pm in @INC (you may need to install the Term::ReadKey module) (@INC contains: /usr/lib/perl5/site_perl /usr/share/perl5/site_perl /usr/lib/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib/perl5/core_perl /usr/share/perl5/core_perl .) at /path/to/perl-motd.pl line 6.
BEGIN failed--compilation aborted at /path/to/perl-motd.pl line 6.

Line 6 of the script is
use Term::ReadKey;

A: First find where that module is installed: locate Term/ReadKey.pm
If it's not found, you have to install it (may require sudo): cpan Term::ReadKey
If it is already installed, you have to tell Perl where it is:
use lib '/path/to';   # assuming it's installed as "/path/to/Term/ReadKey.pm"
use Term::ReadKey;


text:
Q: How can I add jQuery fadeIn to my listview on page change? I want to make my imageset class in my webform page to fadeIn on changing page of my listview. How can I do this? My code below doesn't seem to work... jQuery script isn't even working. Any ideas?
Head section of my MasterPage...

    <title>Cukiernia ŁOBZA</title>
    <link rel="stylesheet" href="styles/user.css" type="text/css" />

    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css"/>

    <link href="styles/lightbox.css" rel="stylesheet" />

ASP Code of my webform page...
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>

            <asp:DataPager ID="DataPager1" runat="server" PagedControlID="Listview1" PageSize="3">
                <Fields>
                    <asp:NextPreviousPagerField ButtonType="Image" FirstPageText="" LastPageText="" NextPageText="" PreviousPageImageUrl="~/images/arrowbtnup.png" PreviousPageText="" ShowNextPageButton="False" />
                </Fields>
            </asp:DataPager>

        <asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1" DataKeyNames="ID">
            <AlternatingItemTemplate>
                <asp:ImageButton ID="ImageButton2" runat="server" ImageUrl='<%# Eval("image1", "{0}") %>' PostBackUrl='<%# Eval("ID", "~/oferta.aspx?cat=" + Request.QueryString["cat"] + "&sub=" + Request.QueryString["sub"] + "&id={0}") %>' Width="180px" Height="120px" CssClass="imagebtn" CommandName="Choose" />
            </AlternatingItemTemplate>
            <ItemTemplate>
                <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl='<%# Eval("image1", "{0}") %>' PostBackUrl='<%# Eval("ID", "~/oferta.aspx?cat=" + Request.QueryString["cat"] + "&sub=" + Request.QueryString["sub"] + "&id={0}") %>' Width="180px" Height="120px" CssClass="imagebtn" CommandName="Choose" />
            </ItemTemplate>
        </asp:ListView>

        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [C_Produkty] WHERE (([kategoria] = @kategoria) AND ([subkategoria] = @subkategoria)) ORDER BY [ID]">
            <SelectParameters>
                <asp:QueryStringParameter Name="kategoria" QueryStringField="cat" Type="Int32" />
                <asp:QueryStringParameter Name="subkategoria" QueryStringField="sub" Type="Int32" />
            </SelectParameters>
            </asp:SqlDataSource>

            <asp:DataPager ID="DataPager2" runat="server" PagedControlID="Listview1" PageSize="3">
                <Fields>
                    <asp:NextPreviousPagerField ButtonType="Image" FirstPageText="" LastPageText="" NextPageImageUrl="~/images/arrowbtndown.png" NextPageText="" PreviousPageText="" ShowPreviousPageButton="False" />
                </Fields>
            </asp:DataPager>

        </ContentTemplate>
        </asp:UpdatePanel>

            <asp:Label ID="Label1" runat="server" Text=""></asp:Label>

            <asp:HyperLink ID="HyperLink1" runat="server" ImageHeight="320px" ImageWidth="480px" CssClass="image1" Visible="false" data-lightbox="image"></asp:HyperLink>
            <asp:HyperLink ID="HyperLink2" runat="server" ImageHeight="80px" ImageWidth="120px" CssClass="image2" Visible="false" data-lightbox="image"></asp:HyperLink>
            <asp:HyperLink ID="HyperLink3" runat="server" ImageHeight="80px" ImageWidth="120px" CssClass="image3" Visible="false" NavigateUrl="~/index.aspx" ImageUrl="~/images/tortbtn.png"></asp:HyperLink>

</asp:Content>

A: It's probably because your imageset is already displayed, try:
$('.imageset').css({'opacity': 0}).animate({'opacity': 1}, 2000);

Explanation
I'm using $.css() to make the
 transparent. jQuery allows us to chain methods so I'm then using $.animate() to reshow the div.
Snippet
This snippet illustrates the difference between the two approaches:

$("#test1").fadeIn(2000)
$("#test2").css({'opacity': 0}).animate({'opacity': 1}, 2000);
div {
  float: left;
  background: #f00;
  width: 200px;
  height: 200px;
  margin: 20px;
}

$("#test1").fadeIn(2000)

$("#test2").css({'opacity': 0}).animate({'opacity': 1}, 2000);

A: The code doesn't work because, $(document).ready does not fire after each partial postback. You need to use pageLoad for it.
function pageLoad() {
    $('.imageset').hide().fadeIn(2000);
}

Documentation: http://www.asp.net/ajax/documentation/live/overview/AJAXClientEvents.aspx


text:
Q: how to add transfer syntax uid to the filemeta of dataset I use pydicom library to generate .dcm files using the datasets coming from the CT and MRI machines, however in that dataset, the tag (0002,0010) is missing. As I dont have that tag, I am not able to detect the transfer syntax whether it is implicit VR little endian, explicit VR little endian,  jpeg lossless etc. I need the transfer syntax for saving the dataset with flags like below
    ds.is_little_endian = True
    ds.is_implicit_VR = False
    ds.file_meta.TransferSyntaxUID = JPEGLossless
    ds.is_explicit_VR = True  etc

If I dont use the above flags, then the dcm file that is generated will not be valid as there is no transfer syntax.
Since I dont know the transfer syntax, I am sending the transfer syntax in command line arguments when I run the program, and setting the above flags accordingly, and saving the dataset. I know this is wrong method but I just used it as a temporary solution. Is there any better way to detect the transfer syntax please as  the tag (0002, 0010) is missing.
 Below is my code that I use for saving the dcm file using the dataset coming from the CT machine. For now i am sending the transfer syntax as command line argument
from pynetdicom3 import AE, VerificationPresentationContexts,      StoragePresentationContexts, QueryRetrievePresentationContexts
from pydicom.uid import ImplicitVRLittleEndian, ExplicitVRLittleEndian, JPEGLossless
from pynetdicom3.sop_class import CTImageStorage, MRImageStorage
from pynetdicom3 import pynetdicom_uid_prefix
from pydicom.dataset import Dataset, FileDataset

import argparse

import uuid
import os
import django
import logging

ttt = []
ttt.extend(VerificationPresentationContexts)
ttt.extend(StoragePresentationContexts)
ttt.extend(QueryRetrievePresentationContexts)

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lh_dcm_viewer.settings')
django.setup()

from dcm_app.models import DCMFile, DCMFileException

def _setup_argparser():

parser = argparse.ArgumentParser(
    description="The getscp application implements a Service Class "
                "Provider (SCP) for the Query/Retrieve (QR) Service Class "
                "and the Basic Worklist Management (BWM) Service Class. "
                "getscp only supports query functionality using the C-GET "
                "message. It receives query keys from an SCU and sends a "
                "response. The application can be used to test SCUs of the "
                "QR and BWM Service Classes.",
    usage="getscp [options] port")

# Parameters

# Transfer Syntaxes
ts_opts = parser.add_argument_group('Preferred Transfer Syntaxes')
ts_opts.add_argument("--type",
                     help="prefer explicit VR local byte order (default)")
ts_opts.add_argument("--detect_transfer_syntax",
                     help="Detect transfer syntax")
ts_opts.add_argument("--port",
                     help="port at which the SCP listens")

return parser.parse_args()

args = _setup_argparser()

ae = AE(ae_title=b'MY_ECHO_SCP', port=int(args.port))

   if args.type == "jpeg_lossless":
ae.add_supported_context('1.2.840.10008.1.2.4.57')
   elif args.type == "implicit":
ae.add_supported_context('1.2.840.10008.1.2')
print("ImplicitVRLittleEndian")
   elif args.type == "explicit":
ae.add_supported_context('1.2.840.10008.1.2.1')

ae.requested_contexts = ttt
ae.supported_contexts = ttt
DICOM_IP = '192.168.1.11'
DICOM_IP = '127.0.0.1'
DICOM_PORT = 5678

def save_file(dataset, context, info):

try:

    random_str = uuid.uuid4().hex
    meta = Dataset()
    meta.MediaStorageSOPClassUID = dataset.SOPClassUID
    meta.MediaStorageSOPInstanceUID = dataset.SOPInstanceUID
    meta.ImplementationClassUID = pynetdicom_uid_prefix
    meta.FileMetaInformationGroupLength = 202

    received_file_path = "../received_dcms/%s.dcm" % random_str

    dataset_vr = None
    try:
        dataset_vr = dataset[("6000", "3000")].VR
    except KeyError:
        pass

    print(dataset_vr)

    if args.type == "implicit" or dataset_vr == "OB or OW":

        ds = FileDataset(received_file_path, {}, file_meta=meta, preamble=b"\0" * 128)
        ds.update(dataset)
        ds.is_little_endian = True
        ds.is_implicit_VR = True

        if(dataset_vr == "OB or OW"):
            print("forced ImplicitVRLittleEndian")

        ds.file_meta.TransferSyntaxUID = ImplicitVRLittleEndian
    elif args.type == "jpeg_lossless":
        ds = FileDataset(received_file_path, {}, file_meta=meta, preamble=b"\0" * 128)
        ds.update(dataset)
        ds.is_little_endian = True
        ds.is_implicit_VR = False
        ds.file_meta.TransferSyntaxUID = JPEGLossless
        ds.is_explicit_VR = True
    elif args.type == "explicit":
        meta.TransferSyntaxUID = "1.2.840.10008.1.2.1"

        ds = FileDataset(received_file_path, {}, file_meta=meta, preamble=b"\0" * 128)
        ds.update(dataset)
        ds.is_little_endian = True

        ds.is_implicit_VR = False
        ds.file_meta.TransferSyntaxUID = ExplicitVRLittleEndian
        ds.is_explicit_VR = True

    ds.save_as(received_file_path)

    f = open(received_file_path, "rb")

    f.close()

    return 0XC200
    return status
except Exception as e:

    logger.error(e)

ae.on_c_store = save_file
ae.start()

A: I hate to send you away but this is a very specialized tool and it has it's own support community. I looked up your issue and found it might be a bug. There is a user who is having a similar problem and he said the transfer syntax is not missing if he uses an older version of the library.
SIMILAR ISSUE:
https://groups.google.com/forum/#!topic/pydicom/Oxd7cbCwseU
Support for this library is found here:
https://groups.google.com/forum/#!forum/pydicom
The code itself is maintained on GitHub where you can open bug reports and view all other bug reports:  https://github.com/pydicom/pydicom/issues


text:
Q: Discord.py message pinning? I've tried multiple different ways to pin (I also want to try unpinning it) a certain message (it has already been sent) using a bot / selfbot with discord.py, here a few examples:
@pinner.event
async def on_message():
    if message.content == 'message im trying to pin':
    message.pin

@tasks.loop(seconds=1)
async def pin_message():
    message = ('message id ')
    await message.pin(message id)

I'm using Python 3.8 and the latest version of discord.py API.

A: In order to pin a message you must first have the message, once you have it you can await message.pin()
To unpin you can use await message.unpin()
The bot must also have manage_messages permisson in order to pin or unpin messages.
This would pin the message that the user triggered the command with
@bot.command()
async def pin_message(ctx):
  await ctx.message.pin()

If you want to pin a specific message you must fetch it with either ctx.fetch_message(message_id) or if you have the text channel textchannel.fetch_message(message_id)
This will pin a message that the user wants:
@bot.command()
async def pin_this(ctx, message_id: int):
  message = await ctx.fetch_message(message_id)
  await message.pin()

Optional: You can also specify a reason with await message.pin(reason="your reason here")
Documentation:

*

*discord.Message.pin

*discord.Message.unpin

*discord.Message.unpin

*discord.TextChannel.fetch_message

A: For pinning messages, you use:
await message.pin(reason=None)

For unpinning:
await message.unpin(reason=None)

From your example:
@client.event
async def on_message(message):
    if message.content == 'message im trying to pin':
        await message.pin()

Go to the API: https://docs.pycord.dev/en/master/api.html?highlight=pin#discord.Message.pin for more.
Note that the bot needs Manage Messages to do this.

A: You can use for example:
async def pinmessage(ctx, id):
  message = get_message(id)
  pin_message(message)

so when I run
>pinmessage 12345678901234

it will pin that message.


text:
Q: In the basic Fraenkel (permutation) model, any functions from $\omega$ to $P(A)$ has finite range. Working within the Basic Fraenkel (permutation) model. As defined in Jech's axiom of choice.
Let $A$ be the set of atoms.
I want to show that any function  $f: \omega \rightarrow P(A)$ has finite range. But honestly I am really stuck, any help or insights is well appreciated.
Cheers

A: Here is an indirect way, which might not reveal much on the Fraenkel model itself, but it is more informative in other ways.

Theorem 1. (Kuratowski) There is a surjection from $X$ onto $\omega$ if and only if there is an injection from $\omega$ into $\mathcal P(X)$.

This one has a bit of a difficult proof, so I will skip it here.
Recall that a set $A$ is amorphous if it cannot be written as a disjoint union of two infinite sets.

Theorem 2. If $A$ is amorphous, then any function from $A$ into a set which can be well-ordered has a finite range.

Proof. Suppose not, then by the basic properties of well-ordered sets we may assume that the function is onto $\omega$. Now take the pre-image of the odd integers and the even integers, and these must be two disjoint infinite subsets.
Remark. We can extend the proof to "linearly ordered", but conceptually it is easier to prove it about well-ordered sets, and it is enough for our case.

Theorem 3. In the basic Fraenkel model the set of atoms is amorphous.

Proof. If $B\subseteq A$ is an infinite set, let $E$ be a finite set such that whenever $\pi\colon A\to A$ is a permutation satisfying $\pi\restriction E=\operatorname{id}$, $\pi(B)=B$.
If $a\in A\setminus B$, but $a\notin E$, then we may take any $b\in B\setminus E$ and consider the $2$-cycle, $\pi=(a\ b)$. Easily, $\pi\restriction E=\operatorname{id}$ and $p(B)\neq B$. Therefore $A\setminus B\subseteq E$, and thus finite.

Corollary. There is no injection from $\omega$ into $\mathcal P(A)$ in Fraenkel's basic model, where $A$ is the set of atoms.

Proof. There is no surjection from $A$, the set of atoms, in Fraenkel's model onto $\omega$, and therefore no injection from $\omega$ into $\mathcal P(A)$.

A: The same way you show, e.g. that there is no injective function $\omega\to A.$ Assume $f:\omega\to P(A)$ has infinite range, and let $E$ be an arbitrary finite subset of $A.$ Since the range is infinite, you can find two atoms $a_1,a_2$ such that $a_1,a_2\notin E$ and there is an $n\in\omega$ such that $a_1\in f(n)$ but $a_2\notin f(n).$ So the permutation that swaps $a_1$ and $a_2$ fixes $E$ but does not fix $f.$ Thus $E$ is not a support for $f,$ and since $E$ was arbitrary, $f$ is not symmetric.


text:
Q: Make a summary version of lecture notes My aim is to make a summary of my lecture notes. More precisely I would like to write in the same file (per chapter), the whole structure (section, sub-sections), and then:

*

*by default the tcolorbox (definitions / theorems), and be able to put an optional parameter which says that this tcolorbox must not be copied.

*Same thing for the remarks: I would like that by default it is not copied, but I would like to give myself the possibility of doing it too.

I don't know what the best approach is to do all of this.
MWE
\documentclass{scrbook}
\usepackage[skins,breakable,xparse,many]{tcolorbox}
\usepackage{xcolor}
\usepackage{cleveref}

%ENV 1
\NewDocumentCommand\DefinirTheoreme{m m m m m m}{%
    \DeclareTColorBox[auto counter,
        number within       = chapter,
        crefname            = {#5}{#6}]{#1}{ o o }{
        enhanced,
        top                 = 2mm,
        coltitle            = #3,
        colframe            = #4,
        colbacktitle        = white,
        boxrule             = 0.5pt,
        toprule at break    = 0mm,
        bottomrule at break = 0mm,
        attach boxed title to top left={yshift=-0.1in,xshift=0.2in},
        IfValueTF={##1}{title=#2 \thetcbcounter {~|~} {\color{black}\normalfont\bfseries ##1}}{title=#2 \thetcbcounter},
        IfValueTF={##2}{##2}{},
        }
   }%
%
\DefinirTheoreme{defi}{Définition}{blue}{blue}{Définition}{Définitions}

%ENV 2
\newcounter{Rem}[section]
\setcounter{Rem}{0}
\newenvironment{rema}[1][\unskip]{%
    \refstepcounter{Rem}
    \par\vspace{\topsep}%
    \noindent\textcolor{blue}{\sffamily Remarque \thesection.\theRem\:---} \: \textcolor{blue}{#1}}{\smallskip}

%
\begin{document}

\section{The first section (WRITED)}

\begin{defi}[WRITED]
    An important definition.
\end{defi}

\begin{rema}
    Not very important, it is not written in the resume file.
\end{rema}

\section{The first section (WRITED)}

\begin{defi}[not writed]
    an unnecessary definition for the resume file.
\end{defi}

\end{document}


text:
Q: How to attach S3 file to email in Django I'm trying to attach a media file saved in an S3 bucket to an email, which I'm doing with this line of code:
email.attach_file(standard.download.url)

The model is defined as follows:
class Standard(models.Model):
    name = models.CharField(max_length = 51)
    download = models.FileField(upload_to="standard_downloads/", null=True, blank=True)

    def __str__(self):
        return self.name

Within settings.py I have defined my media files as follows:
AWS_DEFAULT_ACL = 'public-read'
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
}
DEFAULT_FILE_STORAGE = 'sme.storage_backends.MediaStorage'
MEDIA_ROOT = 'https://%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME

When trying to run the code I'm getting

No such file or directory:
  'https:/bucket-name.s3.amazonaws.com/media/standard_downloads/filename.ext

Please note it is showing as https:/ (a single /).  How do I correct this?

A: Here's the source code of attach_file from Django. It clearly says - to attach file from the filesystem. It does not work with remote urls. And when you give it a url it thinks you are referring to local file, so it escapes all double slashes to single slashes.
def attach_file(self, path, mimetype=None):
    """
    Attach a file from the filesystem.

    Set the mimetype to DEFAULT_ATTACHMENT_MIME_TYPE if it isn't specified
    and cannot be guessed.

    For a text/* mimetype (guessed or specified), decode the file's content
    as UTF-8. If that fails, set the mimetype to
    DEFAULT_ATTACHMENT_MIME_TYPE and don't decode the content.
    """
    path = Path(path)
    with path.open('rb') as file:
        content = file.read()
        self.attach(path.name, content, mimetype)

Django does not provide anything built-in for that. You will have to write something custom on the lines of above code also using libraries like request or boto. Basically the idea is to fetch from remote url save as temp and then use attach on that.
Here's one example on how you could get the file on the fly:
from django.core.mail.message import attach
import requests
response = requests.get("http://yoururl/somefile.pdf")
email.attach('My file',response.read(),mimetype="application/pdf")

A: A better way to do this would be to leverage default_storage which will work whether you are using local file storage, S3 or any other storage backend.
from django.core.files.storage import default_storage

msg = EmailMessage(
    subject="Your subject",
    body="Your Message",
    from_email="email@yourdomain.com",
    to=["email@anotherdomain.com"],
)

filename = "standard_downloads/filename.ext"
with default_storage.open(filename, "r") as fh:
    msg.attach(filename, fh.read())

msg.send()


text:
Q: Warning: Defined but not used Haskell I have this function, and am using ghc -Wall -Werror to check for warnings. From this method...
polygonList :: Int -> [Int] -> [Polygon]
polygonList n [] = []
polygonList _ [x] = error "Too few points remaining"
polygonList n (v:y:list') =
    let pointList = take (2*v) list' -- Note: list' may not have 2v points
        points = getPoints pointList
        list'' = drop (2v) list'

        -- Calc Perim Here
        Just (under, over) = calcPerim (fromIntegral y) points :: Maybe (Length, Length)
        poly = Polygon { verticesNum = v, yVal = y, vertices = points, bottom = under, top = over }
        nextPolygon = polygonList (n-1) list''
    in (poly : nextPolygon)

... I get two warnings that I need to fix:
polycake.hs:30:11: Warning: Defined but not used: 'ln'
polycake.hs:45:13: Warning: Defined but not used: 'n'
They are needed for the function's exhaustive patterns, but is there a better way that I'm unaware of?

A: Did you look at the locations in the code that the warnings point you to? They are giving you exact line and column numbers.
As pointed out in the comments on your question, there are two places in the following code that have a defined but unused variable:
polygonList :: Int -> [Int] -> [Polygon]
polygonList n [] = []
--          ^ you define n here but do not use it; use _ instead
polygonList _ [x] = error "Too few points remaining"
--             ^ you define x here but do not use it; use _ instead

With those modifications applied, the beginning of your function becomes:
polygonList :: Int -> [Int] -> [Polygon]
polygonList _ [] = []
polygonList _ [_] = error "Too few points remaining"

The underscore _ can be used more than once in a single pattern and signifies that the value at that location should be ignored. It is a useful way of telling the user that your pattern might rely more on the shape of your pattern, or only on certain parts of it.
Note: In the following line, (2v) is an error, do you mean (2 * v)?
list'' = drop (2v) list'


text:
Q: Django doesn't recognize/can't find post_save edited field? I'm trying to create a unique SlugField using a post_save model signal. If the SlugField already exists, a number should be appended to the slug to make it unique.
However, Django does not seem to to recognize when the SlugField already exists.
I'm using a single-tabled inherited MPTT model:
class Text(MPTTModel):
    type = models.CharField(max_length=255, blank=False)  # for STI. Essentially returns the class name.
    title = models.CharField(max_length=255, blank=True)
    slug = models.SlugField(max_length=255, blank=True)
    slug_order = models.CharField(max_length=255, blank=True)

    def __init__(self, *args, **kwargs):
        super(Text, self).__init__(*args, **kwargs)
        # If we don't have a subclass at all, then we need the type attribute to match
        # our current class.
        if not self.__class__.__subclasses__():
            self.type = self.__class__.__name__.lower()
        else:
            subclass = [
                x
                for x in self.__class__.__subclasses__()
                if x.__name__.lower() == self.type
            ]
            if subclass:
                self.__class__ = subclass[0]
            else:
                self.type = self.__class__.__name__.lower()

class Book(Text):
    objects = BookManager()

    class Meta:
        proxy = True

@receiver(post_save, sender=Book, dispatch_uid="create_book_slug")
def create_book_slug(sender, instance, **kwargs):
    slug = slugify(instance.title)
    slug_exists = Book.objects.filter(slug=slug).exists() # This always seems to be False
    counter = 1
    while slug_exists:
        counter += 1
        new_slug = f"{slug}-{counter}"
        slug_exists = Book.objects.filter(slug=new_slug).exists()
    if counter > 1:
        slug = f"{slug}-{counter}"
    instance.slug = slug

My test:
b1 = Book.objects.create(title="book book")
b2 = Book.objects.create(title="book book")

self.assertEqual(b1.slug, "book-book") # True
self.assertEqual(b2.slug, "book-book-2") # False - b2.slug gives "book-book"
self.assertEqual(b1.slug, b2.slug) # This is True... obviously not what I want.

self.assertEqual(Book.objects.filter(slug=b1.slug).exists(), True) # False. I have no idea why.

self.assertEqual(Book.objects.filter(title=b1.title).exists(), True) # True. This works.

I have to use post_save as I actually want to leverage the default MPTT fields (lft, rght, level, get_root() etc.) I actually have another STI model called Chapter that has will utilize slug_order:
class Chapter(Text):
    objects = ChapterManager()

    class Meta:
        proxy = True

@receiver(post_save, sender=Chapter, dispatch_uid="create_chapter_slug")
def create_chapter_slug(sender, instance, **kwargs):
    print(instance.get_root()) # This works and points to the Chapter's top parent
    print(instance.get_root().slug) # This doesn't work and returns nothing
    instance.slug = instance.get_root().slug

    # slug_order code below works
    order = instance.rght - instance.lft
    if instance.level == 1:
        instance.slug_order = order
    else:
        instance.slug_order = f"{instance.parent.slug_order}/{order}"

A: Looks like the the post_save signal doesn't actually save.
i.e.
b1 = Book.objects.create(title="book book")
self.assertEqual(b1.slug, "book-book") # True

b1.refresh_from_db()
self.assertEqual(b1.slug, "") # True

And adding instance.save() to the post_save receiver gives a recursion error.
My initial problem is solved with using pre_save instead for the create_book_slug.
My create_chapter_slug is actually a whole other problem (my method for calculating the order is wrong) that I will be posting on another thread...


text:
Q: Command Prompt input I have a Windows 7 laptop, and I think I installed everything correctly, and I am trying to follow a couple tutorials to learn from. I can make a new application ok, and I can start the server just fine by typing "rails server", and I can go to the localhost:3000 'welcome aboard' page just fine, but after that the tutorials ask me to type other stuff into the command prompt window. The problem is, with the server running, I can't type anything into the command prompt window! I'm obviously doing something wrong.. anyone have any idea of what I should be doing?

A: The easiest way is to open another command window.
I set up students to use more than one command window like this:

*

*one for typing most commands

*one for running the server

*one for printing the log file using the "tail -f" command to show ongoing progress

*one for running rails console


text:
Q: Transform is not triggered again on window resize Following on How to make svg RTL
I made my svg RTL using:
transform: translate(100%, 0) scale(-1, 1);

But when i try resizing my browser window, the transform is not applied and the line origin changes!
Here is an example showing this issue
To replicate:
1- Change the windows size (maybe make it bigger), you can see that the line origin doesn't stay on 0 0
2- Use inspect element on the line, uncheck and then check the "transform" in the css class, the element is returned to its intended position
By doing what i described it is obvious that the transform is not applied on resize.

A: You might want to use viewBox to define the position and dimension of an SVG viewport:
function App() {
  return (

        Please resize the browser window, as you can see the line doesnt remain
        on 0, 0

      <svg viewBox="0 0 200 200" vector-effect="non-scaling-stroke">
        <g className="svgRTL">
          <path
            stroke="green"
            strokeWidth="3"
            fill="none"
            d="M 0 0 L 100 100"
          />
        </g>
      </svg>

  );
}


text:
Q: jquery token-input and active_admin I want to use jquery-token-input with has_many relationship inside active_admin.
What is the best way to do it, and how can i implement it generically so that i can re-use the code for further has_many relationships.
I will be looking forward for your suggestion and guide lines.

A: Well, this doesn't use jquery-token-input, but it works!
I used Chosen.
Download the CSS, JS and png files and put into the appropriate assets directory.
In /app/admin/modelname.rb
ActiveAdmin.register Modlename do

#Customize create and edit form
form do |f|
    f.inputs do
       f.input :name
       f.input :othermodel, :input_html => { :class => "chosen-input" }
    end
  f.buttons
  end
end

In active_admin.js
//= require chosen.jquery.min

$(document).ready(function(){
   $(".chosen-input").chosen();
});

In active_admin.css.scss
/*
   *= require chosen
*/

A: There's a RailsCast on this that I was able to adapt in order to do this.
http://railscasts.com/episodes/258-token-fields
The only additional things to think about are making sure that the javascript and css are included in ActiveAdmin.
For the form in ActiveAdmin, here's what I used (in the file app/admin/story.rb)
ActiveAdmin.register Story do
  form do |f|
    f.inputs "Story details" do
        f.input :title
    end
    f.inputs "Issue Categories" do
        f.text_field :issue_tokens, data: {load: f.object.issues}
    end

    f.actions
  end
end

In this case, my models are Story and Issues, connected by a has and belongs to many relationship.
The only gotcha is that the token input seems to be getting overridden by active admin, trying to figure that one out.
Update
Add the following to app/assets/stylesheets/active_admin.css.sass
@import "token-input";
@import "token-input-facebook";

This gets some of the needed styling going, but some work is still needed, I think due to clashes with active admin styling.


text:
Q: Reactjs+Flow: SyntheticKeyboardEvent and passing functions as props I have the following AsyncApp.js component
AsyncApp.js
// @flow
import React from "react";
import { connect } from "react-redux";
import _ from "lodash";
import { fetchPastLaunchesRequest } from "../actions/launches";
import { LaunchList } from "../components/launches/LaunchList";
import { Picker } from "../components/Picker";

type Props = {
  fetchPastLaunchesRequest: (launch_year: string) => Function,
  launches: Array<Object>,
  hasErrored: boolean,
  isLoading: boolean
};

class AsyncApp extends React.Component<Props, void> {
  componentDidMount() {
    let launch_year = "";
    this.props.fetchPastLaunchesRequest(launch_year);
  }

  handleOnChange = (e: SyntheticKeyboardEvent<HTMLInputElement>) => {
    this.props.fetchPastLaunchesRequest(e.currentTarget.value);
  };

  render() {
    const { launches, isLoading } = this.props;
    let launchYears = _.range(2005, 2019);
    return (

        <Picker options={launchYears} onChange={this.handleOnChange} />
        {isLoading && launches.length === 0 &&
Loading...
}
        {launches.length > 0 ? <LaunchList launches={launches} /> :
}

    );
  }
}

const mapDispatchToProps = (dispatch: *) => {
  return {
    fetchPastLaunchesRequest: launch_year =>
      dispatch(fetchPastLaunchesRequest(launch_year))
  };
};

const mapStateToProps = state => {
  return {
    launches: state.launches.items,
    hasErrored: state.itemsHasErrored,
    isLoading: state.itemsIsLoading
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(AsyncApp);

Picker.js
//@flow

import React from "react";

type PickerProps = {
  options: Object,
  onChange: (e: HTMLInputElement) => void
};

export const Picker = ({ options, onChange }: PickerProps) => {
  return (

      <select onChange={e => onChange(e)}>
        <option defaultValue=" ">Pick Year</option>
        {options.map(year => (
          <option value={year} key={year}>
            {year}
          </option>
        ))}
      </select>

  );
};

I keep getting this type checking error in the AsyncApp.js component:
[flow] Cannot create `Picker` element because `SyntheticKeyboardEvent` [1] is incompatible with `HTMLSelectElement` [2] in the first argument of property `onChange`. (References: [1] [2])
(property) AsyncApp.handleOnChange: (e: any) => void
[Flow]
handleOnChange: (e: SyntheticKeyboardEvent < HTMLInputElement > ) => void

A: Changed argument type for onChange to HTMLInputElement
//@flow

import React from "react";

type PickerProps = {
  options: Object,
  onChange: (e: HTMLInputElement) => void
};

export const Picker = ({ options, onChange }: PickerProps) => {
  return (

      <select onChange={e => onChange(e)}>
        <option defaultValue=" ">Pick Year</option>
        {options.map(year => (
          <option value={year} key={year}>
            {year}
          </option>
        ))}
      </select>

  );
};

A: Just for the record. You could also use a wildcard:
onChange: (SyntheticEvent<*>) => void

or
onChange: (SyntheticInputEvent<*>) => void

A: Instead of using SyntheticEvent we can also use KeyboardEvent to identify the type of keyboard key pressed.
const handleKeyDown = (event: React.KeyboardEvent<HTMLElement>) => {}


text:
Q: How to make pynput prevent certain keystrokes from reaching a particular application? I want to create a tool which will allow me to use some of the Vim-style commands in an application (Scrivener) that does not support it.
For example, if

*

*the current mode is Command mode and

*the user presses the button w,

then, the caret should move one character to the right. Instead of the w character, Scrivener should receive the "right arrow" signal.
To implement this, I wrote the following code (based on these 2 answers: 1, 2):
from pynput.keyboard import Key, Listener, Controller
from typing import Optional
from ctypes import wintypes, windll, create_unicode_buffer

def getForegroundWindowTitle() -> Optional[str]:
    hWnd = windll.user32.GetForegroundWindow()
    length = windll.user32.GetWindowTextLengthW(hWnd)
    buf = create_unicode_buffer(length + 1)
    windll.user32.GetWindowTextW(hWnd, buf, length + 1)
    if buf.value:
        return buf.value
    else:
        return None

class State:
    def __init__(self):
        self.mode = "Command"

state = State()
keyboard = Controller()

def on_press(key):
    pass

def on_release(key):
    if key == Key.f12:
        return False
    window_title = getForegroundWindowTitle()
    if not window_title.endswith("Scrivener"):
        return
    print("Mode: " + state.mode)
    print('{0} release'.format(
        key))
    if state.mode == "Command":
        print("1")
        if str(key) == "'w'":
            print("2")
            print("w released in command mode")
            # Press the backspace button to delete the w letter
            keyboard.press(Key.backspace)
            # Press the right arrow button
            keyboard.press(Key.right)
    if key == Key.insert:
        if state.mode == "Command":
            state.mode = "Insert"
        else:
            state.mode = "Command"

# Collect events until released
print("Press F12 to exit")

with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

Whenever I press the button w in Scrivener in Command mode, two keystrokes are sent to Scrivener:

*

*Backspace to delete the already typed w character.

*Right arrow to move the caret.

This kinda works, but you can see the w character being displayed and deleted again (see this video).
How can I make sure that the keystroke with w does not reach Scrivener at all, if the mode is Command and currently focused window is the Scrivener application?

A: First you need to install pyHook and pywin32 library.
Then monitor the keyboard information through pyhook. If you need to intercept the keyboard information (for example, press w), return False.
Finally, through pythoncom.PumpMessages () to achieve loop monitoring.
Here is the sample:
import pyHook
import pythoncom
from pynput.keyboard import Key, Listener, Controller
keyboard = Controller()
def onKeyboardEvent(event):
    if event.Key == "F12":
        exit()
    print("1")
    if event.Key == 'W':
        print("2")
        print("w released in command mode")
        # Press the right arrow button
        keyboard.press(Key.right)
        return False

    print("hook" + event.Key)
    return True

# Collect events until released
print("Press F12 to exit")
hm = pyHook.HookManager()
hm.KeyDown = onKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()


text:
Q: Symfony2 - Is an AdminBundle actually the correct way to organise the app? I'm new to Symfony and am starting an app which includes an admin section. The general advice is pretty obvious - make an AdminBundle.
However, is that really the best practice? The Symfony documentation is saying that a bundle is intended to be a 'plugin' that can be distributed as is, and will work in another app. Doesn't the admin section need to be aware of all the models and things for the main app though? It's an admin section created to administer changes specifically to my app, so how would it be distributable or self-contained?
I feel like I'm missing something because if all the advice is to make an AdminBundle then I obviously don't understand something or haven't delved far enough into Symfony yet.
I'm just looking to get my app started with the correct structure going forward.
FYI, I created a project with the default AppBundle as well. I was just planning to make everything in there, but that doesn't seem right either as it will be harder to organise all the admin stuff separately.

A: I think it depeneds on tour needs and size of your project. Creating a special bundle to put there logic for of admin panel is a good practice. But if you have a small application with just couple of entities it's not necessary to create AdminBundle.
Symfony provides you any way you prefer to do what you need. You can create bundle or put all the admin panel business logic into special directory inside your main bundle controller directory or put all code into the same controllers and manage permissions to admin actions by setting up firewall.
I would suggest to use AdminBundle. It lets you keep your code cleaner: a client logic in one bundle, an admin logic is in another.
Bundle description taken from symfony official documentation isn't saying any opposite things. Because if you want you can use your AdminBundle in another app. Bundle is a way to keep different kind of business logic separated of each other.


text:
Q: How do I retrieve values put in an input box for use with my function? I'm trying to take values from a few input boxes in my html and return the value inside of another in input element.
If i hardcode the var with the info I want, it does return a value properly.
My code looks like this:

    <title>Compounding interest in javascript</title>

    <form>

Enter Amount You Would Like To Set Aside Per Month

        <input type="text">

Enter The Number Of Months Before You Plan To Withdraw

        <input type="text" id="numOfMonths">

Enter Your Interest Rate

        <input type="text">
        <input type="button" id="calcButton" value="Click Me!" onClick="calcValue()">
        <input type="text" id="finalValue">
    </form>

Thanks for your help!

A: You need to use .value to get the contents of an input field. And you should use Number() to convert a string input to a number (you could also use parseInt() or parseFloat() if you want to specify what type of number to convert it to).
And there's no reason to put the result into the output field every time through the loop, just do it once at the end.
You should initialize balance to zero every time you call the function. Otherwise, you'll add the contributions to the previous balance.
Another problem is that you have
 and
. The ID should be in the <input>.

function calcValue() {
  var balance = 0;
  var term = Number(document.getElementById("numOfMonths").value);
  var interest = Number(document.getElementById("interestRate").value) / 100 / 12;
  var contribution = Number(document.getElementById("amountPerMonth").value);

  for (i = 0; i < (term + 1); i++) {
    balance = (balance + contribution) * (1 + interest);
  }
  var rounded = Math.round(balance * 100) / 100;
  document.getElementById("finalValue").value = rounded;
}
<form>

Enter Amount You Would Like To Set Aside Per Month

  <input type="text" id="amountPerMonth">

Enter The Number Of Months Before You Plan To Withdraw

  <input type="text" id="numOfMonths">

Enter Your Interest Rate

  <input type="text" id="interestRate">
  <input type="button" id="calcButton" value="Click Me!" onClick="calcValue()">
  <input type="text" id="finalValue">
</form>

BTW, you know there's a formula to compute compound interest, you don't need to use a loop for it, right? See Wikipedia

A: These are few issues with your code.

*

*document.getElementById("id") will fetch the DOM element. To get the value, you need to use document.getElementById("id").value

*The "id" attributes need to be set on the input elements instead of the h3, because you are accessing document.getElementById("amountPerMonth").value and "value" attribute applies for elements such as input and not headings etc.

*document.getElementById is a javascript function and you need to pass a string as the attribute. Passing "#id" will look for the an element with id as "#id". You seem to be confusing jQuery with Javascript here. In jQuery, it would be $("#id").

*In the for loop, you have (term+1) where term is actually a string. So "1" will be appended to the string causing the for loop to run an incorrect number of times. So proper use of parseInt and parseFloat need to be done.
After these changes, your program should work as expected.
This is the corrected code.

<title>Compounding interest in javascript</title>

<form>

Enter Amount You Would Like To Set Aside Per Month

    <input type="text" id="amountPerMonth">

Enter The Number Of Months Before You Plan To Withdraw

    <input type="text" id="numOfMonths">

Enter Your Interest Rate

    <input type="text" id="interestRate">
    <input type="button" id="calcButton" value="Click Me!" onClick="calcValue()">
    <input type="text" id="finalValue">
</form>

A: Here is a solution to your problem:
HTML:
<form>
Enter Amount You Would Like To Set Aside Per Month
    <input type="text" name="amountPerMonth" id="amountPerMonth"/>

    Enter The Number Of Months Before You Plan To Withdraw
    <input type="text" name="numOfMonths" id="numOfMonths"/>

    Enter Your Interest Rate
    <input type="text" name="interestRate" id="interestRate"/>

    <input type="button" id="calcButton" value="Calculate"/>

    <input type="text" name="finalValue" id="finalValue"/>
</form>

jQuery:
var term = 0;
var interest = 0;
var contribution = 0;
var balance = 0;
var i=0;
var rounded=0;

$('#calcButton').click(function(){
term = parseInt($("#numOfMonths").val());
    interest = (parseInt($("#interestRate").val())/100) / 12;
    contribution = parseInt($("#amountPerMonth").val());

    for (i=0;i<(term+1);i++){
        balance = (balance + contribution) * (1 + interest);

            var rounded = Math.round( balance * 100 ) / 100;
            $("#finalValue").val(rounded);
    }
});

And here's a fiddle for this:
https://jsfiddle.net/2cg2kncn/

A: There are a few things you can improve in your code-

*

*The variables you are using in a particular method should be in declared inside the method.

*document.getElementById("id") returns DOM object, so you should use ".value' to get value of text box.

*Instead of writting id="amountPerMonth" and id="interestRate" with
 you should write it with <input> box, so that you can get value from it. Other wise document.getElementById will not work.

*Once you get the final value of balance, you can assign it outside the for loop.
Here is the solution for your code-

    <title>Compounding interest in javascript</title>

    <form>

Enter Amount You Would Like To Set Aside Per Month

    <input type="text" id="amountPerMonth">

Enter The Number Of Months Before You Plan To Withdraw

    <input type="text" id="numOfMonths">

Enter Your Interest Rate

    <input type="text" id="interestRate">
    <input type="button" id="calcButton" value="Click Me!" onClick="calcValue()">
    <input type="text" id="finalValue">
    </form>


text:
Q: How do I get the dom node of a child element in a component without adding logic to its parent/children? In the following example WrapperComp needs to get access to the dom node of the divs in line 5 and line 8, without adding logic to PageComp or ItemComp. The only things I could change in PageComp are the div tags. E.g. I could add a ref, prop, data-attribute, etc to them.
The divs don't have to be created inside PageComp. WrapperComp would be allowed to create them too, but they must wrap each of its children (In this case each ItemComp).
Example
class PageComp extends React.Component {
  render() {
    return (
    <WrapperComp>

        <ItemComp/>

        <ItemComp/>

    </WrapperComp>
    );
  }
}

class WrapperComp extends React.Component {
  render() {
    return (

A wrapper

        {this.props.children}

    );
  }
}

class ItemComp extends React.Component {
  render() {
    return (

An item

    );
  }
}

ReactDOM.render(
  <PageComp/>,
  document.getElementById('app')
);

JSBIN
What I tried so far:

*

*I already tried to put a ref= on the divs, but that ref would only be available in PageComp not in WrapperComp.

*I also tried to create the divs inside WrapperComp and put a ref= on them  from there, but that would result in a Refs Must Have Owner Warning
Now I wonder.. what would be an appropriate way in react to solve that problem?
Till now the only solution that came to my mind was to put a data-attribute on each div and search the dom for them after componentDidMount like that: document.querySelectorAll('[data-xxx]'). Perhaps I'm not sure if this is how you do it in react..
Why do I want to get the node inside WrapperComp?
I want to create a component that adjusts the dimensions of its children. In the example that component would be WrapperComp. The adjustments can only be done after the children rendered to the dom, e.g. to get clientHeight.

A: If you don't restrict that this needs to be solved by how one should get the DOM, pass them down, etc, I would get rid of the puzzle and approach it in a different direction.
Since you are not given much control to <PageComp> whereas <WrapperComp> seems flexible, I would do the wrapping in the later by transforming the passed children to what you need them to be.
class PageComp extends React.Component {
  render() {
    return (
      <WrapperComp>
        <ItemComp/>
        <ItemComp/>
      </WrapperComp>
    );
  }
}

class WrapperComp extends React.Component {
  render() {
    const wrappedChldren = React.Children.map(this.props.children, function(child) {
      return (

A wrapper

          { child }

      );
    });
    return
{ wrappedChildren }
;
  }
}

With this concentrate can be put on the transformation in the <WrapperComp>, which is pretty intuitive as its name suggests.


text:
Q: Move/Respawn multiple game objects to original position after player dies I want to move multiple games objects to the original position, after the player dies. That is the following code, but I don't know, why it is not working.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class respawn : MonoBehaviour
{
 public lvlmanager Lvlmanager;
 public GameObject[] resetObjekt;

 private Vector3[] originalPosition;
 private Quaternion[] originalRotation;
 private Rigidbody2D[] objektBody;

 private void Start()
 {
     Lvlmanager = FindObjectOfType<lvlmanager>();
     for(int i = 0; i < resetObjekt.Length; i++)
     {
         originalPosition[i] = resetObjekt[i].transform.position;
         originalRotation[i] = resetObjekt[i].transform.rotation;
         objektBody[i] = resetObjekt[i].GetComponent<Rigidbody2D>();
         Debug.Log(originalPosition[i]);
     }
 }
 void OnTriggerEnter2D(Collider2D other)
 {

     if (other.tag == "player")
     {
         Debug.Log("player dead");
         Lvlmanager.RespawnPlayer();
         for (int i = 0; i < resetObjekt.Length; i++)
         {
             objektBody[i].velocity = Vector3.zero;
             objektBody[i].bodyType = RigidbodyType2D.Static;
             resetObjekt[i].transform.position = originalPosition[i];
             resetObjekt[i].transform.rotation = originalRotation[i];
             objektBody[i].bodyType = RigidbodyType2D.Kinematic;
         }
     }
 }
 }

When I start the game, it shows following error:

NullReferenceException: Object reference not set to an instance of an object respawn.Start () (at Assets/script/respawn.cs:21)

Anyone knows, what the problem is?
Those objects are platforms that fall, that's why I use kinematic etc.

A: originalPosition,originalRotation and objektBody is never assigned to.
Before referencing them in Start() you should do
originalPosition = new Vector3[resetObjekt.Length];
originalRotation = new Quaternion[resetObjekt.Length];
objektBody = new Rigidbody2D[resetObjekt.Length];


text:
Q: How come SMPS regulators doesn't show current limiting circuit? for example the LM2678-ADJ is a famous buck converter, there are also many others. I have googled and looked through other regulators, there are many schematics in the datasheets of how you make the output voltage adjustable.
But there does not seem to be any info about current limiting for buck converters. Why is that? Is it harder to make current limiting work on a smps rather than a linear regulator?
LM2678 datasheet: http://www.ti.com/lit/ds/symlink/lm2678.pdf
Thanks!

A: You must not have looked very hard to not find a buck controller with selectable current limit. LM5088 is one example, there are many others.
That being said, there's no "natural" place to measure current in a buck controller. With a boost controller you can measure the switch current from source to gnd with a resistor, easy as a pie.
With a BUCK converter you cannot measure anything against GND, it's a differential measurement across the switch. You could certainly insert a resistor in series with the switch and use a differential opamp circuit to measure that. I actually did so with my first custom buck converter back in the day. However that eats up power as you need fairly large voltage drop to measure it reasonably and/or you need an expensive differential opamp to get the job done.
Therefore usually the current sense is integrated to the controller itself and there are various ways this is done. One popular method with integrated switchers is to measure the voltage drop over the (internal) mosfet, not that difficult to do if you're already doing your own custom chip. Other styles are measuring the low-side current as with LM5088 but this cannot unfortunately used directly but requires some processing. Yet another method is to measure ripple current in the output capacitor, which TI calls DCAP control.
There was a point when manufacturers started pushing voltage mode control chips again but you seriously want to stay away from those, they're evil. Well, for some applications they can be OK but have serious drawbacks which is beyond the scope here.
P.s. LM2678 may be "famous" but it's something of a hurr-durr controller. "Simple" may be good for hobbyist or for a designer fresh out of school on his first design (ahem) but for serious work it's far too restrictive.


text:
Q: Command not found when executing through lxc-attach I am running Arch Linux with a Debian lxc container.
The container is running and I am able to login via lxc-console -n name.
If I use lxc-attach -n name and try to execute a command like ls or something other basic things I get bash: ls: command not found.
Any hints where I have to set a PATH variable?


text:
Q: Entity view with a collection inside not working with Blaze persistance I have a problem with entity views using blaze persistence library. I want to retrieve a list of Suppliers, each one with a list of Products but I'm getting an exception while creating Entity views model.
Setup

*

*Blaze persistence core 1.6.6

*Blaze persistence Entity View 1.6.6

*Spring Data JPA 2.5.6

*Hibernate 5.4.27

I'm using Blaze base configuration shown here.
Model
This is my model (I have removed some fields to be more clear):
@Entity(name = "suppliers")
public class Supplier extends BaseEntity {
    @Column(nullable = false, length = 100)
    private String businessName;

    @OneToMany(mappedBy = "supplier")
    private List<Product> products;
}

@Entity(name = "products")
public class Product extends BaseEntity {
    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private Integer price;

    @ManyToOne
    private Supplier supplier;
}

Entity views
@EntityView(Supplier.class)
public interface SupplierWithProductsView {
    Integer getId();
    String getBusinessName();

    List<ProductView> getProducts();
}

@EntityView(Product.class)
public interface ProductView {
    Integer getId();
    String getName();
    Integer getPrice();
}

Exceptions
The exception I get at startup is the following:
Caused by: java.lang.IllegalArgumentException: Illegal occurence of [products] in path chain resolver!
    at com.blazebit.persistence.parser.PathTargetResolvingExpressionVisitor.invalid(PathTargetResolvingExpressionVisitor.java:562) ~[blaze-persistence-core-parser-1.6.6.jar:1.6.6]
    at com.blazebit.persistence.parser.PathTargetResolvingExpressionVisitor.visit(PathTargetResolvingExpressionVisitor.java:468) ~[blaze-persistence-core-parser-1.6.6.jar:1.6.6]
    at com.blazebit.persistence.parser.expression.EntityLiteral.accept(EntityLiteral.java:50) ~[blaze-persistence-core-parser-1.6.6.jar:1.6.6]
    at com.blazebit.persistence.view.impl.metamodel.MetamodelUtils.isIndexedList(MetamodelUtils.java:125) ~[blaze-persistence-entity-view-impl-1.6.6.jar:1.6.6]
    at com.blazebit.persistence.view.impl.metamodel.MetamodelUtils.isIndexedList(MetamodelUtils.java:120) ~[blaze-persistence-entity-view-impl-1.6.6.jar:1.6.6]
    at com.blazebit.persistence.view.impl.metamodel.AttributeMapping.determineIndexed(AttributeMapping.java:333) ~[blaze-persistence-entity-view-impl-1.6.6.jar:1.6.6]
    at com.blazebit.persistence.view.impl.metamodel.attribute.AbstractMethodListAttribute.<init>(AbstractMethodListAttribute.java:61) ~[blaze-persistence-entity-view-impl-1.6.6.jar:1.6.6]
    at com.blazebit.persistence.view.impl.metamodel.attribute.MappingMethodListAttribute.<init>(MappingMethodListAttribute.java:35) ~[blaze-persistence-entity-view-impl-1.6.6.jar:1.6.6]
    at com.blazebit.persistence.view.impl.metamodel.MethodAttributeMapping.getMethodAttribute(MethodAttributeMapping.java:757) ~[blaze-persistence-entity-view-impl-1.6.6.jar:1.6.6]
    at com.blazebit.persistence.view.impl.metamodel.ManagedViewTypeImpl.<init>(ManagedViewTypeImpl.java:319) ~[blaze-persistence-entity-view-impl-1.6.6.jar:1.6.6]
    at com.blazebit.persistence.view.impl.metamodel.FlatViewTypeImpl.<init>(FlatViewTypeImpl.java:41) ~[blaze-persistence-entity-view-impl-1.6.6.jar:1.6.6]
    at com.blazebit.persistence.view.impl.metamodel.ViewMappingImpl.getManagedViewType(ViewMappingImpl.java:892) ~[blaze-persistence-entity-view-impl-1.6.6.jar:1.6.6]
    at com.blazebit.persistence.view.impl.metamodel.MetamodelBuildingContextImpl.getManagedViewType(MetamodelBuildingContextImpl.java:234) ~[blaze-persistence-entity-view-impl-1.6.6.jar:1.6.6]
    at com.blazebit.persistence.view.impl.metamodel.ViewMetamodelImpl.<init>(ViewMetamodelImpl.java:88) ~[blaze-persistence-entity-view-impl-1.6.6.jar:1.6.6]
    at com.blazebit.persistence.view.impl.EntityViewManagerImpl.<init>(EntityViewManagerImpl.java:271) ~[blaze-persistence-entity-view-impl-1.6.6.jar:1.6.6]
    ... 60 common frames omitted

I tried to take some tests by debugging and investigating in the library code and I found that if I add @MappingIndex to the products list in the view, the exception thrown seems more clear. I haven't fully understood how the mapping index works but maybe it is correlated. The following is the new exception:
Caused by: java.lang.IllegalArgumentException: There are error(s) in entity views!
The resolved possible types [java.util.List] are not assignable to the given expression type 'java.util.Collection<my.package.Product>' of the mapping expression declared by the attribute products[my.package.SupplierWithProductsView.getProducts]!
    at com.blazebit.persistence.view.impl.EntityViewManagerImpl.<init>(EntityViewManagerImpl.java:285) ~[blaze-persistence-entity-view-impl-1.6.6.jar:1.6.6]
    at com.blazebit.persistence.view.impl.EntityViewConfigurationImpl.createEntityViewManager(EntityViewConfigurationImpl.java:206) ~[blaze-persistence-entity-view-impl-1.6.6.jar:1.6.6]
    at my.package.configurations.BlazePersistenceConfig.createEntityViewManager(BlazePersistenceConfig.java:44) ~[main/:na]

... other lines omitted

Anyone has any idea how to solve my problem?
Thanks in advance!

A: I tested your sample app now and I saw this exception:
Caused by: java.lang.IllegalArgumentException: Illegal occurence of [products] in path chain resolver!
    at com.blazebit.persistence.parser.PathTargetResolvingExpressionVisitor.invalid(PathTargetResolvingExpressionVisitor.java:562)
    at com.blazebit.persistence.parser.PathTargetResolvingExpressionVisitor.visit(PathTargetResolvingExpressionVisitor.java:468)
    at com.blazebit.persistence.parser.expression.EntityLiteral.accept(EntityLiteral.java:50)
    at com.blazebit.persistence.view.impl.metamodel.MetamodelUtils.isIndexedList(MetamodelUtils.java:125)
    at com.blazebit.persistence.view.impl.metamodel.MetamodelUtils.isIndexedList(MetamodelUtils.java:120)
    at com.blazebit.persistence.view.impl.metamodel.AttributeMapping.determineIndexed(AttributeMapping.java:333)
    at com.blazebit.persistence.view.impl.metamodel.attribute.AbstractMethodListAttribute.<init>(AbstractMethodListAttribute.java:61)
    at com.blazebit.persistence.view.impl.metamodel.attribute.MappingMethodListAttribute.<init>(MappingMethodListAttribute.java:35)
    at com.blazebit.persistence.view.impl.metamodel.MethodAttributeMapping.getMethodAttribute(MethodAttributeMapping.java:757)
    at com.blazebit.persistence.view.impl.metamodel.ManagedViewTypeImpl.<init>(ManagedViewTypeImpl.java:319)
    at com.blazebit.persistence.view.impl.metamodel.FlatViewTypeImpl.<init>(FlatViewTypeImpl.java:41)
    at com.blazebit.persistence.view.impl.metamodel.ViewMappingImpl.getManagedViewType(ViewMappingImpl.java:892)
    at com.blazebit.persistence.view.impl.metamodel.MetamodelBuildingContextImpl.getManagedViewType(MetamodelBuildingContextImpl.java:234)
    at com.blazebit.persistence.view.impl.metamodel.ViewMetamodelImpl.<init>(ViewMetamodelImpl.java:88)
    at com.blazebit.persistence.view.impl.EntityViewManagerImpl.<init>(EntityViewManagerImpl.java:271)

The error means that the expression products, which is created behind the scenes for SupplierWithProductsView#getProducts, is illegal. This is an unfortunate side effect of the association being named the same as the entity ProductEntity i.e. @Entity(name = "products"). I created the following bug report for this and will look into this as soon as possible: https://github.com/Blazebit/blaze-persistence/issues/1450
In the meantime, you could rename the association to e.g. productList, seelingProducts or something like that. Alternatively, you could also rename the entity by using @Entity(name = "product") i.e. omitting the s.


text:
Q: Find the difference between two vectors and the mean of the result So, with the help of someone here in stats i could solve  most of my problems.
Now i'm stuck at this part:
I have the below code, which worked very well if this values were fixed.
immediate.amput.below.EV
watchful.wait.EV

Now what they are is vectors. They represent a vector with [n_psa] size.
What i need to do is, i need iterate for n_psa values, i.e for 100 values and find the difference between each  immediate.amput.below.EV[1] - watchful.wait.EV[1] and so on, save the results only as positive numbers, even if the output is a negative number in a new vector, and find the mean of the new vector.
This is what i used to do.
DELTA_COST <- max(immediate.amput.below.EV,watchful.wait.EV) - min(immediate.amput.below.EV,watchful.wait.EV)
mean(DELTA_COST)

A: To calculate the absolute value in R, use the function abs(). Below is an example for vectors a and b. The sizes can change as long as they have the same dimension, otherwise you will get strange results or errors.
a <- c(1, 4, 8, 20)
b <- c(50, 2, 4, 21)
DELTA_COST <- abs(a-b)

DELTA_COST
[1] 49   2   4  1

mean(DELTA_COST)
[1] 14


text:
Q: SVN projects folder structure I am new to svn. I have installed SVN on Linux CentOS 6.3 machine. I have created few projects under SVN and the location is /var/www/svn/<MyRepos> ..
Now that we have to create few repos under one folder, so it should look like:
/var/www/svn/Common/ProjA/[trunk,branch,tags]
/var/www/svn/Common/ProjB/[trunk,branch,tags]
/var/www/svn/release/ProjA/[trunk,branch,tags]
/var/www/svn/release/ProjB/[trunk,branch,tags]

I created /common directory thru Linux mkdir and created /ProjA thru svnadmin create, which was successful, but when tried to access from browser, it was not able to connect. Is this is the correct way to do it? please advice.
Note: The files will be imported from cvs thru cvs2svn tool as we are doing the migration from CVS to SVN.

A: You cannot manipulate a directory stucture in a Subversion repository using the standard shell commands mkdir, cp, mkdir, mv, etc. You must use a Subversion client and point it at the repository URL. The directory/file structure is not visible via the host filesystem - it can only be viewed and manipulated via the Subversion libraries.
Before you go any further, you must read the fine manual and gain an understanding of the basics of how the repository works and how to interact with it. You cannot just install it, throw a few shell commands around, and hope for the best.

A: Thanks for the suggestions everyone. I have found the solution, I just had to create new location tag in the subversion.conf so as to create the above said structure.


text:
Q: how to a translatable string in drupal theme? I want to put a string as a signature in drupal theme I am working on. the website is multilingual and the string should be translated based on the current language of the website. I don't know how to do it.
my drupal version is 6.
Would you help me?

A: Wrap your message in the t() function.
http://api.drupal.org/api/drupal/includes!common.inc/function/t/6
Then see this page for a brief guide on localizing:
http://drupal.org/node/322729


text:
Q: In Nuclear Magnetic Resonance what is the Rotating Frame? My understanding is that there's an initial precession frequency ($\omega_0$) about the direction of magnetization ($z$). Then when you excite the nucleus into the spin state with the radio frequency pulse, the direction of Nucleus's Magnetic Moment rotates orthogonality ($x$) to the pulse direction ($y$) changing the bulk magnetization.
This bulk magnetization is still precessing about the direction of magnetization ($z$), so is the rotating frame just accounting for that precession?
I'm pretty sure the rotation ($\omega_1$) about the direction of pulse magnetization (that is about $x$) doesn't have anything to do with the frequency of the rotating frame. My understanding is that precession only relates to the pulse length.
I'm just not sure what the rotating frame is or how it relates to the measurement of induced current from free induction decay.
Edit: I posted this question in several locations, so here's a summary of the answers I got.

*

*The Initial Precession Frequency (ω0) is the Rotating Frame.

*The Pulse Rotation (ω1) is in the Rotating Frame.

*I'm still not clear on how Bulk Magnetization develops after a pulse sequence.

A: The rotating frame is, as you say, just to account for the rotation about the $z$ axis. More precisely, it's a choice of frame that "undoes" the rotation. This also allows us to think of the RF magnetic field as simply a pulsed static magnetic field along a particular direction (say $x$). From this, we can easily see how the RF magnetic field simply rotates the magnetization in the $xz$ plane.
This also answers the question regarding $\omega_1$, since it is clear that the precession amount only depends on the pulse length and the strength of the pulsed RF field. $\omega_0$ was already taken into account in transforming to the rotating frame, and in a sense is no longer relevant.


text:
Q: Pythonnet: how to use an embedded python intepreter? I'm trying to use an embedded python interpreter from C# using pythonnet (the python3 compatible version found at https://github.com/renshawbay/pythonnet)
My interpreter is located in D:\src\scratch\TestPythonNet\TestPythonNet\PythonRuntime and has the "Lib" and "Libs" folder from the python distribution.
I've tested using the following code:
   <!-- language: c# -->
   PythonEngine.PythonHome = @"D:\src\scratch\TestPythonNet\TestPythonNet\PythonRuntime";
   PythonEngine.ProgramName = "PythonRuntime";
   PythonEngine.Initialize();
   using (Py.GIL())
   {
      PythonEngine.RunSimpleString("print(1)");
   }

But, it doesn't work. I get a "SystemError: PyEvalCodeEx: NULL globals". Everytime I try to get an object from python, the code fails.
What am I doing wrong?

A: I think I've found the answer. If I add a reference to the "clr" module provided by pythonnet, it does work
PythonEngine.PythonHome = @"D:\src\scratch\TestPythonNet\TestPythonNet\PythonRuntime";
PythonEngine.ProgramName = "PythonRuntime";
PythonEngine.Initialize();
// ==>
PyObject a = PythonEngine.ImportModule("clr");
using (Py.GIL())
{
    PythonEngine.RunSimpleString("print(1)");
}


text:
Q: Strange memory leak with analyze on text setting of UILabel When I Product > Analyze the clang analyzer gives me a memory leak I do not understand. It says that I am leaking in the second line something what was initialized in the first line of the following code
[[testView newScore] setText: [NSString stringWithFormat: @"+%d", addScore]];
[[testView newScore] setTextColor: [UIColor greenColor]];

As Instruments isn't working right now (I am using Xcode 4.1 with SDK 4.3) I can't investigate this leak any further.
Do you see why this could be a memory leak. The property newScore is defined like this:
@property (nonatomic, retain) UILabel *newScore;

and testView is a subclass of UIView.
Edit: Screenshot of the analyzer output:

Thank you for reading!

A: Can you post a screenshot of the analyzer output (i.e. the blue arrows pointing to the problematic control flow)?

Derp;  I missed the obvious.  Sorry.   The method is named newScore and the new* prefix indicates to the compiler that the object returned is +1 retain count.
Rename the method and all will be well.