text:
Q: Explicit instantiation of class templates is ignored? I wanted to check that the extern keyword did infact prevent class code being generated in the translation unit:
template<class> struct always_false : std::false_type {};

template <typename T> class A{
    static_assert(always_false<T>::value, "If this fires, 'A' is instantiated");
};

extern template class A<int>; //error: static assertion failed: If this fires, 'A' is instantiated|

int main(){
//    A<int> f;
}

Why is it that the previous code still produces an error from the static_assert if this is my only source file? As far as I understand from the explicit use of extern this should prevent any production of code for the class A<int> and the linker takes care of finding a later explicit instantiation definition (in the translation unit for which the code is actually written) to match any use of A<int> with.
However it seems that the explicit instantiation declaration is generating code in this translation unit itself as indicated by the compilation error. If I comment out extern template class A<int> everything works fine. I was using GCC 4.9.2. but it appears clang 3.5.1 throws this error too.
Alternatively this also kicks up the same assert error:
template<class> struct always_false : std::false_type {};

template <typename T> class A{
public:
    void test() { static_assert(always_false<T>::value, "If this fires, 'test()' is instantiated"); }
};

extern template void A<int>::test();

int main(){
    A<int> a;
    a.test();
}

Here I would've expected the member function A<int>::test() to not even be instantiated and again wait until linking before "finding" code for the function, but it looks like the code is generated in the same translation unit. However if I take out the static_assert:
template <typename T> class A{
public:
    void test() { }
};

extern template void A<int>::test();

int main(){
    A<int> a;
    a.test();
}

Then I get the error I'm expecting, indicating that A<int>::test() is not instantiated and there was a linker error:
**undefined reference to `A<int>::test()'|**

Why would the static_assert throw an error if test() was never instantiated?

A: Your premise is wrong. extern template prevents object code generation for function templates (including member functions of class templates), but it doesn't prevent the instantiation of the class bodies.
Edit: To answer the updated question: the member function is defined inline in the class, so the compiler will still instantiate it so that it can inline it if necessary. If you define the function out of line, you will not get an error (tried GCC 5.2.0 via godbolt).
#include <type_traits>

template<class> struct always_false : std::false_type {};

template <typename T> class A{
public:
    void test();
};

template <typename T>
void A<T>::test() { static_assert(always_false<T>::value, "If this fires, 'test()' is instantiated"); }

extern template void A<int>::test();

int main(){
    A<int> a;
    a.test();
}


text:
Q: Concept of constant property during initialization in Swift "
For class instances, a constant property can be modified during initialization only by the class that introduces it. It cannot be modified by a subclass."
Excerpt From: Apple Inc. "The Swift Programming Language (Swift 3.1)." iBooks.
I am having difficulty in understanding this, Since i am able to modify the property by a subclass also.
Below is the code.
class ConstantTest {
    let constant: String
    init(constant: String) {
        self.constant = constant
    }
    func printConstant() {
        print(constant)
    }
}

let constanttest = ConstantTest(constant: "Hello")
constanttest.printConstant()

class SubConstClass: ConstantTest { }

var subTest = SubConstClass(constant: "hey")
subTest.printConstant()

A: The key to your confusion is what it means for a subclass to initialize a constant property. This means that a subclass cannot introduce an initializer that assigns the value. Let's consider a simple case:
class Person {
    let name: String
    init() {
        name = "Alice"
    }
}

This could be more simply written by assigning name in its declaration, but I'm hoping this is clearer. Now we want to create a subclass that assigns name to something else. The obvious way to do this (and how you'd do it in languages that don't have constant properties) would be to assign it after calling super.init():
class Employee: Person {
    override init() {
        super.init()
        name = "Bob" // error: cannot assign to property: 'name' is a 'let' constant
    }
}

Nope. We run into exactly the case described in your excerpt. Well, maybe we should assign it first?
class Employee: Person {
    override init() {
        name = "Bob" // error: cannot assign to property: 'name' is a 'let' constant
        super.init()
    }
}

Nope. No better.
Ah! It's because we call super.init(). Let's just not call it.
class Employee: Person {
    override init() {
        name = "Bob" // error: cannot assign to property: 'name' is a 'let' constant
    }
}

No... When they say you can't do this, they mean you can't do this. You can explore more, for instance changing the class to:
class Person {
    let name = "Alice"
}

And you'll find you have all the same problems. You cannot assign to a let constant in a superclass from a method introduced in a subclass.

A: You are not modifying existing constants in your code - only creating new instances of your class.  If you want to see an error to prove it, try this:
let constanttest = ConstantTest(constant: "Hello")
constanttest.constant = "World" //Will not compile because "constant" is a constant

As an example for the bit about it not being able to be modified by a subclass:
class ConstantTest {

    let constant: String //<--- This is the constant you are unable to change
    init(constant: String) {
        self.constant = constant
    }

    func printConstant() {
        print(constant)
    }
}

let constantTest = ConstantTest(constant: "Hello")
constantTest.printConstant()
constantTest.constant = "World" //Will not compile

class SubConstClass: ConstantTest { }

let subTest = SubConstClass(constant: "hey")
subTest.printConstant()
subTest.constant = "Hi" //Will not compile (same as superclass)

In case you are confused about the instantiation of these classes, here is another simple example of var and let using String:
let constantString = "constant"
var mutableString = "mutable"

constantString = "oops" //Will not compile
mutableString = "changed" //Totally fine, since this is a var

A: I just think the other answer haven't understood your confusion. , though creeperspeak commented you here. You seem not to understand the difference between a class and its instances:
See here and here
And then the examples below:
let constanttest1 = ConstantTest(constant: "Hello") // This is an INSTANCE of ConstantTest class
let constanttest2 = ConstantTest(constant: "Hi") // ANOTHHER INSTANCE
let constanttest3 = ConstantTest(constant: "Bye") // another instance
let constanttest4 = ConstantTest(constant: "ByeBye") // another instance

var subTest = SubConstClass(constant: "hey") // This is an an instance of SubConstClass
var subTest2 = SubConstClass(constant: "heyhey") // This is an an instance of SubConstClass
var subTest3 = SubConstClass(constant: "HaHaHa") // This is an an instance of SubConstClass.

None of the instances conflict with each other.

redpajama_set_name: RedPajamaStackExchange


text:
Q: noob mac user - developer directory conventions I just got a Mac Mini OS X Server. This is my first foray into the Mac world. Wanting to get off on the right foot as I configure my machine, which will be used principally for software development (java, groovy, grails, javascript, etc.), I am wondering what conventions are typically followed as you install software tools, locate your projects, etc. I have tried googling this question, using a variety of search terms, but none of the pages comes up with answers near to what it is I am asking. I am not asking about where tools that come with an installer (an image, as I understand it). No, my first question is about installing things like tomcat, mysql, or similar, things that need me to intervene and select a location.
My second question, then, is: where do I place my projects that I am developing? I am thinking that these should probably go to a subdirectory of my home directory, one called projects, perhaps?
Is there anything else I should know as I go about configuring my Mac for development? Are there tools/utilities that I should install that are unique to the Mac world (in other words, don't suggest tools like Firefox plugins that I would have likely used on a PC)?
Thanks!

A: The main thing is to stick to the 'site local' areas; /usr/local/* and /Library/*. Of course anything under a user's home is perfectly safe as well. Doing this should keep you out of trouble with respect to software updates from Apple. Sometimes you need some environment variable changes to allow your software to pick up e.g. additional $PATH elements.
Regarding useful tools, I like the package manager Mac Ports. It's often a fast way to fill out a dependency chain or experiment with various software packages.


text:
Q: In C++11 threads, what guarantees does a std::mutex have about memory visibility? I am currently trying to learn the C++11 threading api, and I am finding that the various resources don't provide an essential piece of information: how the CPU cache is handled. Modern CPUs have a cache for each core (meaning different threads may use a different cache). This means that it is possible for one thread to write a value to memory, and for another thread to not see it, even if it sees other changes the first thread also made.
Of course, any good threading API provides some way to solve this. In C++'s threading api, however, it is not clear how this works. I know that a std::mutex, for example, protects memory somehow, but it isn't clear what it does: does it clear the entire CPU cache, does it clear just the objects accessed inside the mutex from the current thread's cache, or something else?
Also, apparently, read-only access does not require a mutex, but if thread 1, and only thread 1, is continually writing to memory to modify an object, won't other threads potentiality see an outdated version of that object, thus making some sort of cache clearing necessary?
Do the atomic types simply bypass the cache and read the value from main memory using a single CPU instruction? Do they make any guarantees about the other places in memory being accessed?
How does memory access in C++11's threading api work, in the context of CPU caches?
Some questions, such as this one talk about memory fences, and a memory model, but no source seems to explain this in the context of CPU caches, which is what this question asks for.

A: std::mutex has release-acquire memory ordering semantics, so everything in thread A that happened-before the atomic write to the critical section from thread A's point of view must be visible to thread B before entering the critical section in thread B.
Have a read of http://en.cppreference.com/w/cpp/atomic/memory_order to get started. Another good resource is the book C++ Concurrency in Action. Having said this, when using the high level synchronization primitives, you should be able to be able to get away with ignoring most of these details unless you are curious or want to get your hands dirty.

A: I think I understand what you are getting at. There are three things at play here.

*

*The C++11 standard describes what happens at the language level... locking a std::mutex is a synchronization operation. The C++ standard does not describe how this works. CPU caches do not exist as far as the C++ standard is concerned.

*The C++ implementation, at some point, puts some machine code in your application that implements a mutex lock. The engineers creating this implementation must take into account both the C++11 spec and the architecture spec.

*The CPU itself manages the cache in such a way that to provide the semantics necessary for the C++ implementation to work.
This may be easier to understand if you look at atomics, which translate to much smaller snippets of assembly code but still provide synchronization. For example, try this one on GodBolt:
#include <atomic>

std::atomic<int> value;

int acquire() {
    return value.store(std::memory_order_acquire);
}

void release() {
    value.store(0, std::memory_order_release);
}

You can see the assembly:
acquire():
  mov eax, DWORD PTR value[rip]
  ret
release():
  mov DWORD PTR value[rip], 0
  ret
value:
  .zero 4

So on x86, there's nothing necessary, the CPU already provides the required memory ordering semantics (although you can use an explicit mfence it's usually implied by the operations). This is definitely not how it works on all processors, see the Power output:
acquire():
.LCF0:
0: addis 2,12,.TOC.-.LCF0@ha
  addi 2,2,.TOC.-.LCF0@l
  addis 3,2,.LANCHOR0@toc@ha # gpr load fusion, type int
  lwz 3,.LANCHOR0@toc@l(3)
  cmpw 7,3,3
  bne- 7,$+4
  isync
  extsw 3,3
  blr
  .long 0
  .byte 0,9,0,0,0,0,0,0
release():
.LCF1:
0: addis 2,12,.TOC.-.LCF1@ha
  addi 2,2,.TOC.-.LCF1@l
  lwsync
  li 9,0
  addis 10,2,.LANCHOR0@toc@ha
  stw 9,.LANCHOR0@toc@l(10)
  blr
  .long 0
  .byte 0,9,0,0,0,0,0,0
value:
  .zero 4

In here there are explicit isync instructions because the Power memory model provides fewer guarantees without them.
This is just punting things down to a lower level, however. The CPU itself manages shared caches using a technique like the MESI Protocol, which is a technique for maintaining cache coherence.
In the MESI protocol, when a core modifies a block of cache, it must flush that block from other caches. Other cores mark the block invalid, writing the contents out to main memory if necessary. This is inefficient, but necessary. For this reason you don't want to try and shove a bunch of commonly used mutexes or atomic variables in a small region of memory, because you can end up with multiple cores fighting over the same block of cache. The Wikipedia article is fairly comprehensive and has more detail than I'm writing here.
Something I'm omitting is the fact that mutexes typically require some kind of kernel-level support in order for threads to go to sleep or wake up.


text:
Q: Windows Phone 7 Streaming Audio Basic Authentication I am trying to play a password protected Icecast stream from Windows Phone Application.
        UriBuilder station = new UriBuilder();
        station.Host="myhost";
        station.Port=80;
        station.Password = "password";
        station.UserName = "user";
        station.Path = "path";
        station.Scheme = "http";

        Uri stationUrl = station.Uri;
        Debug.WriteLine(stationUrl);
        BackgroundAudioPlayer.Instance.Track = new AudioTrack(stationUrl, "asd", "abc", "asd", null);
        BackgroundAudioPlayer.Instance.Play();

I even tried using
BackgroundAudioPlayer.Instance.Track = new AudioTrack(new Uri("http://user:password@host:port/path", UriKind.Absolute), "abc", "as", "de", null);

It could not play. But when I remove username and password it can play.
Authentication is taking place using a PHP file. When I checked the authentication results by printing the $_POST values, they were blank. The same URL works in VLC, Firefox not in IE though.
Is there any way I can make it work?


text:
Q: problema com uppercase no django Estou com problema de uppercase no django, no codigo a seguir, funciona no primeiro form (nome) e no ultimo form (orgao), porem nos forms intermediarios nao transforma em maiusculas as letras enviadas no banco...
models.py
class Requerente(models.Model):
NACIONALIDADE = (
    ('BRASILEIRO', 'BRASILEIRO'),
    ('BRASILEIRA', 'BRASILEIRA'),
    ('ESTRANGEIRO', 'ESTRANGEIRO'),
    ('ESTRANGEIRA', 'ESTRANGEIRA'),
    )
ESTADO_CIVIL = (
    ('CASADO', 'CASADO'),
    ('CASADA', 'CASADA'),
    ('SOLTEIRO', 'SOLTEIRO'),
    ('SOLTEIRA', 'SOLTEIRA'),
    ('DIVORCIADO', 'DIVORCIADO'),
    ('DIVORCIADA', 'DIVORCIADA'),
    ('VIÚVO', 'VIÚVO'),
    ('VIÚVA', 'VIÚVA'),
)
REGIME = (
    ('COMUNHAO DE BENS', 'COMUNHAO DE BENS'),
    ('COMUNHAO PARCIAL DE BENS', 'COMUNHAO PARCIAL DE BENS'),
    ('SEPARAÇÃO DE BENS', 'SEPARACAO DE BENS'),
    )
nome = models.CharField(max_length=100)
nacionalidade = models.CharField(choices=NACIONALIDADE, max_length=50, null=True)
estado_civil = models.CharField(u'estado civil', max_length=50, choices=ESTADO_CIVIL, null=True)
nubente = models.CharField(max_length=100, null=True)
regime = models.CharField(u'regime', max_length=50, choices=REGIME, blank=True, null=True)
profissao = models.CharField(max_length=50, null=True)
rg = models.CharField(max_length=100, null=True)
orgao = models.CharField(max_length=50, null=True)
cpf = models.CharField(max_length=14, )
logradouro = models.ForeignKey(Logradouro, verbose_name=u'Rua, Av.')
numero = models.CharField(max_length=50, )
bairro = models.ForeignKey(Bairro, )
cidade = models.ForeignKey(Cidade)
telefone = models.CharField(max_length=20, blank=True, null=True)
celular =  models.CharField(max_length=20, blank=True, null=True)

def __unicode__(self):
    return self.nome
def save(self, force_insert=False, force_update=False):
    self.nome = self.nome.upper()
    super(Requerente, self).save(force_insert, force_update)

def save(self, force_insert=False, force_update=False):
    self.nubente = self.nubente.upper()
    super(Requerente, self).save(force_insert, force_update)

def save(self, force_insert=False, force_update=False):
    self.profissao = self.profissao.upper()
    super(Requerente, self).save(force_insert, force_update)

def save(self, force_insert=False, force_update=False):
    self.orgao = self.orgao.upper()
    super(Requerente, self).save(force_insert, force_update)

A: Por que você não tenta usar somente um save e ir tratando esses fields nesse save?
Aqui está uma possível solução, usando um único save para tratar os fields:
def save(self, *args, **kwargs):
    self.nubente = self.nubente.upper()
    self.profissao = self.profissao.upper()
    self.orgao = self.orgao.upper()

    super(Requerente,self).save(*args,**kwargs)

Coloque esse único save no seu Model e tente executar novamente.

A: Caso queria, você também pode usar a função clean no models.py para não ter que sobrescrever a função save.
    class Requerente(models.Model):

        nacionalidade = models.CharField(choices=NACIONALIDADE, max_length=50, null=True)

        def clean(self):
            self.nacionalidade = str(self.nacionalidade.upper())

Assim a gravação e recuperação do banco sempre será em maiúsculo.


text:
Q: Find the nearest point on a line I have a line that exists between two latlon positions, and a point on a certain latlon position. What I want to know is what the nearest point on that line is (in respect to the other point). So a latlon position on that line.
I know how to do the basic math, but I just can't get my head around the latlong calculation. Can anyone help me or give me some pointers on how to do it?
Thanks

A: This is the code I made using a Vector3 type. Isn't exactly spot on but close enough for further calculations:
    public static LatLon GetOrthographicProjecten(LatLon start, LatLon end, LatLon offsetpoint)
    {
        #region Start node conversion

        var sLat = DegreesToRadians(start.Lat);
        var sLon = DegreesToRadians(start.Lon);

        var sX = EarthRadius * Math.Cos(sLat) * Math.Cos(sLon);
        var sY = EarthRadius * Math.Cos(sLat) * Math.Sin(sLon);
        var sZ = EarthRadius * Math.Sin(sLat);

        #endregion

        #region End node conversion

        var eLat = DegreesToRadians(end.Lat);
        var eLon = DegreesToRadians(end.Lon);

        var eX = EarthRadius * Math.Cos(eLat) * Math.Cos(eLon);
        var eY = EarthRadius * Math.Cos(eLat) * Math.Sin(eLon);
        var eZ = EarthRadius * Math.Sin(eLat);

        #endregion

        #region Offsetpoint conversion

        var oLat = DegreesToRadians(offsetpoint.Lat);
        var oLon = DegreesToRadians(offsetpoint.Lon);

        var oX = EarthRadius * Math.Cos(oLat) * Math.Cos(oLon);
        var oY = EarthRadius * Math.Cos(oLat) * Math.Sin(oLon);
        var oZ = EarthRadius * Math.Sin(oLat);

        #endregion

        // Create vectors
        var p1 = new Vector3(sX, sY, sZ);
        var p2 = new Vector3(eX, eY, eZ);
        var o = new Vector3(oX, oY, oZ);

        // Calculate
        var u = p2 - p1;
        var po = o - p1;
        var w2 = po - (u * Vector3.DotProduct(po, u) / Math.Pow(u.Magnitude, 2));
        var point = o - w2;

        // Convert to latlon
        var rlat = RadiansToDegrees(Math.Asin(point.Z / EarthRadius));
        var rlon = RadiansToDegrees(Math.Atan2(point.Y, point.X));

        return new LatLon(rlat, rlon);
    }


text:
Q: CUploadedFile::getInstance Always Returns Null on Uploaded File I have built a form in YII and I need to process an uploaded file. I followed this guide, but I've stumbled upon an issue. CUploadedFile::getInstance always returns null.
Here's what I use. My model:
class AdditionalFieldFile extends CFormModel {

    public $uploadedFile;

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        return array(
            //note you wont need a safe rule here
            array('uploadedFile', 'file', 'allowEmpty' => true, 'types' => 'zip,doc,xls,ppt,jpg,gif,png,txt,docx,pptx,xlsx,pdf,csv,bmp'),
        );
    }

}

And handling the uploaded file in the controller on form submit:
$model = new AdditionalFieldFile();
$model->uploadedFile = CUploadedFile::getInstance($model, 'field_'.$type_field.'['.$id_common.']');

And after that $model->uploadedFile is null for some reason.
Note that $type_field and $id_common come dynamically.
Also, the form has 'enctype'=>'multipart/form-data' so this is not the cause.

A: Ok, a self-answer follows.
It turns out that I had to use the active file field in the view, using an instance of the class that extends CFormModel as a model.
Solution:
CHtml::activeFileField(new AdditionalFieldFile(), 'field_'.$type_field.'['.$id_common.']');


text:
Q: Are free Artinian modules finitely generated? I think the answer is yes. Let $M$ be the Artinian free $R$-module.
Proof. Let $S$ be a basis of the free $R$-module M. On the contrary, if $S$ were infinite, then we could pick an infinite sequence of pairwise distinct elements from $S,$ e.g., $s_1, s_2,$ etc.
From this, we have the strictly decreasing sequence of $R$-submodules $M_1 \supsetneq M_2 \supsetneq \cdots,$ where $M_i = R \langle s_j \,|\, j \geq i \rangle.$ However, this contradicts the assumption that $M$ is Artinian.
Is the proof valid? If so, can we then conclude that Artinian vector spaces are finitely generated?


text:
Q: Rail and railing (difference)
*

*Hold on to the rail.

*Hold on to the railing.

What's the difference between rail and railing?

A: When used as a noun, in your example, both rail and railing has no significant difference.

rail (noun)

*

*a bar of wood or metal fixed horizontally for any of various purposes, as for a support, barrier, fence, or railing.

*a fence; railing.

  (there are 5 other definitions too)
railing (noun)

*

*a fencelike barrier composed of one or more horizontal rails supported by widely spaced uprights; balustrade.

*banister.

*rails collectively.

By definition, a rail is an integral part of a railing. But there is also a definition that implies rail can be used to mean railing too. They are used interchangeably under the given context.


text:
Q: Since v3.0 Facebook Graph API group-id/feed endpoint always returns empty array I have a small FB app which were retrieving posts from a group where I am an admin. It was working fine for ages, but with the latest changes in v3.0 of the Graph API, it is broken, and I totally don't understand why.
My access token has groups_access_member_info,user_managed_groups permission and I able to see my SECRET group in the list GET /v3.0/me/groups
However, when I try to retrieve the feed GET /v3.0/<group-id>/feed the empty list is returned.
I also tried to do it for the CLOSED group and the result is the same.
What happened? Is it FB bug? Did anybody managed to retrieve feed from a group?
Any suggestions are welcome!
Thanks!

A: I'm have the same question as well. Facebook and others keep telling us to use our own app, but we just use Graph API explorer to download group posts. We are a university study research group, not a startup or a company so we don't have our own app to give people.

A: Your app must be be approved for the Groups API feature.
The Groups API is a collection of Graph API endpoints that let you read and create Facebook Group data on behalf of group members.


text:
Q: Upgrade Apache from source if the original was installed from an rpm? (migrated from stackoverflow.com)
Recently I've inherited a set of machines running Red Hat Enterprise Linux 5.4. They have been provisioned with Apache Server v2.2.3 installed from rpms. I need to upgrade Apache to v2.2.19. For various reasons I'm building Apache from source. Installing my new version of Apache is no problem but then I have two instances of Apache, v2.2.3 at /usr/sbin/httpd and v2.2.19 at /usr/local/sbin/httpd. In most cases I'd just remove the existing version of Apache with rpm -e, but there are a ton of other rpms that have Apache as a dependency. I can't seem to find an rpm of Apache 2.2.19 for REL 5.4, so I can't do an rpm --upgrade. If I build Apache 2.2.19 with the prefix of the existing Apache instance (/usr/sbin/httpd), the install fails because /usr/sbin/httpd already exists. I've explored using yum to upgrade the packages but the server is behind a firewall and can't see the outside world.
At this point I'm leaning towards creating my own rpm but that seems like a lot of extra work for a seemingly small task. It seems like there's something really basic I'm not getting.

A: You really, really want to create an RPM.  You shouldn't have to do it from scratch; there'll be any number of existing packages out there you can use (or at least use as a base) -- including the existing RPM package.
Installing from source in a package-managed environment is just asking for trouble, from anyone who has to administer the server in the future or even just you when in 3 years you forget what horror you've wrought.

A: I tend to use packages provided by the distribution, but if I for any reason need to compile something like Apache from source, I make sure I

*

*install it to separate path (such as /usr/local/apache2 or /opt/apache2

*create my own init scripts for them (such as /etc/init.d/apache2_custom) - messing up with the scripts provided by distribution will bite you sooner or later

*update /etc/motd and other documentation to clearly state the fact that this server uses self-compiled package FOO

A: Move your old httpd binary out of the way then install.
mv /usr/sbin/httpd /usr/sbin/httpd.old -v,  set your --prefix=/usr/sbin  for Apache ./configure, then install.  Make sure to back up your Apache config files, first.  (tar czpf /etc/httpd-backup-$(date +%s).tar.gz /etc/httpd/ )

A: While it may lead you into a slippery slope of dependency removal you should check which packages require httpd to be installed.
# rpm -q --whatrequires httpd

If you can remove the packages than you might have your answer, if you can't remove apache due to dependencies and you absolutely must run the newer version than I would suggest turning off the rpm version of httpd and stop it from starting on boot.
# service httpd stop
# chkconfig httpd off

I would suggest then installing your custom compiled version and run it out of another directory for configuration/binaries. If you go that route it would also be wise to copy the default init script, modify the paths and add it as a different name.
# chkconfig --add httpd-custom
# chkconfig httpd-custom on

Keep in mind if you are using Redhat support they wont help you with the custom compiled version of httpd, and they really would not support you if you messed with the original binaries.


text:
Q: Светлана составляет коды из букв своего имени. Код должен состоять из 8 букв, Светлана составляет коды из букв своего имени. Код должен состоять из 8 букв, и каждая буква в нём должна встречаться столько же раз, сколько в имени Светлана. Кроме того, одинаковые буквы в коде не должны стоять рядом. Сколько кодов может составить Светлана? ОТВЕТ 15120. ЧТО НЕ ТАК?
k=0
for x1 in 'СВЕТЛАНА':
  for x2 in 'СВЕТЛАНА':
    for x3 in 'СВЕТЛАНА':
      for x4 in 'СВЕТЛАНА':
        for x5 in 'СВЕТЛАНА':
          for x6 in 'СВЕТЛАНА':
            for x7 in 'СВЕТЛАНА':
              for x8 in 'СВЕТЛАНА':
                s=x1+x2+x3+x4+x5+x6+x7+x8
                  if s.count('А') == 2 \
                     and s.count('С') == 1 \
                     and s.count('В') == 1 \
                     and s.count('Е') == 1 \
                     and s.count('Т') == 1 \
                     and s.count('Л') == 1 \
                     and s.count('Н') == 1 \
                     and s.count('АА') == 0:
                    k=k+1
print(k)

A: Давайте посмотрим задачу с другой стороны. Пусть у нас восемь разных букв. Сколько можно сделать перестановок? 8!. Теперь из этих восьми букв две одинаковые. Сколько тогда разных перестановок? 8! / 2, потому что теперь все мы не различаем пары перестановок в которых две одинаковые буквы на одних и тех местах:

светланA, светлAна - если мы различаем буквы аА,
    \        /       это две разные перестановки
     \      /
     светлана      - если буквы а неразличимы, перестановка одна

Сколько перестановок в которых две буквы а рядом? Каждая такая перестановка соответствует перестановке из семи различных букв, потому что:

светлаан <-> светлан

Таких перестановок 7!.
Из числа всех перестановок вычтем плохие:

8! / 2 - 7! = 8 * 7! / 2 - 7! = 3 * 7! =
= 3 * 1 * 2 * 3 * 4 * 5 * 6 * 7 = 3 * 120 * 6 * 7 = 720 * 21 =
= 14400 + 720 = 15120

A: В комментариях к другому ответу писал, вот что я имею в виду
from itertools import permutations

a = list("светлана")
temp = permutations(a, 8)
b = set(["".join(i) for i in list(temp)])

counter = 0
for i in b:
    if "аа" not in i:
        counter += 1
print(counter)

вывод
15120

A: Анна, вот вам код, исправленный тем же подходом, что и у вас применён.
Исключено повторение последовательностей. Теперь результат 15120.
Подсказка: вы могли сам это обнаружить, упростив пример до слова "AСA", например, и прогнав в отладчике или на бумажке (что я и сделал:-).
used=[]
k=0
for x1 in 'СВЕТЛАНА':
  for x2 in 'СВЕТЛАНА':
    for x3 in 'СВЕТЛАНА':
      for x4 in 'СВЕТЛАНА':
        for x5 in 'СВЕТЛАНА':
          for x6 in 'СВЕТЛАНА':
            for x7 in 'СВЕТЛАНА':
              for x8 in 'СВЕТЛАНА':
                s=x1+x2+x3+x4+x5+x6+x7+x8
                  if s.count('А') == 2 \
                     and s.count('С') == 1 \
                     and s.count('В') == 1 \
                     and s.count('Е') == 1 \
                     and s.count('Т') == 1 \
                     and s.count('Л') == 1 \
                     and s.count('Н') == 1 \
                     and s.count('АА') == 0 \
                     and s not in used:
                    k=k+1
                    used.append(s)
print(k)

A: Вместо того, чтобы решать это задание из егэ миллионами циклов, лучше ознакомьтесь с библиотекой itertools https://habr.com/ru/company/otus/blog/529356/. Методов для егэ там - уйма, просто прочитайте статью и потренируйтесь их юзать. Касаемо вашего задания - используйте функцию permutations из модуля itertools. Вот код:
from itertools import permutations

count = 0
for variant in permutations("СВЕТЛАНА", 8):
    if "АА" not in "".join(variant):
        count += 1

print(count / 2)

A: Советую использовать библиотеку itertools и её функцию product, так код будет выглядеть намного лучше:
from itertools import product

def f(n: str):
    return 'АА' not in n and n.count('А') == 2 \
           and n.count('С') \
           and n.count('В') \
           and n.count('Е') \
           and n.count('Т') \
           and n.count('Л') \
           and n.count('Н')

print(sum(map(lambda x: f("".join(x)), product("СВЕТЛАН", repeat=8))))  # Имя подавать без дубликатов букв
print(sum(map(lambda x: f(''.join(x)), set(permutations("СВЕТЛАНА", r=8))))) # Второй вариант решения

Вывод
15120
15120

Данный код применим к любому имени, главное менять функцию проверки, в зависимости от условия. И само имя поданное в функцию.


text:
Q: How to call title attribute enable from screen options in wordpress? enter code hereI have adding title with menu from screen options in wordpress. Trying to call title dynamic in wordpress but not getting any solutions.
html code :

* Home
Wp dynamic code :
wp_list_pages(array( 'title_li'=>'','include'=> array( 5 )));

A: Wordpress has a function named get_current_screen you can use it like this :
$screen = get_current_screen();
$option = $screen->get_option('name_of_your_option', 'option');


text:
Q: How to deserialize an class into different class (in new namespace) using BinaryFormatter (C#) I have a class User belong to Authentication namespace, as below:
namespace Authentication {
    public class User
    {
       public string Name {get;set;}
    }
}

I serialized an object of class User  using BinaryFormatter into byte[ ] and store it in database.
User usr = new User();
usr.Name = "myself";
var usrValue = convertObjectToByteArr(usr);
//then store usrValue into db.

After some time, class User has new property and moved to new namespace: Authentication.Organization
namespace Authentication.Organization{
    public class User
    {
        public string Name {get;set;}

        public int Age {get;set;}
    }
}

My question: How do I de-serialize the object of previous User into current User ?
I'll hit exception: {"Unable to load type Authentication.User required for deserialization."} when I try to deserialize it:
byte[] prevUsrValue= (byte[])helper.getPreviousUserValue();//read from database

User previousUser = convertByteArrToObject(prevUsrValue) as User;

FYI, I am using these method to serialized and de-serialize:
//serialization
public static byte[] convertObjectToByteArr(object o)
{
    if (o != null)
    {
        System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        binaryFormatter.Serialize(memoryStream, o);
        return memoryStream.ToArray();
    }
    return null;
}

//de-serialization
public static object convertByteArrToObject(byte[] b)
{
    if (b != null && b.Length > 0)
    {
        System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(b);
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        memoryStream.Position = 0;
        return binaryFormatter.Deserialize(memoryStream);

    }
    return null;
}

A: Do not store binary serialized objects in the database. Serialize user as its properties into tables, using your ORM of choice (EF, Linq2SQL, NHibernate etc).
Serializing binary objects into database is incredibly bad. Databases are long lived and queryable. You are negating both in one stroke: your long lived data can onyl be deserialized by the very specific code you have now (20 years from now someone will have to run C# v. 4.5 to desrialize your objects stored today) and the binary serialized object is nothing but an opaque blob to the database, unqueryable and unsearchable.
Don't do it.

A: I would make the case that there are some valid cases for storing binary data in a database.  For example, in our commercial product, the database is used to store data internally, so we use a binary serialized form to make it intentionally unqueryable and unsearchable.  We include an indexed key column along with the binary data column for lookup, but beyond that the data is unrecognizable.
There is an added benefit that the binary serialized data takes less storage space than if we created a column for every field in the object.
We use version tolerant serialization (VTS) to address the updated code issue, but not sure this helps with the original post where the namespace has changed.


text:
Q: How should merge 2 element of array in PHP? I want to merge 2 element in array in PHP how can i do that. Please any on tell me.
$arr = array('Hello','World!','Beautiful','Day!');  // these is my input

//i want output like

array('Hello World!','Beautiful Day!');

A: Specific to that case, it'd be very simple:
$result = array($arr[0].' '.$arr[1], $arr[2].' '.$arr[3]);

A more general approach would be
$result = array();
for ($i = 0; $i < count($arr); $i += 2) {
    if (isset($arr[$i+1])) {
        $result[] = $arr[$i] . ' ' . $arr[$i+1];
    }
    else {
        $result[] = $arr[$i];
    }
}

A: The generic solution would be something like this:
$result = array_map(function($pair) {
    return join(' ', $pair);
}, array_chunk($arr, 2));

It joins together words in pairs, so 1st and 2nd, 3rd and 4th, etc.

A: In case your array is not fixed to 4 elements
$arr = array();
$i = 0;
foreach($array as $v){
  if (($i++) % 2==0)
    $arr[]=$v.' ';
  else {
    $arr[count($arr)-1].=$v;
  }
}

Live: http://ideone.com/VUixMS

A: Presuming you dont know the total number of elements, but do know they will always an even number (else you cant join the last element), you can simply iterate $arr in steps of 2:
$count = count($arr);
$out=[];
for($i=0; $i<$count; $i+=2;){
    $out[] = $arr[$i] . ' ' .$arr[$i+1];
}
var_dump($out);

A: Here it is:
$arr = array('Hello', 'World!', 'Beautiful', 'Day!');
$result = array();
foreach ($arr as $key => $value) {
  if (($key % 2 == 0) && (isset($arr[$key + 1]))) {
    $result[] = $value . " " . $arr[$key + 1];
  }
}
print_r($result);

A: A easy solution would be:
$new_arr=array($arr[0]." ".$arr[1], $arr[2]." ".$arr[3]);


text:
Q: Swiper-Slide-Active class when Swiper is multirow I have Swiper set to show 2 rows per column, but when I do this then the Swiper-Slide-Active class are not properly set, i.e. this class is not applied to the slides (2) that are shown in the center of the swiper.
Any idea what am i doing wrong here?, settings for the swiper below:
var swiper = new Swiper('.swiper-container', {
                pagination: '.swiper-pagination',
                effect: 'coverflow',
                grabCursor: true,
                centeredSlides: true,
                slidesPerView: 'auto',
                slidesPerColumn: 2,
                spaceBetween: 20,
                simulateTouch: true,
                centeredSlides:true,
                slideToClickedSlide: true,
                paginationClickable:true,
                grabCursor:true,
                coverflow: {
                    rotate: 45,
                    stretch: 0,
                    depth: 100,
                    modifier: 1,
                    slideShadows: false
                }
            });

A: Currently, multirow Swiper is not compatible with slidesPerView:'auto', so if it is possible for your layout, switch slidesPerView to some fixed value


text:
Q: Strange (for me) declaration of function What that declaration means in C ?
void help_me (char *, char *);

I'm newbie, but I know about pointers. Seems like this is something different ?

A: This declaration says that help_me is a function taking two pointers to char (for example, two strings).
For a function prototype declaration the variable names are optional: void help_me (char *, char *); and void help_me (char * foo, char * bar); are equivalent.

A: It's a prototype for a function. It doesn't give the argument names because it isn't strictly require in a prototype.
Here it is declaring that there exists a function, help_me that takes 2 arguments both of type char * and returns nothing.

A: It's a prototype, and in a prototype only the type of arguments are needed, i..e you don't need to state something like:
void help_me (char* a_char, char* another_char);


text:
Q: Does Apple Reject applications that use a lot of bandwidth? I've heard reports that Apple will reject applications that use excessive amounts of bandwidth.  The number that I've heard is a maximum of 1MB/minute of bandwidth usage.  Although I've seen this number on various boards, I haven't been able to find an explicit statement from Apple's guidelines that speak to this.
I'm looking to stream video to an application and want to know what the maximum encoding rate of the videos should be.
Does anyone know what the exact number is?  Is it documented somewhere?

A: There is no published limit, I believe Apple leaves themselves some room to make a judgement about individual apps.
Keep in mind that you'll probably need to limit the bandwidth you use over cell anyways, since Edge is rather slow.  There is no limit on WiFi.

A: I do not know of any specification regarding this topic. But yes, Apple will reject Applications which use a lot of bandwidth. You can restrict your application to WiFi only, then bandwidth usage is not a problem to Apple anymore. They have contracts with the mobile network operators to restrict the bandwith within their networks.

A: 1 mb/minute tested over five minutes seems to be the test.
Please see this other question for advice on this:
iPhone app rejected for "transferring excessive volumes of data"
This is also confirmed by Brian Stormont:
http://blog.stormyprods.com/2009/04/avoiding-iphone-app-rejection-from.html


text:
Q: Inertia.js child component props/data? Taking pingcrm as an example, can a child component receive data from its corresponding controller and not only the route controller?
For example, we have the routes:
Route::get('/', [DashboardController::class, 'index'])
    ->name('dashboard')
    ->middleware('auth')

Route::get('contacts', [ContactsController::class, 'index'])
    ->name('contacts')
    ->middleware('remember', 'auth')

If I embed <Contacts /> as a child component of the Dashboard, it doesn't receive any data from ContactsController.
Coming from a Vue background where I would ensure a component has the appropriate data inside the component itself for re-usability (e.g. a contacts table <ContactsTable /> that appears multiple times at different routes throughout the app), is this possible with Inertia.Js?
There is shared data but that doesn't seem ideal for most use cases and the documentation explicitly warns to use this sparingly as it is sent on every response.
What confuses me is that the controllers seem to be route bound rather than component bound, unless I am misunderstanding something?


text:
Q: Javascript confusion for scope of 'this' inside closure function I tried below function to understand this keyword scope global/private.
I understood it 97%. but got stuck in confusion over the output of x.private_fa() which returns a private function but not the private value inside it.

a = 1.1;
b = 2.1;
c = 3.1;

function fa() {
  return "Global fa()";
}

function f() {
  var a = 1;
  this.b = 2;

  function fa() {
    return this.b; // or this.a not working..!
    //return b // 2.2
    //return a // 1
  }

  return {
    private_a: a, // 1
    global_a: window.a, // 1.1
    private_b: this.b, // 2
    global_b: b, // 2.1
    private_fax: fa(), // 2.1
    private_fa: fa, // function private fa()
    global_fa: window.fa(), // Global fa()
    global_c: c, // 3.1
    private_c: this.c // 3
  };
}

try {

  f.prototype.c = 3;

  var x = new f();

  f.prototype.c = 4;

  console.log("x:", x);

  /*??? Please explain this.. ??? */
  console.log("x.private_fa():", x.private_fa());

  console.log(x.private_c);
  var x1 = new f();
  console.log(x1.private_c);

  console.log(" - End - ");
} catch (e) {
  console.error("Error: ", e.message);
}

A: In the code you posted, a call to x.private_fa() returns undefined, just because the object x hasn't a b member (and fa returns this.b).
If you want it to return that value let your object's private_fa return a bound version of the "private" fa():
var bound_fa = fa.bind(this);

return {
    private_a: a, // 1
    global_a: window.a, // 1.1
    private_b: this.b, // 2
    global_b: window.b, // 2.1
    private_fax: fa(), // 2.1
    private_fa: bound_fa, // function private fa()
    global_fa: window.fa(), // Global fa()
    global_c: window.c, // 3.1
    private_c: this.c // 3
};

In bound_fa function, this will be forever tied to f() context (where the desired variable b belongs).
This reading could clarify the this enigma further: https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch1.md


text:
Q: Can GPL v2 code link to an LGPL v3 library If I write a library that is released under the terms of the GPL v2 (or higher, at option); may that library depend on another library released under the LGPL v3 (or higher), without implicitly enforcing GPL v3. That is, I am purely linking to that library.
Reading this and this, I understand that the LGPL v3 and GPL v2 are not "compatible". But it is not clear to me, whether compatibility means only mixing of code, or whether it extends to the linking (without modifying the LGPL'ed library).

A: According to the License compatibility matrix from GNU, if you link your GPLv2 (or later) software with an LGPLv3 library, the effective license for the product becomes GPLv3.
The copyleft nature of the GPL licenses means that everything your software depends on must be available under the same terms as the part that actually carries the GPL license. That includes libraries you link to (with an explicit exception for major OS components and standard libraries).
The code doesn't have to be all licensed under the GPL, but the GPL does require that you have the freedom to modify all parts of an application that contains GPL code and that you have the freedom to distribute the application with or without modifications.

What it means for a license X to be compatible with the GPL is that the license X gives you, the user, at least as much freedom as the GPL does, so that in a product that contains both GPL code and code that uses license X, the distribution of that product doesn't violate any terms and conditions of either license.
GPLv3 and GPLv2 are not compatible with each other, because GPLv3 has put additional requirements in place, which is not allowed under GPLv2. This is also the reason why a combination of GPLv2 (or later) and LGPLv3 effectively 'upgrades' the GPLv2 code to GPLv3, which is possible under the "or later" permission.

A: I don't have enough rep to comment on Bart's excellent answer, but I thought it worth mentioning that some notable open source libraries dual license under the GPL and LGPL specifically to avoid such issues.
For example, Qt is available under GPLv2, GPLv3 or LGPLv3 (or under a commercial license if you pay for it). This means you can link a GPLv2 program to Qt, even if the GPLv2 program does not grant the "or later" permission. By doing this, you would be opting to use Qt under the GPLv2 licensing terms. (You need to be careful though, as not all Qt modules are available under all licenses.)

If writing a library, you need to think carefully before releasing it under multiple licenses because your users only need to comply with one of them. This means that, if your library is GPLv2+/LGPLv3+, and someone creates a modified version and releases it under only one of those licenses, you cannot merge their changes back into your library without changing your library's license. (And you cannot change your library's license unless you get the permission from all of its contributors.)


text:
Q: Error in PHP mySQL query untraceable The following code is executing perfectly but there is a mySQL error somewhere that is producing an error message.
 $sql = mysql_query("UPDATE users SET password = $user_pwd WHERE email = '$user_email' AND authkey = '$user_authkey'");

 if(!mysql_query($sql,$config_connect))
 {
      echo $error .= 'The reset key did not match or has expired';
 }
 else
 {
      $approve = 1;
      $command .= '
Your password has been reset.
';
 }

The error:

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near '1' at line 1

A: I hope your using mysql_real_escape_string somewhere in the code. Also although not directly relating to the question the mysql extension is discouraged. If your not maintaining legacy code you should switch to PDO or mysqli.
I would rewrite it like this and then you can print $sql and run it yourself to get a better idea what's going wrong (note the quotes around password).
$sql = sprintf("UPDATE users SET `password`='%s' WHERE email='%s' AND authkey = '%s'", $user_pwd, $user_email, $user_authkey);
$result = mysql_query($sql,$config_connect);

if (!$result) {
    echo $error .= 'The reset key did not match or has expired';
} else {
    $approve = 1;
    $command .= '
Your password has been reset.
';
}

A: Password is a restricted keyword in MySQL, quote it in your query.
This:
$sql = mysql_query("UPDATE users SET password = $user_pwd WHERE email = '$user_email' AND authkey = '$user_authkey'");

Should be:
$sql = mysql_query("UPDATE users SET `password` = '$user_pwd' WHERE email = '$user_email' AND authkey = '$user_authkey'");

And unless you are passing quotes in your $user_pwd you need to quote that string in you query as well.
If at all possible change that field name in your database to save yourself some nightmarish debugging in the future.

A: You should quote $user_pwd : '$user_pwd'

A: perhaps i found it.
use apostrophs for $user_pwd > '$user_pwd'
i would try it on sql editor.

A: $sql = mysql_query("UPDATE users SET password = '$user_pwd' WHERE email = '$user_email' AND authkey = '$user_authkey'");

You should put $user_pwd in quotes, as password must be a string field, and query is trying to assign a integer value to this field, thats why syntax error is thrown. Try this modification.


text:
Q: What is a small tent kind of shop on the side of the road called? What is a small tent kind of shop on the side of the road called?
It can sell stuff like newspapers, snacks, coffee, and other small things. The only two things that come to mind are "a hot dog stand" and "street vendor" (though the latter is the person). So, I was wondering what other words for it may be?
In my language it's called a kiosk or simply a van, whether it's immovable or on the wheels, but from what I've googled, the pictures say it's not the same thing in English.
Here is what I want to know the name for:

A: I guess you could call it a vending cart or a street vending cart (you could even call it a mobile vending kiosk if you wanted). That is, it's a cart that's used for vending or selling things. If you go and do a quick search on Google, you will see that you're going to get a lot of hits with these phrases. So, these terms are very simple and actually used in the real world.

A: A Market Stall (or simply a stall) might be what you're looking for. This would be used to describe a tent-like structure, not something on wheels. Though the word Kiosk is also used (certainly in British English).
https://en.wikipedia.org/wiki/Market_stall

A: In the UK this might be known as a 'stand' or a 'van'.
A 'stand' as in a hotdog stand, although this would be applicable if the server was stood at ground level and the unit could be moved by hand.
A 'van' as in an ice-cream van, although this would not be an official definition found in the dictionary it is in common use.

A: pushcart
A type of cart with wheels that you manually push.
Dictionary.com says the term is primarily used in the US and in Canada

mainly US and Canadian a handcart, typically having two wheels and a canvas roof, used esp by street vendors.  Also called: barrow

Wikipedia suggests that it is typically known as a food cart

A food cart is a mobile kitchen set up on the street to prepare and sell street food to passers-by. Food carts are often found in cities worldwide selling food of every kind.
Food carts come in two basic styles.

*

*One allows the vendor to sit or stand inside and serve food through a window.

*In the other, the vendor stands next to the cart, while all the room in the cart is used for storage and to house the cooking machinery, usually a grilling surface.

*Some food carts are towed by another vehicle, while some are pushed by a human or animal.

It can also be simply called a food stall with wheels, or a vendor cart

A hot dog cart
If the food cart is part of a vehicle, it is called a foodtruck

A: The phrase market cart brings up some similar images in eBay. I think I've also seen this kind of stand called a "barrow", too. Collins list the following for "barrow":

chiefly Brit a handcart, typically having two wheels and a canvas roof, used esp by street vendors

Which neatly describes your images in a British fashion and gives "handcart" as an alternative.

A: It can be called
a BOOTH.
According to Merriam-Webster's Dictionary
https://www.merriam-webster.com/dictionary/booth:
: a stall or stand (as at a fair) for the sale or exhibition of goods.

A: I've tended to describe this sort of thing to others (and them describe it to me) as a kiosk. I've always been able to understand what they meant in any given case, and vice versa.


text:
Q: Generate all possible lists by replacing elements with 0 I would like to create from a list all the different list were 0,1,2,3...all element are replaced by an other
For example, if the replacement item is 0:
L=[1,2,3]
->[1,2,3],[0,2,3],[1,0,3],[1,2,0],[0,0,3],[0,2,0],[1,0,0],[0,0,0]

So far, I've tried I managed to do what I whant using Itertools but only in the case where 1 value is replaced by 0
Does anyone know how to do this ?

A: Everyone's trying too hard here.  We want each value to be either the original value or 0 -- we want pairs like (1,0), (2,0), and (3,0):
>>> from itertools import product, repeat
>>> L = [1, 2, 3]
>>> zip(L, repeat(0))
<zip object at 0x7f931ad1bf08>
>>> list(zip(L, repeat(0)))
[(1, 0), (2, 0), (3, 0)]

and then we can just pass that into product:
>>> list(product(*zip(L, repeat(0))))
[(1, 2, 3), (1, 2, 0), (1, 0, 3), (1, 0, 0), (0, 2, 3), (0, 2, 0), (0, 0, 3), (0, 0, 0)]

A: This is one way using itertools. The benefit of this method is that it is lazy.
A new list is produced on every __next__ call of the generator transformer.
Alternatively, as below, you can output all combinations by calling list on the generator function.
from itertools import combinations, chain

A = [1, 2, 3]

def transformer(x):
    idx = chain.from_iterable(combinations(range(len(x)), i) for i in range(len(x)+1))
    for indices in idx:
        y = x.copy()
        for j in indices:
            y[j] = 0
        yield y

res = list(transformer(A))

print(res)

[[1, 2, 3], [0, 2, 3], [1, 0, 3], [1, 2, 0], [0, 0, 3], [0, 2, 0], [1, 0, 0], [0, 0, 0]]

A: You can use recursion. First, create a function that can generate a full combinations for each index of the input:
def full_combinations(d, current = []):
   if len(d) == len(current):
     yield current
   else:
     yield current
     for i in range(len(d)):
        if len(set(current+[i])) == len(current)+1:
           yield from full_combinations(d, current+[i])

combination_list = list(full_combinations([1, 2, 3]))
new_results = [[0 if c in i else a for c, a in enumerate([1, 2, 3])] for i in combination_list]
full = [a for i, a in enumerate(new_results) if a not in new_results[:i]]

Output:
[[1, 2, 3], [0, 2, 3], [0, 0, 3], [0, 0, 0], [0, 2, 0], [1, 0, 3], [1, 0, 0], [1, 2, 0]]

A: It's not pretty, but I'm sure you can get this idea to work.
The idea is to use itertools.combinations to get all combinations of indices for every length, then we flatten this list with itertools.chain().
Then we loop through this list of lists, setting those indices to the replace character.
import itertools
l = [1,2,3]
replace = 0

indices = list(itertools.chain(*[list(itertools.combinations(list(range(len(l))),z+1)) for z in range(len(l))]))

allcombs = [[l]]
for i in indices:
    l2 = l[:]
    for j in i:
        l2[j] = replace
    allcombs.append(l2)

print(allcombs)

[[[1, 2, 3]], [0, 2, 3], [1, 0, 3], [1, 2, 0], [0, 0, 3], [0, 2, 0], [1, 0, 0], [0, 0, 0]]


text:
Q: Install JMAP inside a docker container How can I install jmap on my docker container to get its heap dump once its deployed to AWS ECS as a container.I am using distroless as my base java image.Below is my dockerFile.I have managed to install all other utilities in my container other than jmap
FROM progrium/busybox as prgbusybox
RUN opkg-install curl bash git
FROM busybox:1.35.0-uclibc as busybox
FROM gcr.io/distroless/java:11
COPY --from=busybox /bin/wget /bin/wget
COPY --from=prgbusybox /usr/bin/curl /bin/curl
COPY --from=prgbusybox /bin/cat /bin/cat
COPY --from=prgbusybox /bin/ls /bin/ls
COPY --from=prgbusybox /bin/grep /bin/grep
COPY --from=prgbusybox /bin/ps /bin/ps
COPY --from=prgbusybox /bin/cp /bin/cp
COPY --from=prgbusybox /bin/chmod /bin/chmod
COPY --from=prgbusybox /bin/mkdir /bin/mkdir
COPY --from=prgbusybox /bin/sh /bin/sh
COPY target/my-app*.jar /app/app.jar
WORKDIR /app
RUN wget https://github.com/apangin/jattach/releases/download/v1.5/jattach && chmod +x jattach
ENTRYPOINT ["java","-Xlog:gc=debug:file=./gc.log:time,uptime,level,tags:filecount=10,filesize=10m", "-XX:InitialHeapSize=700M","-XX:MaxHeapSize=1024M", "-jar", "app.jar"]
HEALTHCHECK NONE


text:
Q: Robocopy's copy criteria when MINAGE and MAXAGE is specified What attribute does Robocopy look at when applying the MINAGE and MAXAGE flags? Date created or updated? If a group of files is created and later one of them is updated, if I run Robocopy with a later date range will the updated file be copied?

A: There is confusion here and elsewhere, I believe the following is correct:

*

*minage and maxage actually refer to the last modified date
of the file (not creation date)

*minlad and maxlad actually refer to the last access date of the file.
Sources for the above:

*

*I tested minage with robocopy on Windows 7, and it used last modified date, not creation date. Also backed up by this Technet thread and this thread too.

*The robocopy documentation says that minlad & maxlad are the access date.

A: According to this Technet thread:
minage and maxage refer to the creation date of the file.
minlad and maxlad refer to the last write time of the file.
Note that on later versions of Windows (I think vista and later), last access time stamping is off by default to improve performance.


text:
Q: Fix a Custom Menu Link I am currently creating a Custom menu and submenu link in wordpress but getting the following error
After saving the menu,

*

*the Link URL disappear from the custom menu

*the Sub menu also shift to become a main menu


text:
Q: What is the command for Package Manager | Settings | Repositories | Source code I tried to do step two of building Banshee from source, but it failed as follows:
~$ sudo apt-get build-dep banshee
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to find a source package for banshee

I was able to solve this problem by executing Package Manager | Settings | Repositories | Source code, followed by the command
sudo apt-get update

After which the build-dep step succeeded.
Is there a non-GUI way of enabling the source code repositories for apt-get? The man page says there's apt-get source, but it isn't clear to me that command has the same effect.

A: You can do it from terminal by running the following commands:
sudo -i   #to switch to the root user
echo "deb-src http://archive.ubuntu.com/ubuntu raring main universe restricted multiverse" >> /etc/apt/sources.list
echo "deb-src http://security.ubuntu.com/ubuntu/ raring-security restricted universe main multiverse" >> /etc/apt/sources.list
echo "deb-src http://archive.ubuntu.com/ubuntu raring-updates restricted universe main multiverse" >> /etc/apt/sources.list
exit
sudo apt-get update

This if you use Ubuntu 13.04. If you use other Ubuntu version, change raring with your Ubuntu code name. To see from terminal what is the code name of your current Ubuntu version, use the following command:
lsb_release -c

Also you can change the mirror server (in this case is the main server http://archive.ubuntu.com/ubuntu) with your favorite.


text:
Q: Chrome and IE8 vs the others I am in the process of creating a web page in which I wish to replace a  element with a new  element. The original  element is (for example):
  ;Abbreviation;The definition

The form of the supplied string is <separator><string><separator><string>. The separator is supplied to insure that any special characters in either the first or the second string will not cause parsing difficulties.
A JavaScript function is invoked by the onload event handler for the  element. It detects all s with the class of "green_link". If no such  exists, the function exits. Otherwise, for each such , the function creates a new  element:

      Abbreviation

          Abbreviation

          The definition

Then the function replaces the "green_link"  with the newly created "revised_green_link" .
Browsers were tested using a test page and the actual page. Firefox 3.6.12, Opera 11.11, and Safari 5.0.2 displayed what was expected for both pages. Chrome 12.0.742 displays the test page as expected but fails to display the actual page as expected. IE 8 fails to display either page as expected.
I find it interesting that all of the browsers display the web page as expected when they are directed to it on localhost:port once that Visual Studio 2008 has displayed the page using "View in browser" (i.e., http://localhost:1291/BIODAB.html).
Both HTML documents were successfully checked as XHTML 1.0 Strict by the W3C Markup Validation Service. All CSS (both test and actual) was validated successfully at CSS Level 2.1 by the W3C CSS Validation Service. All JavaScript, with the exception of the jQuery JavaScript Library v1.4, was passed through JSLint without errors.
I have no idea what is causing this diverse behavior and would appreciate some thoughts.

A: You can create HTML tags with javascript and it is cross-browser:
var newSpan = document.createElement('SPAN');
newSpan.id = 'newSpanId';

and then append it to the desired container (div, a, etc...)
parentContainer.appendChild(newSpan);

To remove an element:
parentContainer.removeChild(document.getElementById('elementId'));

A: In IE8, there are two parts to the failure.
The first is that the HTTP headers include this line:
 x-ua-compatible: IE=EmulateIE7

which is putting the browser into IE7 mode.
The second part is that the GreenLinkTest.js contains
getAttribute("class")

which doesn't work in IE7. See getAttribute cannot return class in IE7? for more details.
I can't see a problem with Chrome.


text:
Q: Running a script after tty1 has loaded I have been attempting to write a script to run dcled on start up, the program that runs this.  I am using Debian Jessie with multiarch enabled.  This is essentially a small file server.  I am attempting to do this because I thought it would be cool to see a little led screen print out every time someone attempts to log into the server without having to actually log in and read /var/log/auth.log.  Here is the script I have so far.
!/bin/bash

### BEGIN INIT INFO
# Provides:          dcled.sh
# Required-Start:    $all
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: dcled
# Description:       print file to dcled
### END INIT INFO

# Author:

PATH=/usr/bin

tail -f /var/log/auth.log | dcled -s 50 -p 4

The script works and runs the last line of /var/log/auth.log (when something is new is written to it), but the tty terminal does not show up.  I have used by update-rc.d and insserv to attempt to do get this to work 100% correct to no avail.  Any help with this would be greatly appreciated.


text:
Q: How do I unit test my request, given that the return result is always encrypted? I have this helper class that helps to generate request header and return it as a request.SuperAgentRequest using superagent-bluebird-promise.
My question here is
How do I unit test my request? Given that the return result is always encrypted.
How to test security.decryptJWE?
What I have done in my unit testing so far is to only check the number of times the function is being called.
Unit test class:
let sendRequestSpy = sinon.spy(helper, "sendRequest");

main.updateInfo();

sinon.assert.callCount(sendRequestSpy, 10);

helper class:
const restClient = require('superagent-bluebird-promise');

function sendRequest(id) {
    ...

    _.set(headers, "Authorization", authHeaders);

    let request = restClient.get(url);

    // Set headers
    if (!_.isUndefined(headers) && !_.isEmpty(headers)) {
        request.set(headers);
    }

    return request;
}

main class:
function updateInfo {

    ...
        for (var i = 0; i < list.length; i++) {

            let request = helper.sendRequest(id);
            request.buffer(true).end(function (err, res) {
            ...
                let data = {
                    body: res.body,
                    text: res.text
                };

                let apiData = data.text;

                let privateKey = "./resource/priv_key.pem";

                var jweParts = apiData.split(".");
                security.decryptJWE(jweParts[0], jweParts[1], jweParts[2], jweParts[3], jweParts[4], privateKey)
                .then(apiData => {
                    ...
                    //process here
                }
            }
    }
}

security class:
...
security.decryptJWE = function decryptJWE(header, encryptedKey, iv, cipherText, tag, privateKey) {
  console.log("Decrypting JWE".green + " (Format: " + "header".red + "." + "encryptedKey".cyan + "." + "iv".green + "." + "cipherText".magenta + "." + "tag".yellow + ")");
  console.log(header.red + "." + encryptedKey.cyan + "." + iv.green + "." + cipherText.magenta + "." + tag.yellow);
  return new Promise((resolve, reject) => {

    var keystore = jose.JWK.createKeyStore();

    console.log((new Buffer(header, 'base64')).toString('ascii'));

    var data = {
      "type": "compact",
      "ciphertext": cipherText,
      "protected": header,
      "encrypted_key": encryptedKey,
      "tag": tag,
      "iv": iv,
      "header": JSON.parse(jose.util.base64url.decode(header).toString())
    };
    keystore.add(fs.readFileSync(privateKey, 'utf8'), "pem")
      .then(function (jweKey) {
        // {result} is a jose.JWK.Key
        jose.JWE.createDecrypt(jweKey)
          .decrypt(data)
          .then(function (result) {
            resolve(JSON.parse(result.payload.toString()));
          })
          .catch(function (error) {
            reject(error);
          });
      });

  })
    .catch(error => {
      console.error("Error with decrypting JWE: %s".red, error);
      throw "Error with decrypting JWE";
    })
}

A: After much research, I finally managed to find out how to test my request.
and that is using nocks.
let test = nock('https://test.api.com/id')
        .get('/ID123945/')
        .reply(200, json.encoded.success.result);

However, i am still unable to find out how to test with the return data (of my own and return it as encrypted)


text:
Q: Looking for examples of programmatic generation of geometries in xml3d There are various examples here in the specification but I could not find an end-to-end example on how to start e.g. with a numerical dataset representing an object surface, construct the meshes on the fly and display in a browser.

A: We have some examples of this in our xml3d-examples repository, particularly the wave example which generates and deforms a grid on the fly. The face morphing example also shows mesh deformation, the principle for generating the mesh would be basically the same.
What you'll want to do is write an Xflow operator that takes the numerical dataset as input and outputs vertex positions (and normals and face indices if necessary). The end result would look something like this:
<data id="mydata" compute="index, position, normal = xflow.yourOperator(input1, input2 ...)">
    <float3 id="myinput1" name="input1">...</float3>
    ...
</data>

<mesh src="#mydata" type="triangles"></mesh>

Here is the operator from the wave example above, that would be a good starting point. Xflow will automatically re-compute the mesh whenever the input data changes and you could use the setScriptValue function on value elements (int, float, float3 etc) to set the input data without having to dump it into the DOM as text:
document.getElementById("myinput1").setScriptValue(numericalData.input1);


text:
Q: Relationship between PSRR and gain Wikipedia says that power supply rejection ratio (PSRR) is the ratio of output noise referred to the input vs noise at the power supply:

The PSRR is defined as the ratio of the change in supply voltage to the equivalent (differential) input voltage it produces in the op-amp

Good Quality Design of Analog Cmos Integrated Circuits by Razavi seems to say the same thing:

The power supply rejection ratio (PSRR) is defined as the gain from the input to the output divided by the gain from the supply to the output.

So the overall rejection from power supply to output vary with the closed-loop gain of the op-amp?
So an op-amp with +40 dB gain and 100 dB PSRR, with 0 dBV noise at the power supply would have -60 dBV noise at the output?  The Wikipedia example seems to say that it would be -120 dBV instead, which I don't understand.
Is there also an output component of PSRR?  Like if you lower the gain of the amp, the input referred noise would decrease, right?  But is there then a constant component coupled from the power supply through the output stages that starts to dominate?
Analog Devices MT-043, on the other hand, says:

PSRR or PSR can be referred either to the output (RTO) or the input (RTI). The RTI value can be obtained by dividing the RTO value by the amplifier gain. In the case of the traditional op amp, this would be the noise gain. The data sheet should be read carefully, because PSR can be expressed either as an RTO or RTI value.

Is this true?  How do you find out from the datasheet which method is used?

A: Gain is absolutely the ONLY important part of PSRR. Essentially what you are saying is how much can an op-amp when feeding back a signal cancel out any ripples introduced from the power supply, not from the input of the circuit..
Lets take a simple example: an ideal (infinite open loop gain) voltage follower (output tied directly to the inverting input, fed from the non inverting input). The circuit has a closed loop gain of 1, but the feedback (since the overall gain is SOOO high) will mean that any power supply ripple will be canceled due to the feedback forcing the non inverting and inverting inputs to be in perfect lockstep..
But take the SAME example, but make the OPEN loop gain of the opamp 1, still with closed loop gain of 1, then suddenly the op amp can't keep up with the changes between the non-inverting input and the output-inverting input. And hence all ripple from the power supply would be visible on the output (essentially the op-amp would turn into a noise source with the noise being the coupled power supply ripple)
I understand HOW stevenvh could say that the gain is not meaningful, because he meant CLOSED loop gain... But the gain of question is OPEN loop gain, and YES, that is EVERYTHING in PSRR.
EDIT: And to answer your question, just to follow up slightly here, the PSRR is related to open loop gain, but the more closed loop gain you introduce, the more power supply ripple you will get on the output (hence the 60dB you reference above)
Here is why: Same example I give above, except this time you have a REAL op amp, (finite open loop gain), and resistors in your feedback path, meaning you have a closed loop gain of some value, say 6dB. Since the resistors behave as a voltage divider, the op-amp has to OVERCOMPENSATE for the power supply ripple being fed back to the non-inverting input. If it can only compensate for 100dB of power supply ripple, you will only get 94dB of rejection. The more closed loop gain you introduce, the less of the power supply ripple you are able to reject.
The whole conversation stems from the separate meanings of open loop and closed loop gain.
2nd EDIT: And the way that you get 60dB, or I get my 94dB is that you have to realize you have to convert dB BACK so for example you need to use
$$
20 \log10\left(\frac{10^\frac{100}{20}}{10^\frac{6}{20}}\right) = 94 \mathrm{dB}
$$
$$
20 \log10\left(\frac{10^\frac{100}{20}}{10^\frac{40}{20}}\right) = 60 \mathrm{dB}.
$$
And YES the other guy who said it should be 1mV not 1µV on Wikipedia is correct.

A: The confusion here is that PSRR (Power Supply Rejection Ratio) is a general term which in practice is actually used to refer to multiple things.  In general it is a ratio comparing a change in a parameter against a change in the supply's DC voltage level.
For example, PSRR in an ADC is often used to refer to the ratio of the Gain Error to Change in DC Voltage of the Supply.
Some of this comes from confusing the acronym PSRR, which can be used as:
"Power Supply Rejection Ratio" which is, as mentioned above, a ratio between a measured parameter and a change in the supply's DC voltage.
and
"Power Supply Ripple Rejection" which is the term which is, in general, the ratio of AC voltage on the supply to AC voltage on the input or output.  But, this can also be a ratio of an input to an output in the case of something like an Linear Regulator.
Lets look at an example: http://focus.ti.com/lit/ds/symlink/opa121.pdf

Here you'll see in the table on page 2 a value listed under the "Offset Voltage" section as "Supply Rejection".
This is a "Power Supply Rejection Ratio" comparing changes in the supply's DC level to shifts in the output's offset voltage.

On page 3 a value listed under the "Input Offset Voltage" section as "Supply Rejection".
This is a "Power Supply Rejection Ratio" comparing changes in the supply level to shifts in the input offset voltage.

Looking at charts on page 4, we see a graph of "Power Supply Rejection vs Frequency".
This is a "Power Supply Ripple Rejection" measurement of AC ripple rejection which is the ratio of Supply Ripple to Input Ripple.

This last one may be a bit confusing as for an op-amp the "Power Supply Ripple Rejection" is often specified as a ratio of the supply ripple to the input ripple.  This will generally be the case for devices with feedback or in the case of an op-amp, are generally used with feedback.
For devices without feedback, class D audio amplifiers for instance, "Power Supply Ripple Rejection" is usually just a ratio of the supply ripple to the output ripple and "Power Supply Rejection Ratio" is a measurement of the impact on the supply DC level to the output offset voltage.
In summary there isn't really a hard and fast definition for 'PSRR' and often other terms are used such as 'Supply Rejection', 'Ripple Rejection', 'Power Supply Rejection', etc.  The important thing is that they are always measurements describing the effect of the power supply on the circuit in question.  To figure out what the measurement really means you have to consider the context of the measurement as well as the mode of operation of the device.
EDIT: Here are some examples of different uses by manufacturer:
National Semiconductor: Uses the terms "Power Supply Rejection Ratio" for AC and "DC Power Supply Rejection Ratio" for DC.
Maxim: Uses "Power Supply Rejection Ratio" for DC and "Ripple Rejection" for AC
TI: Uses "Power Supply Ripple Rejection (PSRR)" LDOs and Various forms of "Supply Rejection" for Op-amps (see data sheet above).
Analog Devices: Uses "Power Supply Rejection Ratio" defines it as relating to either the input or output, and even argues that the term PSRR shouldn't be used if its expressed in dB but rather PSR (Power Supply Rejection) should.
There are many more examples but I'll leave it at that.
So again, there really is no standardized definition here, its all up to context.

A: There is a PDF of op-amp test procedures on Intersil's website here which shows that PSRR is referred to the amplifier input. By my calculations, Wikipedia's 1uV output noise should read 1mV.
\$20 \log(\frac{1\mathrm V}{1\mathrm{mV}/100})\$ = 100dB

A: Microchip's op-amp topologies paper explains it this way:
"In a closed-loop system, a less than ideal power supply rejection capability of an amplifier manifests itself as a offset voltage error..."
\$ PSRR(dB) = 20 log \frac {\Delta V_{SUPPLY}}{\Delta V_{OS}} \$
\$ PSR(\frac{V}{V}) = \frac {\Delta V_{OS}}{\Delta V_{SUPPLY}} \$
where
\$ V_{SUPPLY} = V_{DD} - V_{SS}\$
\$ \Delta V_{OS} = \$ input offset voltage change due to PSR
It also goes on to say that having bad PSR is not good for high-gain closed-loop amplifiers powered from batteries, as the DC change in supply voltage (as the battery discharges) will have a measurable affect on the output due to the input offset change.


text:
Q: incomplete type 'void' is not assignable c I am experiencing an error for the following double pointer to void variable, void ** foo. I do not understand why I get this error although I am casting the struct type. Shouldn't *heap->foo[0] now contain/point to the address of personA?
typedef struct Person{
    char * name;
    char age;
}Person;

typedef struct myStruct{
    void ** foo;
}myStruct;

void initialize(myStruct * H, int numbOfPersons){
     H->foo = malloc(sizeof(myStruct*));
    *H->foo = malloc(sizeof(myStruct)*numberOfPersons);

 }

void insert(myStruct * H, void * personA){
    *H->foo[0] = (myStruct)personA;  //error here
}

int main(void){
    myStruct heap;
    int numberOfPpl = 2;
    initialize(heap, numberOfPpl);

    Person A;
    A.grade = 10
    strcpy(A->name, "Jason");

    Insert(&heap, &A);
    return 0;
}

I get the following error:
incomplete type 'void' is not assignable
                 *H->foo[0] = (Student*)I;

A: Type void is not assignable! The left side of an assignment must have an assignable type. You need to cast the left side of the assignment. The tricky part is that you need to do the cast at the pointer level:
*(myStruct*)H->foo[0] = *personA;

There are also some other bugs in your code. Turn up the warning level in your compiler so you can see them (-Wall if you use gcc).

A: there are some errors in your code:
wrong function:
void initialize(myStruct * H, int numbOfPersons){
     H->foo = malloc(sizeof(Person*)); // as I understand you want to add person in H with type of myStruct
    *H->foo = malloc(sizeof(Person)*numbOfPersons);
 }

*

*you have allocated memory for your variable with type myStruct but you don't use it and you loose you allocation if you make H->foo[0] = something you should use memcpy

*if you use H->foo[0] don't add * H->foo[0] = *H->foo

void insert(myStruct * H, void * personA){
    memcpy(H->foo[0], (void*)personA, sizeof(struct Person));  //error here
}
myStruct struct1; don't use C keywords as a variable name
Person A;
A.age = 10; // grade does not exist in your struct and you have forget ;
strcpy(A.name, "Jason"); // A is not a pointer don't use A->name and also you must allocate the memory before do strcpy or use char name[number_of_char] definition

Don't forget to free allocated memory if you use memory dynamic allocation


text:
Q: Mapping std::map to Python Sometimes it makes sense to have a key-ordered dictionary. In C++, this is often implemented with a Red-black tree. But any self-balancing binary search tree will do (fwiw, Knuth is particularly clear on this subject). The best solution I've been able to come up with so far is to take R. McGraw's AVL-tree type and create a wrapper class that basically implements the STL map interface (also counting on the handy ordering of pairs (two element tuples) in Python). Such a tuple basically corresponds to std::map::value_type.
Yes, there's Python's bisect module, and while that is logarithmic at insertion time in the same way that self-balancing binary trees are logarithmic at insertion time (right?), frankly I just want an object. Called OrderedDict or something (and no, the Python 3.1 OrderedDict doesn't qualify -- that's for 'insertion-time' ordering -- and frankly what insertion-time ordering has to do with ordering is not quite obvious).
Note, a key-ordered dictionary is highly useful in many industries (in finance for instance, it's ordinary to keep track of price books of data, which are basically ordered dictionaries of price -> quantity, aggregated order information, etc.).
If anyone has any other ideas, that's great. All I know is I just got five million times smarter by Alex Martelli's 'answers' here. So I thought I'd ask.

A: I got exactly the same need, and Alex Martelli's answer has totally convinced me: best is keeping a dictionary and a list of partially sorted keys, then sort when needed. This is efficient because of the very particular behaviour of python's sort algorithm (AKA Timsort).
Key-ordered dict in Python
I tested his implementation and mine, and his was best (because he does not insert in the middle of the list)
(I strongly advise you to read the paper linked in AM's comment about the timsort, which is a pearl).

A: Lists are a miserable substitute for a tree.
Insertions need to move the whole list around to make space; deletions need to move the list back down.  Adding or deleting stuff in batch is fine when it's possible, but it's very often not, or takes unnatural contortions to arrange it.  A fundamental attribute of a tree is that insertions and deletions are O(log n); no amount of handwaving will turn O(n) into O(log n).
Inserting an item into a tree when you already know where it's going to go is O(1).  Equivalently, deleting an item from a tree based on its node is also O(1).  std::map supports both of these.  These are both O(n) with a list.
Another fundamental property of a tree is that iterating over a range of values is O(1) per iteration.  Combining list and dict loses this, because each iteration needs to do a dict lookup.  (The list-of-tuples approach doesn't have this problem.)
Trees are among the most basic of data types.  Python's lack of a tree container type is a wart.  Maybe there's a third-party library implementing one (eg. the one linked by Mr. "Unknown", which I havn't tried so I can't vouch for), but there's no standard Python type for it.

A: I stumbled on this question needing an OrderedMap myself, and found to my horror that the accepted answer is complete garbage. So I rolled my own, in case anyone finds it useful:
from bisect import *

class OrderedMap:
    """Much less efficient than a dict,
    but keys don't need to be hashable."""
    __default_arg = object()
    def __init__(self, keyvalues_iter = None):
        self.clear()
        if keyvalues_iter is not None:
            self.update(keyvalues_iter)
    def clear(self):
        self.__keys = []
        self.__values = []
    def __index(self, key):
        if self.__keys:
            index = bisect(self.__keys, key)-1
            if self.__keys[index] == key:
                return index
        raise KeyError(key)
    def __len__(self):
        return len(self.__keys)
    def __contains__(self, key):
        try:
            self.__index(key)
            return True
        except KeyError:
            return False
    def __getitem__(self, key):
        index = self.__index(key)
        return self.__values[index]
    def __setitem__(self, key, value):
        try:
            index = self.__index(key)
            # exists
            self.__values[index] = value
        except KeyError:
            # new
            index = bisect(self.__keys, key)
            self.__keys.insert(index, key)
            self.__values.insert(index, value)
    def __delitem__(self, key):
        index = self.__index(key)
        self.__keys.pop(index)
        self.__values.pop(index)
    def __iter__(self):
        return iter(self.__keys)
    def get(self, key, default=__default_arg):
        try:
            return self[key]
        except KeyError:
            if default != OrderedMap.__default_arg:
                return default
            raise
    def setdefault(self, key, default = None):
        try:
            return self[key]
        except KeyError:
            if default != OrderedMap.__default_arg:
                self[key] = default
                return default
            raise
    def items(self):
        return zip(self.__keys, self.__values)
    def iteritems(self):
        return iter((self.__keys[x], self.__values[x])
                    for x in xrange(len(self)))
    def keys(self):
        return self.__keys[:]
    def iterkeys(self):
        return iter(self.__keys)
    def values(self):
        return self.__values[:]
    def itervalues(self):
        return iter(self.__values)
    def update(self, other):
        for k, v in other.iteritems():
            self[k] = v
    def __repr__(self):
        s = ", ".join("%s: %s" % (repr(self.__keys[x]),
                                  repr(self.__values[x]))
                      for x in xrange(len(self)))
        return "OrderedMap{%s}" % (s,)

A: You might be looking for a SortedCollection:
http://code.activestate.com/recipes/577197-sortedcollection/

A: The Python sortedcontainers module provides a SortedDict data type for exactly these purposes. It uses a modified B-tree type data structure and is written in pure-Python. The module has 100% test coverage and hours of stress. Though pure-Python, it's faster that C-implementations and has a performance comparison to back it up.
Because it's pure-Python, installation is a breeze with pip:
pip install sortedcontainers

Then you simply:
from sortedcontainers import SortedDict
help(SortedDict)

The performance comparison includes a pretty comprehensive list of alternative implementations. It's worth a look.

A: For a list that stays sorted, you can try module heapq.

A: As you said, you can roll your own implementation with bisect:
class OrderedDict:
  def __init__(self, keyvalues_iter):
    self.__srtlst__ = sorted(keyvalues_iter)
  def __len__(self):
    return len(self.__srtlst__)
  def __contains__(self, key):
    index = bisect(self.__srtlst__, key)
    if index<len(self.__srtlst__) and self.__srtlst__[index][0] == key:
      return True
    else:
      return False
  def __getitem__(self, key):
    index = bisect(self.__srtlst__, key)
    if index<len(self.__srtlst__) and self.__srtlst__[index][0] == key:
      return self.__srtlst__[index][1]
    else:
      raise KeyError(key)
  def __setitem__(sekf, key, value):
    index = bisect(self.__srtlst__, key)
    if index<len(self.__srtlst__) and self.__srtlst__[index][0] == key:
      self.__srtlst__[index][1] = value
    else:
      self.__srtlst__[index]=(key, value)
  def __delitem__(sekf, key, value):
    index = bisect(self.__srtlst__, key)
    if index<len(self.__srtlst__) and self.__srtlst__[index][0] == key:
      del __srtlst__[index]
    else:
      raise KeyError(key)
   def __iter__(self):
     return (v for k,v in self.__srtlst__)
   def clear(self):
     self.__srtlst__ = []
   def get(self, key, default=None):
    index = bisect(self.__srtlst__, key)
    if index<len(self.__srtlst__) and self.__srtlst__[index][0] == key:
      return self.__srtlst__[index][1]
    else:
      return default
   def items(self):
     return self.__srtlst__[:]
  def iteritems(self):
    return iter(self.__srtlst__)
  def iterkeys(self):
    return (k for k,v in self.__srtlst__)
  def itervalues(self):
    return (v for k,v in self.__srtlst__)
  def keys(self):
    return [k for k,v in self.__srtlst__]
  def values(self):
    return [v for k,v in self.__srtlst__]
  def setdefault(self, key, default):
    index = bisect(self.__srtlst__, key)
    if index<len(self.__srtlst__) and self.__srtlst__[index][0] == key:
      return self.__srtlst__[index][1]
    else:
      self.__srtlst__[index]=(key, default)
      return default
  def update(self, other):
    #a more efficient implementation could be done merging the sorted lists
    for k, v in other.iteritems():
      self[k] = v

hmmm... it seems that I already did that for you, d'oh!


text:
Q: GWT Deployment Confusion, Please give some guidelines I wanted to know one thing. When deploying a GWT application on
the server, lets say an application in which there are client  files
Greeting.java(entrypoint), service.java,serviceAsync.java and server
file serviceImpl.java(), only the client files will converted to
javascript. After compilation, I take the war file and place it on the
server, but where to place the server file that is serviceImpl.java???

A: The war file will also contain a /WEB-INF folder with the web.xml your libs and the other java classes needed for the server side.
So you only need to copy your war file in the proper webapps folder from your server.


text:
Q: Writing a 2D Array to a string, then to a .txt file - Java I have a Method that calls a second method, the second method will:

*

*Create any missing directories

*Create a file

*Decode a 2D String[] to a String (Not working)

*Write content

*Write the decoded String to the file with a header (Not working)

First method
public static boolean store(Exception exception, String[][] flags){
    return storePrivate(exception, location, flags);
}

Second Method (Not all code just relevant code)
private static boolean storePrivate(Exception exception, String dir, String[][] flags){
    String flag = "";

    for(int i = 0; i >= flags.length; i++){
        flag = flag + "" +  flags[i][0] + ": " + flags[i][1] + "\n";
    }
    try {
        File directory = new File(dir);
        File file = new File(dir + id + ".txt");
        if (!directory.exists()) {
            directory.mkdirs();
        }
        file.createNewFile();
        FileWriter filewriter = new FileWriter(file.getAbsoluteFile());
        BufferedWriter writer = new BufferedWriter(filewriter);

        if(flag != ""){
            writer.write("Flags by Developer: ");
            writer.write(flag);
        }
        writer.flush();
        writer.close();
        return true;
    } catch (IOException e) {
        return false;
    }
}

Call to the first method
public static void main(String[] args) {
    try {
        test();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        ExceptionAPI.store(e, new String[][]{{"flag1", "Should be part of flag1"}, {"flag2", "this should be flag 2 contence"}});
    }
}

public static void test() throws IOException{
    throw new IOException();
}

I cant find why this won't work. I think it has to do with the second method, particularly
if(flag != ""){
    writer.write("Flags by Developer: ");
    writer.write(flag);
}

Thanks if anyone can help me.
Curlip

A: Try this if you want to just convert an array of strings into a single string:
    String[] stringTwoD = //... I think this is a 1D array, and Sting[][] is a 2D, anyway
    String stringOneD = "";
    for (String s : stringTwoD)
        stringOneD += s;//add the string with the format you want

BTW, your loop condition seems wrong and ,so you may change it to  :
for(int i = 0; i < flags.length; i++){
    flag += flags[i][0] + ": " + flags[i][1] + "\n";
}


text:
Q: Django: Displaying image from model field? I'm having trouble getting an image to display. This should be really easy to fix. I'm just a noob. :/
My models.py is the following:
import datetime

from django.db import models
from django.utils import timezone

class Coin(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    ticker = models.CharField(max_length=5)
    logo = models.ImageField(upload_to='uploads/', verbose_name='image')
    website = models.URLField(max_length=200, default="https://example.com/")
    reddit = models.URLField(max_length=200, default="https://reddit.com/r/")
    twitter = models.URLField(max_length=200, default="https://twitter.com/")
    summary = models.CharField(max_length=500, blank=True)
    description = models.TextField()
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.ticker

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class CoinImage(models.Model):
    coin = models.ForeignKey(Coin, default=None, related_name='images',
                             on_delete=models.CASCADE)
    image = models.ImageField(upload_to='static/uploads', verbose_name='image')

In my views.py I have:
from django.http import HttpResponse, Http404
from django.template import loader
from django.shortcuts import render

from .models import Coin

def index(request):
    latest_coins_list = Coin.objects.order_by('-pub_date')[:5]
    context = {'latest_coins_list': latest_coins_list}
    return render(request, 'coins/index.html', context)

def detail(request, coin_id):
    try:
        coin = Coin.objects.get(pk=coin_id)
    except Coin.DoesNotExist:
        raise Http404("Coin does not exist")
    return render(request, 'coins/detail.html', {'coin': coin})

My main urls.py is:
from django.contrib import admin
from django.urls import include, path
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('coins/', include('coins.urls')),
    path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

My app urls.py is:
from django.urls import path
from django.conf import settings
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('<int:coin_id>/', views.detail, name='detail'),
]

Then finally in my template file details.html:
{% load static %}

{{ coin.name }} | {{ coin.ticker }}

{{ coin.description }}

Website: {{ coin.website }}

Twitter: {{ coin.twitter }}

Reddit: {{ coin.reddit }}

When I view the template I get the alt text. Then when trying to access the image directly 127.0.0.1:8000/static/uploads/thumbs/me.jpg I get a template error saying:

Page not found (404) Request Method:  GET Request URL:
    http://127.0.0.1:8000/static/uploads/thumbs/me.jpg Raised by:
    django.views.static.serve
'uploads/thumbs/me.jpg' could not be found
You're seeing this error because you have DEBUG = True in your Django
  settings file. Change that to False, and Django will display a
  standard 404 page.

This should be a really simple thing to do. If someone can point me in the right direction I would appreciate it so much. Sorry, am noob. :P
Added for someone:
import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'i*a%3!kg*mj7j-=5b@_3cx(^%sqr*&sp$-fg*qv=qewm!a-_gt'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'coins',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'blockintel.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'blockintel.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,  '/static/')
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

A: During development, you can serve user-uploaded media files from MEDIA_ROOT. This is te absolute filesystem path to the directory that will hold user-uploaded files. in your settings, you should provide:
# MEDIA_ROOT = os.path.join(BASE_DIR,'your_directory')
MEDIA_ROOT = os.path.join(BASE_DIR,'media') # media most of the time

MEDIA_URL, URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slash if set to a non-empty value. You will need to configure these files to be served in both development and production environments. add this in your settings
# MEDIA_URL = '/your_url/'
MEIDA_URL = '/media/' # most of the time

You will need to do this as well by adding the following snippet to your root urls.py:
urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

NOTE: This helper function works only in debug. Know more here

ISSUES / SUGGESTIONS
In this field, rather than uploading a file to static directory, just provide your media directory, in that case, it's media.
image = models.ImageField(upload_to='uploads/', verbose_name='image')

Django will automatically create a directory: 'uploads' inside the MEDIA_ROOT which is media,
So access all your the images that you have with
# file.url
{{ coin.logo.url }}