text:
Q: GL_INVALID_OPERATION on random opengl es 2.0 functions I am executing the following C++ code in the middle of my game (everything is running fine except this), and I'm not running it while rendering:
MetaBalls::MetaBalls() : largeTexture(NULL), metaballsShader(NULL), smallTexture(NULL), smallFBO(0), largeFBO(0) {

// 1. Compile shader that will render small texture onto larger texture using blur threshold
CRender::Instance()->CreateShader("Shaders/metaballs.fs", "Shaders/metaballs.vs", &metaballsShader);
metaballsShader->_locations["projview"] = glGetUniformLocation(metaballsShader->_program, "projview");

// 4. Load the sprite that will be rendered as particles on the small texture
// TODO: batch render this
m_metaballSprite.InitSprite("Embellishments/particle.png", OFFSCREEN);

// 2. Create new texture and 2 frame buffers
// First frame buffer to render small texture, second frame buffer to scale small texture up into big one
glGenTextures(1, &smallTexture);
glBindTexture(GL_TEXTURE_2D, smallTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8_OES, SMALL_TEX_W, SMALL_TEX_H, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);

// 3. Create second larger texture to contain final water textured (rendered in game as sprite)
glGenTextures(1, &largeTexture);
glBindTexture(GL_TEXTURE_2D, largeTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8_OES, LARGE_TEX_W, LARGE_TEX_H, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);

// 5. Attach small texture to frame buffer
glGenFramebuffers(1, &smallFBO);
glBindFramebuffer(GL_FRAMEBUFFER, smallFBO);
glBindTexture(GL_TEXTURE_2D, smallTexture);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, smallTexture, 0);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
    s3eDebugErrorShow(S3E_MESSAGE_CONTINUE_STOP, "Metaballs small framebuffer incomplete");
}

// 6. Attach large texture to other frame buffer
glGenFramebuffers(1, &largeFBO);
glBindFramebuffer(GL_FRAMEBUFFER, largeFBO);
glBindTexture(GL_TEXTURE_2D, largeTexture);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, largeTexture, 0);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
    s3eDebugErrorShow(S3E_MESSAGE_CONTINUE_STOP, "Metaballs small framebuffer incomplete");
}

// 7. Build geometry for small frame buffer
float w = PTM_DOWNSCALE(SMALL_TEX_W);
float h = PTM_DOWNSCALE(SMALL_TEX_H);
CRender::Instance()->BuildQuad(
    tVertex( b2Vec3(0,0,0), b2Vec2(0,1) ),
    tVertex( b2Vec3(w,0,0), b2Vec2(1,1) ),
    tVertex( b2Vec3(w,h,0), b2Vec2(1,0) ),
    tVertex( b2Vec3(0,h,0), b2Vec2(0,0) ),
    smallBuffer);

// 8. Build geometry for large frame buffer
w = PTM_DOWNSCALE(SMALL_TEX_W);
h = PTM_DOWNSCALE(SMALL_TEX_H);
CRender::Instance()->BuildQuad(
    tVertex( b2Vec3(0,0,0), b2Vec2(0,1) ),
    tVertex( b2Vec3(w,0,0), b2Vec2(1,1) ),
    tVertex( b2Vec3(w,h,0), b2Vec2(1,0) ),
    tVertex( b2Vec3(0,h,0), b2Vec2(0,0) ),
    largeBuffer);

// return to default state
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

My problem is that I'm getting this error reported from OpenGL ES 2.0:
GL Error GL_INVALID_OPERATION on entry to function glGenFramebuffers(1, 0xd8450e8)

If I switch the order of the above opengl calls near the start of the function I can get GL_INVALID_OPERATION occuring on either of the glGenTextures lines, glBindFramebuffer, or even glCreateProgram() which is executed inside the first CreateShader function. Although with the current call order, the shader is loading and compiling fine.
The error I am getting breaks the documented results of these calls on opengl.org, for example, glGenFramebuffers should only return GL_INVALID_OPERATION if you pass a non-zero value that glGenFrameBuffers did not return. However, I have checked the integers returned from glGenFrameBuffers... they are 2 and 3. Nothing wrong with those since I already have a third frame buffer elseware. I also tried generating both textures and frame buffers at once but they produce the same GLuint's and the same errors occur.
Any idea how this error could possibly be caused?? I've had similar code running in this class no problem in the past.


text:
Q: Create custom templates using ckeditor, tinymce or any online editor I am not sure if the title represents what exactly I need to do, But here is the details. I am building a website using PHP that allows people to create different templates, then they should select one of them and then fill the fields to fill the placeholders. For example consider the following image

The name of the recipient could be a placeholder so some part of the template can be

Dear {recipient}
{body}

and I prepare two fields for recipient and the body and it will be replaced by the value of the corresponding field. I can do this. What I can't do is how to let the user to align the placeholders in the paper. For example there is a placeholder for the date that must be at right of the page, or any other placeholder that can be place inside the paper (same as the following image). I would like to know if ckeditor or any other editor allows me to create such template?
The structure of the template must be kept in A4 or A5 print page.

A: I'm having trouble understanding your question. If you're looking for templates in TinyMCE editor, I think you should try using template plugin for tinymce - there is one for wordpress. You can write your own plugin too, there was question about it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Parametrize Jenkins Pipeline How can I parametrize my jobs from the pipeline syntax?
I have the job:
image
image
How can I apply ENV parameters to the jobs inside my pipeline scripts by the same ENV selection for the pipeline?
image
So when I run my pipeline I want to select the parameter one time and apply this parameter for all the jobs inside my pipeline syntax

A: Like this:
pipeline {
    agent any

    parameters {
        string defaultValue: '', description: 'Name: ', name: 'NAME', trim: true
    }

    stages {
        stage('Printing parameters') {
            steps {
                script {
                    print("Hi, my name is ${env.NAME}")
                }
            }
        }
    }
}

When you say "apply this parameter for all the jobs inside my pipeline", I'm assuming you mean "all the stages inside my pipeline". Jenkins treats parameters as environment variables, so once they're filled, they can be read in all pipeline stages.
Best regards.


text:
Q: Read Java generated public key in node I have the bytes of a public key generated in Java with something like this:
package test;

import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.util.Base64;

public class Test {

    public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
         KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
         //generator.initialize(dsabits, sr);
         KeyPair keyPair = generator.generateKeyPair();
         PublicKey publicKey = keyPair.getPublic();

         byte[] encodedBytes = Base64.getEncoder().encode(publicKey.getEncoded());
         System.out.println("decodedBytes " + new String(encodedBytes));
    }

}

=> decodedBytes MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJQz9HgPKzGi+jT5uZ7CEU8mQyNZXm1IpPBIaMGZ2IW54iv+ptVAI8lG9mRNPTyZf07GZNnDSp5RcAn19lUh6eBxZ6R+Yg78rjw4UFfuGQPe8pKrAsy0ESOxLJrh2iQpa4H1DQ86Jq1kSUGFBMCpk68RyT+yQGwBCO8yomqp+7HQIDAQAB

Now I need to encrypt a string in node using this publick key.
I tried with
var crypto = require("crypto");
var pubKeyB64 = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJQz9HgPKzGi+jT5uZ7CEU8mQyNZXm1IpPBIaMGZ2IW54iv+ptVAI8lG9mRNPTyZf07GZNnDSp5RcAn19lUh6eBxZ6R+Yg78rjw4UFfuGQPe8pKrAsy0ESOxLJrh2iQpa4H1DQ86Jq1kSUGFBMCpk68RyT+yQGwBCO8yomqp+7HQIDAQAB';

var pubKey = Buffer.from(pubKeyB64, 'base64');

var toEncrypt = 'ciao';
var buffer = new Buffer(toEncrypt);
var encrypted = crypto.publicEncrypt(pubKey, buffer);
console.log(encrypted.toString("base64"));

but unfortunately I get

Error: error:0906D06C:PEM routines:PEM_read_bio:no start line

I don't have control over the public key generation format, unfortunately I have to use what I got there.
Is there a way to use this key in node to encrypt a string somehow?

A: Assuming you mean https://nodejs.org/api/crypto.html#crypto_crypto_publicencrypt_key_buffer it says it wants as a string

A PEM encoded public or private key.

To create the PEM encoding, instead of converting your base64 to binary, break it into chunks of 64 chars except the last each followed by a newline, put a line -----BEGIN PUBLIC KEY----- plus newline at the beginning and a line -----END PUBLIC KEY----- plus newline at the end.
I could code this on the Java side but you say you can't change that, and I don't know enough js to code the nodejs side, so setting CW for anyone else to.


text:
Q: resque worker load distribution not fair I have a Resque Job backed by ActiveRecord that saves a post message to the database.
Have 7 worker instances running. I send 20K records to my sinatra application.
When i query the redis database, i see the following results...
redis> get resque:stat:processed:localhost:6929:default
"5696"
redis> get resque:stat:processed:localhost:6930:default
"1"
redis> get resque:stat:processed:localhost:6942:default
"1"
redis> get resque:stat:processed:localhost:6953:default
"10854"
redis> get resque:stat:processed:localhost:6959:default
"3446"
redis> get resque:stat:processed:localhost:6972:default
"1"
redis> get resque:stat:processed:localhost:6986:default
"1"

can anyone comment on it please?
 4 of the 7 workers only processed 1 job each in their lifetime

A: Finally figured it out when i replaced ActiveRecord with RDBI. I was getting the following error when my workers were trying to connect to the oracle database
java.sql.SQLRecoverableException: I/O Exception: Connection reset
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:281)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:118)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:224)

After googling, i stumbled upon this post http://kr.forums.oracle.com/forums/thread.jspa?messageID=3793101 . So, i decided to pass the -Djava.security.egd=file:///dev/urandom option to my jvm. I edited the settings in glassfish's jvm options, but that did not work as those settings benefited my sinatra app but not the resque workers running in the background.
So, i had to start the resque workers by passing the jvm argument. I wrote a rake task to do the same.
desc "Start multiple workers for JRUBY production environment which ocnnects to oracle database"
task :start_workers => :setup do

threads = []

ENV['COUNT'].to_i.times do
  threads << Thread.new do
    system "/usr/bin/java -Djdk.home= -Djava.security.egd=file:///dev/urandom -Djruby.home=/usr/local/rvm/rubies/jruby-1.6.0 -Djruby.script=jruby -Djruby.shell=/bin/bash -Djffi.boot.library.path=/usr/local/rvm/rubies/jruby-1.6.0/lib/native/ppc-Linux:/usr/local/rvm/rubies/jruby-1.6.0/lib/native/i386-Linux:/usr/local/rvm/rubies/jruby-1.6.0/lib/native/x86_64-Linux -Xmx500m -Xss1024k -Djruby.memory.max=500m -Djruby.stack.max=1024k -Dsun.java.command=org.jruby.Main -Djava.class.path=/usr/local/rvm/rubies/jruby-1.6.0/lib/mysql-connector-java-5.0.6-bin.jar:/usr/local/rvm/rubies/jruby-1.6.0/lib/ojdbc6.jar:/usr/local/rvm/rubies/jruby-1.6.0/lib/sqlitejdbc-v056.jar: -Xbootclasspath/a:/usr/local/rvm/rubies/jruby-1.6.0/lib/jruby.jar org/jruby/Main /usr/local/rvm/gems/jruby-1.6.0/bin/rake resque:work RACK_ENV=#{ENV['RACK_ENV']} QUEUE=#{ENV['QUEUE']} INTERVAL=#{ENV['INTERVAL']}"
  end
end

threads.each { |thread| thread.join }

end


text:
Q: Генерация большого дерева в Symfony Forms Как реализовать дерево в Symfony Forms? На Symfony пишу всего пару недель.
Пробовал множество способов, по сути форму можно реализовать обычным способом без вспомогательных классов. Хотелось бы все таки разобраться как создать дерево с помощью Symfony Forms, или может это дурная затея?
Форма состоит из множества текстовых полей, возникла именно трудность реализации многоуровневого дерева.
Есть таблица пользователей, у каждого пользователя имеются свои категории. Всего категорий 3000, да их очень много. В таблице UserCategory 227848 записей.
Форму создаю с помощью \Symfony\Bundle\FrameworkBundle\Controller\AbstractController::createForm

Структура дерева

*

*Категория 1

*

*Категория 2

*Категория 3

*

*Категория 4

*Категория 7

*Категория 8

*

*Категория 9

*Категория 10

*

*Категория 11

*Категория 12

Класс сущности пользователей

/**
 * @ORM\Entity(repositoryClass="App\Repository\UsersRepository")
 */
class Users
{

    /**
     * @ORM\Id()
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue()
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=254, options={"default":""})
     * @Assert\NotBlank()
     * @Assert\Regex("/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/", message="Введите корректный email-адрес.")
     * @Assert\Email()
     */
    private $email;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Category", mappedBy="idUser")
     */
    private $userCats;

    public function __construct()
    {
        $this->userCats = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function setId(int $id): self
    {
        $this->id = $id;
        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;
        return $this;
    }

    /**
     * @return Collection|UserCategory[]
     */
    public function getUserCats(): Collection
    {
        return $this->userCats;
    }

    public function addUserCat(UserCategory $userCat): self
    {
        if (!$this->userCats->contains($userCat)) {
            $this->userCats[] = $userCat;
            $userCat->setId($this);
        }

        return $this;
    }

    public function removeUserCat(UserCategory $userCat): self
    {
        if ($this->userCats->contains($userCat)) {
            $this->userCats->removeElement($userCat);
            // set the owning side to null (unless already changed)
            if ($userCat->getId() === $this) {
                $userCat->setId(null);
            }
        }

        return $this;
    }

}

Класс сущности категорий

/**
* @ORM\Entity(repositoryClass="App\Repository\CategoryRepository")
* @ORM\Table(indexes={
*     @ORM\Index(columns={"idParent"})
* })
*/
class Category
{

    /**
    * @ORM\Id()
    * @ORM\GeneratedValue()
    * @ORM\Column(type="integer", length=10)
    */
    private $id;

    /**
    * @ORM\Column(type="string", length=250, options={"default":""})
    */
    private $name;

    /**
    * @ORM\Column(type="integer", length=10)
    */
    private $idParent;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function setId(int $id): self
    {
        $this->id = $id;
        return $this;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getIdParent(): ?int
    {
        return $this->idParent;
    }

    public function setIdParent(int $idParent): self
    {
        $this->idParent = $idParent;
        return $this;
    }

    public function __toString()
    {
        return $this->getName();
    }
}

Класс сущности выбранных категорий пользователя

/**
* @ORM\Entity(repositoryClass="App\Repository\UserCategoryRepository")
*/
class UserCategory
{

    /**
    * @ORM\Id()
    * @ORM\ManyToOne(targetEntity="App\Entity\Users", inversedBy="userCats")
    */
    private $idUser;

    /**
    * @ORM\Id()
    * @ORM\Column(type="integer", length=10)
    */
    private $idCat;

    public function getIdUser(): ?Users
    {
        return $this->idUser;
    }

    public function setIdUser(?Users $idUser): self
    {
        $this->idUser = $idUser;

        return $this;
    }

    public function getIdCat(): ?int
    {
        return $this->idCat;
    }

    public function setIdCat(int $idCat): self
    {
        $this->idCat = $idCat;

        return $this;
    }
}

A: Для сущности категории используйте шаблон nested. В форме укажите группировку по родителю. По идеи, будет тот результат что вы хотите. В прицепе патерн и не обязательно использовать, но в вашем случае желательно, сэкономите на запросах к БД.


text:
Q: Servlets and Wsdl file have a wsdl link and I know the soap request what to send and lso the response format through the membrane soap ui client
I have written a simple html page having 3 fields which i pass through request format of soap and then i get a response based on it. This passing of request and validations are done in servlet which i call through action in form. Now i have a wsdl file link.
How should I use it to make request response from the servlet .please help me with code.
EDIT : THE WSDL CONTAINS WCF BASED SOAP SERVICE .

A: You have to build a web service client from wsdl using wsimport java utility, then you will get a webservice handle, using that you can build a request, send a request and get a response.
for more details: http://docs.oracle.com/javaee/6/tutorial/doc/bnayn.html


text:
Q: Spring MVC : How to access a model object List in JS? It is supposed to be a trivial knowledge in Spring MVC, but I am stuck in this tricky part.
Obviously I miss something important!
So, I want to:

*

*send a List of names taken from the database to the front end

*add an extra name  in the list names (in the controller side)

*access the list of names in a javascript variable in the jsp file

//controller
List<String> names = namesService.getnames(); ("John", "Peter", "John" )
names.add("Nick");
model.addAttribute("names", names);
//JSP
<script type="text/javascript">
    var names = ${names};
</script>

What happens next is that the names received from the database ("John", "Peter", "John" ) are recognized in JS as Strings, but "Nick" is recognized as an uknown variable Nick:
Uncaught ReferenceError: Nick is not defined

Why is this happening? How could I solve it?

A: when you use ${names} it calls toString() method of names object  and returns its result. for example consider the following code:
List<String> names = new ArrayList<>();
names.add("alice");
names.add("bob");

in your jsp you have this:
<script type="text/javascript">
    var names = [alice, bob]
</script>

so it is obvious that alice and bob references are not defined. they must be ['alice', 'bob'].
so enclose your string with ' everything should works.
List<String> names = new ArrayList<>();
names.add("'alice'");
names.add("'bob'");


text:
Q: Determine exact name of an OpenType font in PowerShell I have a collection of OpenType font files which are all different styles of the same family:

*

*"FreigSanLFProBol.otf" (FreightSansLFPro Bold)

*"FreigSanLFProBoo.otf"
(FreightSansLFPro Regular)

*"FreigSanLFProBooIta.otf"
(FreightSansLFPro Italic)

In order to install these fonts via PowerShell and properly add them to the registry, I need to know their friendly style name.
When I install "FreigSanLFProBol.otf" via Windows Explorer, the registry key contains this data:
{
  name: "FreightSansLFPro Bold (TrueType)",
  type: REG_SZ,
  data: "FreigSanLFProBol.otf"
}

The problem is I have no idea how to programmatically identify the value in the "name" key from the font file itself.
Using the information available in Name of font by powershell, I was able to get most of the way there:
$path = "C:\Windows\Fonts\FreigSanLFProBol.otf"
Add-Type -AssemblyName System.Drawing
$fontCollection = New-Object System.Drawing.Text.PrivateFontCollection
$fontCollection.AddFontFile($(Get-Item $path).fullname)
$fontCollection.Families[-1].Name

That gives me the result of "FreightSansLFPro" - which is different than the reg key value which gives it as "FreightSansLFPro Bold". (Never mind the fact that the reg key still lists the type as "TrueType Font" even though it's an OpenType Font).
Where does it get "Bold" from, and how do I get that specific value/name from the font file programmatically?

A: $folder = "C:\Windows\fonts\"

$objShell = New-Object -ComObject Shell.Application

$fileList = @()
$attrList = @{}
$details = ( "Title",
              "Font style",
              "Show/hide",
              "Designed for",
              "Category",
              "Designer/foundry" ,
               "Font Embeddability",
               "Font type",
               "Family",
               "Date created",
               "Date modified",
               "Collection",
               "Font file names",
               "Font version"
                 )

 #figure out what the possible metadata is
$objFolder = $objShell.namespace($folder)
for ($attr = 0 ; $attr  -le 500; $attr++)
{
    $attrName = $objFolder.getDetailsOf($objFolder.items, $attr)
    if ( $attrName -and ( -not $attrList.Contains($attrName) ))
    {
        $attrList.add( $attrName, $attr )
    }
}

 #$attrList

 #loop through all the fonts, and process
     $objFolder = $objShell.namespace($folder)
    foreach($file in $objFolder.items())
    {
        foreach( $attr in $details)
        {

            $attrValue = $objFolder.getDetailsOf($file, $attrList[$attr])
            if ( $attrValue )
            {
                Add-Member -InputObject $file -MemberType NoteProperty -Name $attr -value $attrValue
            }
        }
        $fileList += $file
        write-verbose "Prcessing file number $($fileList.Count)"
    }

$fileList | select $details |  out-gridview

Source: https://powershell.org/forums/topic/listing-font-details/


text:
Q: Image Fusion Using wavelet transform in python How to fuse 2 images using wavelet transform. There are several methods available such as Principal Component Analysis, High Pass Filtering, IHS, etc. I want to know how to fuse using Wavelet transform. I know the theory behind and want to know how to implement it in Python.
Here is the link of Image Fusion Based on Wavelet transform https://www.slideshare.net/paliwalumed/wavelet-based-image-fusion-33185100

A: First you need to download PyWavelet
https://pywavelets.readthedocs.io/en/latest/
Second run the following code on your images:
import pywt
import cv2
import numpy as np

# This function does the coefficient fusing according to the fusion method
def fuseCoeff(cooef1, cooef2, method):

    if (method == 'mean'):
        cooef = (cooef1 + cooef2) / 2
    elif (method == 'min'):
        cooef = np.minimum(cooef1,cooef2)
    elif (method == 'max'):
        cooef = np.maximum(cooef1,cooef2)
    else:
        cooef = []

    return cooef

# Params
FUSION_METHOD = 'mean' # Can be 'min' || 'max || anything you choose according theory

# Read the two image
I1 = cv2.imread('i1.bmp',0)
I2 = cv2.imread('i2.jpg',0)

# We need to have both images the same size
I2 = cv2.resize(I2,I1.shape) # I do this just because i used two random images

## Fusion algo

# First: Do wavelet transform on each image
wavelet = 'db1'
cooef1 = pywt.wavedec2(I1[:,:], wavelet)
cooef2 = pywt.wavedec2(I2[:,:], wavelet)

# Second: for each level in both image do the fusion according to the desire option
fusedCooef = []
for i in range(len(cooef1)-1):

    # The first values in each decomposition is the apprximation values of the top level
    if(i == 0):

        fusedCooef.append(fuseCoeff(cooef1[0],cooef2[0],FUSION_METHOD))

    else:

        # For the rest of the levels we have tupels with 3 coeeficents
        c1 = fuseCoeff(cooef1[i][0],cooef2[i][0],FUSION_METHOD)
        c2 = fuseCoeff(cooef1[i][1], cooef2[i][1], FUSION_METHOD)
        c3 = fuseCoeff(cooef1[i][2], cooef2[i][2], FUSION_METHOD)

        fusedCooef.append((c1,c2,c3))

# Third: After we fused the cooefficent we nned to transfor back to get the image
fusedImage = pywt.waverec2(fusedCooef, wavelet)

# Forth: normmalize values to be in uint8
fusedImage = np.multiply(np.divide(fusedImage - np.min(fusedImage),(np.max(fusedImage) - np.min(fusedImage))),255)
fusedImage = fusedImage.astype(np.uint8)

# Fith: Show image
cv2.imshow("win",fusedImage)

The fusedImage is the resulted fusion of I1 and I2


text:
Q: kivy Buildozer Android build cannot find translation files Post building my kivy app for Android using Buildozer the run step fails as it cannot find the message files for gettext.
I have the following line in my .spec file:
source.include_exts = py,png,jpg,kv,atlas,mo,po,ini

The .mo files are in the current app dir under ./locales.
I have also included the following line in .spec:
source.include_patterns = locales/*

Finally, my code in main.py includes:
trans = gettext.translation('base', localedir='locales', languages=[locale.getdefaultlocale()[0][0:2]])

languages is set to en and an en directory is within the locales folder.
Is appears as if Buildozer is picking these up:
Listing '/Users/martinprater/PycharmProjects/kivy/.buildozer/android/app/locale/de'...
Listing '/Users/martinprater/PycharmProjects/kivy/.buildozer/android/app/locale/de/LC_MESSAGES'...
Listing '/Users/martinprater/PycharmProjects/kivy/.buildozer/android/app/locale/en'...
Listing '/Users/martinprater/PycharmProjects/kivy/.buildozer/android/app/locale/en/LC_MESSAGES'...

How can I validate if they are included in the app?
Thanks,
Martin

A: I am not sure if this is the easiest way, but could solve the issue by switching to p4a native and using setup.py:
setup(
    ...
    package_data={'.': ['main.py', '*.kv', '*.png', 'locales/*/LC_MESSAGES/base.mo']}
)

Then accessing the file using pkg_resources:
pkg_resources.resource_filename('pkg', 'locales')


text:
Q: Give an example of a group $G$ where $n|ord(G)$ but there is no $g\in G$ such that $ord(g)=n$ I thought about Some kind of: $D_n\times \Bbb{Z}_p$ but it does not work. I don't know where to start looking for it, I mean I know where to do not look for it, cannot be cyclic ;), now I can see that the group of symmetries will not work as well. But I am guessing and checking. I think this is not the right approach

A: A somewhat trivial set of examples: $|G|$ divides $|G|$, so take any group which is not cyclic and it'll have no element of order $|G|$.
For a less trivial example, look at $G = \mathbb{Z}_2 \times \mathbb{Z}_2 \times \mathbb{Z}_2$.  Every non-identity element has order $2$, but $|G| = 8$.

A: Take $\mathbb{Z}_2\times\mathbb{Z}_2$. It has no element of order $4$.

A: Try $S_{3}$ with $n=6$, where $S_{3}$ denotes the symmetric group on $3$ symbols

A: Perhaps the following is worth mentioning. If $n$ is prime, then Cauchy's theorem tells you that a finite group of order divisible by $n$ has an element of order $n$.
We will show

Suppose $n$ is not prime.  Then there is a group $G$ of order divisible by $n$, with no elements of order $n$.

If $n = p^{k}$ is a power of the prime $p$, with $k > 1$, then the direct product of $k$ groups of order $p$ will have order $n$, but all non-trivial elements will have order $p < n$.
If $n$ is not a power of a prime, but it is of the form $p^{k} m$, where $p$ is a prime, $k >1$, and $\gcd(p, m) = 1$, then the argument just used applies to show that there is a group of order $n$ with no elements of order $n$. First build a group $H$ of order $p^{k}$ with no elements of order $p^{k}$, and then take $G$ to be the direct product of $H$ by the cyclic group of order $m$.
If $n = p_{1} \cdots p_{k}$ is a product of $k > 1$ distinct primes, with $p_{1} < \dots < p_{k}$, consider the symmetric group $H$ on $p_{k}$ letters. It does not have an element of order $p_{1} p_{k}$, because if $a$ where such an element, then $a^{p_{k}}$ and $a^{p_{1}}$ would be commuting elements of order resp. $p_{1}$ and $p_{k}$. But an element of order $p_{k}$ is a $p_{k}$-cycle, and only commutes with its powers. Now take the direct product $G$ of $H$ by a cyclic group of order $p_{2} \cdots p_{k-1}$.

A: $S_4$ has order $24$ but no elements of order $6, 8, 12, 24$.

A: Maybe needless to say: if $G$ is a finite group then the following are equivalent.
(a) For all $d \mid |G|$ there is a $g \in G$ with $ord(g)=d$.
(b) $G$ is cyclic.
The proof is almost trivial. Hence, any finite non-cyclic group provides an example to the question.


text:
Q: Using JPA annotations with Hibernate to describe @OneToMany relationship where foreign key is only in child table I have an existing data model that I'm very happy with:
public class Garden {
    private String name; // "Oak Grove"
    private List<Plant> plants;
}

public class Plant {
    private String name; // "Cherry Tomato"
}

I would like to map this in Hibernate with the following conditions:

*

*The Plant class in Java does not maintain a reference to its parent Garden. This makes things more difficult in the Java tier, IMO.

*The PLANT table should have a GARDEN_ID column which is a foreign key to the GARDEN(ID) column.
My initial setup, prior to the @OneToMany addition:
@Entity(name = "GARDEN")
public class Garden {
    @Id
    @Column(name = "ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name = "NAME", nullable = false)
    private String name; // "Oak Grove"

    // Not yet mapped
    private List<Plant> plants;
}

@Entity(name = "PLANT")
public class Plant {
    @Id
    @Column(name = "ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name = "NAME", nullable = false)
    private String name; // "Cherry Tomato"
}

How can I define the @OneToMany annotation on the List<Plant> plants; in such a way that the foreign key reference is maintained in the Plant?
If I just add:
@OneToMany(cascade = { CascadeType.ALL })
@JoinColumn(name = "GARDEN_ID")
private List<Plant> plants;

Then saving a garden with a plant fails like so:
Caused by: org.h2.jdbc.JdbcSQLException: NULL not allowed for column "GARDEN_ID"; SQL statement:
insert into PLANT (NAME, ID) values (?, ?) [23502-191]

So it seems Hibernate isn't trying to persist the foreign key. Is there a way to accomplish this without completely mucking up my object model?
Edit: The way I'm testing this is with:
Garden garden = new Garden("Oak Grove");
garden.addPlant(new Plant("Cherry Tomato"));
gardenManager.save(garden);

In which the save() method looks very Hibernate-ey:
public void save(T item) {
    try (Session session = factory.openSession()) {
        Transaction transaction = session.beginTransaction();
        try {
            session.saveOrUpdate(item);
            transaction.commit();
        } catch (Exception ex) {
            System.out.println("Error occurred saving item: " + ex.getMessage());
            ex.printStackTrace();
            transaction.rollback();
        }
    }
}

A: Yogesh Sakurikar was close, but the bi-directional @JoinColumn was a bit off. Below you will see how to join bidirectionally or mono-riectionally
@Entity(name = "GARDEN")
public class Garden {
    @Id
    @Column(name = "ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name = "NAME", nullable = false)
    private String name; // "Oak Grove"

    // use this if you don't want a bi-directional relationship
    // @OneToMany
    // @JoinColumn(name = "ID", referencedColumnName="GARDEN_ID")
    // private List<Plant> plants;

    // use this if you want it bi-directional
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "garden")
    private Set<Plant> plants;
}

@Entity(name = "PLANT")
public class Plant {
    @Id
    @Column(name = "ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name = "NAME", nullable = false)
    private String name; // "Cherry Tomato"

    // use this if you don't want a bi-directional relationship
    // @Column(name="GARDEN_ID")
    // private long gardenId;

    // use this if you want a bi-directional relationship
    @ManyToOne
    @JoinColumn(name = "GARDEN_ID", referencedColumnName="ID", nullable = false)
    private Garden garden;

}

The code below assumes bi-directional relationship. Otherwise you'd need to know your Garden.id before you could fully describe any child Plant
Garden garden = new Garden("Oak Grove");
Plant plant = new Plant("Cherry Tomato")
plant.setGarden(garden); //don't forget to set the parent on the child
garden.addPlant(plant);
gardenManager.save(garden);

A: For one to many relationship, if the plant will going to hold the relationship, you need to define it using bi-direction.
Here is I think you should be able to achieve it:
@Entity(name = "GARDEN")
public class Garden {
    @Id
    @Column(name = "ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name = "NAME", nullable = false)
    private String name; // "Oak Grove"

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "garden")
    private List<Plant> plants;
}

@Entity(name = "PLANT")
public class Plant {
    @Id
    @Column(name = "ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column(name = "NAME", nullable = false)
    private String name; // "Cherry Tomato"

    @ManyToOne
    @JoinColumn(name = "GARDEN_ID", nullable = false)
    Garden garden;
}

This bidirectional approach will let entity manager know that there exists a relationship between the two and since on one side it is one to many, for other side it become many to one. Hope this will help.


text:
Q: Timeout when trying to create any terraform resource on localstack I am trying to set up localstack environment for lambda, but I can not create any resource. I used the official guide from https://github.com/localstack/localstack but every resource I try to create when perform terraform apply I got timeouts from the services.
Below I included example docker-compose and main.tf files which try to create s3 bucket. Also I tried to run examples from some github repositories and I also have this timeout problem.
Generally I see that localstack services are healthy and I can access them via for AWS cli. But I am stuck and do not know where the problem is.
access s3 via cli
aws --endpoint-url=http://localhost:4566 s3api list-buckets

{
    "Buckets": [],
    "Owner": {
        "DisplayName": "webfile",
        "ID": "bcaf1ffd86f41161ca5fb16fd081034f"
    }
}

docker-compose.yml
version: '2.1'

services:
  localstack:
    container_name: "${LOCALSTACK_DOCKER_NAME-localstack_main}"
    image: localstack/localstack:latest
    network_mode: bridge
    ports:
      - "4566:4566"
      - "4571:4571"
      - "${PORT_WEB_UI-8080}:${PORT_WEB_UI-8080}"
    environment:
      - SERVICES=${SERVICES- }
      - DEBUG=${DEBUG- }
      - DATA_DIR=${DATA_DIR- }
      - PORT_WEB_UI=${PORT_WEB_UI- }
      - LAMBDA_EXECUTOR=${LAMBDA_EXECUTOR- }
      - KINESIS_ERROR_PROBABILITY=${KINESIS_ERROR_PROBABILITY- }
      - DOCKER_HOST=unix:///var/run/docker.sock
      - HOST_TMP_FOLDER=${TMPDIR}
    volumes:
      - "${TMPDIR:-/tmp/localstack}:/tmp/localstack"
      - "/var/run/docker.sock:/var/run/docker.sock"

main.tf
provider "aws" {
  region = "us-east-1"
  access_key = "123"
  secret_key = "xyz"
  skip_credentials_validation = true
  skip_requesting_account_id = true
  skip_metadata_api_check = true
  s3_force_path_style = true
  endpoints {
    s3 = "http://localhost:4572"
  }
}

resource "aws_s3_bucket" "b" {
  bucket = "demo-bucket-terraform"
  acl    = "private"
}

terraform apply

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # aws_s3_bucket.b will be created
  + resource "aws_s3_bucket" "b" {
      + acceleration_status         = (known after apply)
      + acl                         = "public-read"
      + arn                         = (known after apply)
      + bucket                      = "demo-bucket-terraform"
      + bucket_domain_name          = (known after apply)
      + bucket_regional_domain_name = (known after apply)
      + force_destroy               = false
      + hosted_zone_id              = (known after apply)
      + id                          = (known after apply)
      + region                      = (known after apply)
      + request_payer               = (known after apply)
      + website_domain              = (known after apply)
      + website_endpoint            = (known after apply)

      + versioning {
          + enabled    = (known after apply)
          + mfa_delete = (known after apply)
        }
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_s3_bucket.b: Creating...
aws_s3_bucket.b: Still creating... [10s elapsed]
aws_s3_bucket.b: Still creating... [20s elapsed]
aws_s3_bucket.b: Still creating... [30s elapsed]
aws_s3_bucket.b: Still creating... [40s elapsed]
aws_s3_bucket.b: Still creating... [50s elapsed]
.
.
.


text:
Q: How to Create a UITextField to accommodate value in this following manner? I am developing an ios application that has two input fields that for entering date. I am planning to add a UIDatePicker in the following manner
[_datePicker setFrame:CGRectMake([UIScreen mainScreen].bounds.size.width-_datePicker.bounds.size.width, [UIScreen mainScreen].bounds.size.height-_datePicker.bounds.size.height, _datePicker.frame.size.width, _datePicker.frame.size.height)];
_inputText.inputView=_datePicker;
But the bigger problem is, I need it to look something like the image I have posted

How can I accomplish this?

A: Okay... there should be a couple ways to solve this.
1)
Put a transparent (or clear colored) UIButton over the view with the date labels.  You may need to make the view containing the labels change color/alpha something to indicate the button has been touched before bringing up the date picker.
2)
If the above doesn't work, try adding the view with the labels as a subview into UIButton.


text:
Q: Flash assembly to microcontroller I would like to program a microcontroller board directly in Assembly (any instruction set) in the most direct way. I don't want to use any IDE or bootloader code to handle the flashing. My aim is to flash a binary file containing the instructions, directly to memory and have the microcontroller boot from it.
I have noticed that many or the more popular microcontrollers have their own flash tools or very high level IDE interfaces to communicate to the microcontroller.
Can anyone suggest me a specific microcontroller and a method for transferring assembly code to microcontroller?

A: This is not an uncommon thing to do: you are looking for an assembler.  This can be done on any microcontroller.  All manufacturers provide tools to do this.  Often it is in the same package as those "high level" IDEs.  The IDE is merely running the command-line tools for you, whereas you will run them directly.
The easiest way to step into this is would be to use the standard bootloader and write your amount inline inside your C/CPP file using the "asm" directive.  Once you are practiced at it, you can then move to writing the assembly code in an .asm file and running the assembler instead of the C compiler.  Then you can skip the step of linking to the standard C libraries and standard bootloader, and flash the output directly to the microcontroller.
Supposing you chose Atmel, you could do this two ways:
The simplest would be to purchase a development board like the Arduino.  Next download the Arduino IDE to start with inline assembly.  Lastly download AVR Studio which is the full development platform.
The bare-metal way would be to purchase an Atmel microcontroller like the AtMega328p + a USB in-circuit programmer (ISP). Then download the AVR Studio.  Mount the chip on a breadboard and use the ISP to flash the chip using AVR Studio.
Hopefully I've given you enough keywords that you can find your way from here.


text:
Q: How to forecast many products forecasting together? I have data about sale as example follows:

Date
Product
Category
Sale
Promotion of product 1
Promotion of product 2
Promotion of product 3

01/01/2020
Product1
A
3
1
0
0

01/01/2020
Product2
A
4
0
1
0

01/01/2020
Product3
B
2
0
0
1

02/01/2020
Product1
A
7
1
0
0

02/01/2020
Product2
A
4
0
1
0

03/01/2020
Product1
A
2
0
0
0

03/01/2020
Product2
A
1
0
0
0

03/01/2020
Product3
B
9
0
0
1

Suppose I have 50 products and because of the hypothesis that the sale and promotion of one product can impact to others. So, I would like to forecast each product in parallelly. (I mean that model forecast whose the outputs are the sale of each product) What are the methods to solve this problem?

A: Similar questions have been asked and given fairly comprehensive answers here and here.
A few comments:

*

*The main keywords you will want to look for are i) 'Hierarchical Modeling' and ii) 'Panel Modeling'.

*

*Panel modeling is concerned with modeling multiple time series at once.

*Hierarchical modeling makes use that some products belong to the same category.

*If you have a large number of products, it may make sense to engineer the promotional features. For example, instead of having 1 column per product, maybe try columns like:

*

*Is this product on Sale?

*How many other products are on sale?

*Are products from the same category on sale?


text:
Q: Función para obtener un listado de directorios Quiero crear una función que me devuelva una lista de directorios como una array dentro de esta base de código:
public string[] obtenerListadoDirectorio(string directorio, string filtro)
{
    string[] devolver = null;
    listFicheros = devolver;
    return devolver;
}

El problema que se me presenta es que no sé que funciones/librerías debo usar.

A: Usando la libreria de System.IO con las funciones de Directory puedes obtener lo que buscas:
public string[] obtenerListadoDirectorio(string directorio, string filtro)
{
    string[] devolver = System.IO.Directory.GetDirectories(directorio, filtro);

    return devolver;
}

Puedes simplificar más las líneas de código poniendo el código de la siguiente forma:
public string[] obtenerListadoDirectorio(string directorio, string filtro)
{
    return System.IO.Directory.GetDirectories(directorio, filtro);
}


text:
Q: What happens when you remove a value from the middle of an array? If I have an array like this:
local array = {'foo', 'bar', 'baz'}

And I remove the second element like this:
array[2] = nil

Would this send array[3] and any larger index to the hash part of a table? Or does it just leave a hole in the array portion?

A: It will add a another border.
This has a few effects:

*

*you can no longer use ipairs to get all your elements as ipairs will stop at the first border

*the length operator # will no longer give you the number of elements in that table as it may return any border.

*table.concat will raise an error invalid value (nil) at index 2 in table for 'concat'

*some functions in the table library will no longer work for  values after the border

See

*

*length operator

*ipairs

*table manipulation

A: That leaves a hole.
Therefore exists: table.remove()
You have to specialize your tools than.
For example a tprint() that can handle it...
tprint=function(tab,...)
local args={...}
local start=args[1]
local stop=args[2]

if type(args[1])=='number' and type(args[2])=='number' then
 warn('Using numbers for table print out')
 for i=start,stop do
  io.write(string.format('%d = %s\n',i,tab[i])):flush()
  if start==stop then return tab[i] end
 end
else
 warn('Using pairs() for table print out')
 for key,value in pairs(tab) do
  io.write(string.format('%s = %s\n',key,value)):flush()
 end
end

end

Than you can do things like...
>tprint(arg)
Lua warning: Using pairs() for table print out
1 = -W
2 = -i
3 = -e
4 =  dofile('/root/lua/tprint.lua')
0 = /root/bin/lua
1618128658 = It is alive!!!
1618129059 = function: 0x566bf0f0
1618129084 = function: 0x566bfba0
1618128894 = tprint
>tprint(arg,1618128658,1618128658)
Lua warning: Using numbers for table print out
1618128658 = It is alive!!!
It is alive!!!

...or a sequence from 0 to 4 ...
>tprint(arg,0,4)
Lua warning: Using numbers for table print out
0 = /root/bin/lua
1 = -W
2 = -i
3 = -e
4 =  dofile('/root/lua/tprint.lua')

A: you can put remaining entries into a new list, to essentially close that gap
newarray = {}
for i = 1, #array do
    if array[i] then
        newarray[ #newarray ] = array[i]
    end
end

or nudge them all down one position, using multiple assignment to flip-flop entries ( index 3 into 2, 2 into 3... ) leaving that nil as the final entry, so things behave as expected.
for i = 1, #array do
    if not array[i] then
        array[i], array[i+1]  = array[i+1], array[i]
    end
end


text:
Q: What's the difference between not and ~ in python Just to check, I couldn't find anything about ~, so I want to make sure it's the same.
Also, can you use ! in python like in C++?
It seems that these two codes give the same output:
bool(~0)

bool(not 0)

A: This is how it is in Python.

'~' is a bitwise operator
whereas 'not' is a logical opeartor

A: You should read Python 3.10 documentation at Unary arithmetic and bitwise operations.

The ~ operator does a simple job:

Inverts the bits


text:
Q: How to verify AWS S3 bucket details is valid or not using Nodejs? In my application am having a form, in that user should enter their AWS S3 details. Before saving the details I have to check whether the account is correct or not. I am building this application using Node js,mongodb,Angular js.
UPDATE
aws s3 details are
{
       "aws": {
        "key": "",
        "secretkey": "",
        "region": "",
        "bucket_name": ""
    }

A: Using the AWS Javascript SDK you should make a headBucket request using the supplied credentials in the constructor.
const AWS = require('aws-sdk');
const s3 = new AWS.S3({ credentials, region });

s3.headBucket({
  Bucket: "examplebucket"
}, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
})

https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#headBucket-property
If the request is successful you have access.

A: If you have the user credentials then you can use aws-sdk which is available as node module.
set the credentials in sdk config and use S3 API to verify the given buckets.

npm install aws-sdk

var AWS = require('aws-sdk');
AWS.config = new AWS.Config();
AWS.config.accessKeyId = "accessKey";
AWS.config.secretAccessKey = "secretKey";
AWS.config.region = "region";

var s3 = new AWS.S3();

You can refer the site for better understanding

A: You can try making a s3 client using aws s3 sdk and then try calling method that your app needs to. For example if you need to create an object in the provided bucket, Then simply try making test object  and see if it works. You can pass stored credentials like in below links:
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/loading-node-credentials-json-file.html
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials-node.html
const AWS = require('aws-sdk');
const fs = require('fs');

AWS.config.update({ accessKeyId: '...', secretAccessKey: '...' });
//make sure you pass proper credentials
const s3 = new AWS.S3();
fs.readFile('test-file.txt', function (err, data) {
  if (err) { throw err; }
  var base64data = new Buffer(data, 'binary');
  const params = {
    Bucket: '...bucket-name-here...',
    Key: 'test-object.txt',
    Body: base64data
  };
  s3.putObject(params, function(err, data) {
    //check error or data to see if you have proper permissions.
  });
});

Also see these examples for putObject method:
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property
https://gist.github.com/homam/8646090


text:
Q: html legend tag explore not working center here explore .. not work

.
bottom is crome... correct

bottom is crome...
legend.scheduler-border {
width:inherit;
font-size: 1.8em !important;
font-weight: bold !important;
text-align: center !important;
}

fieldset.scheduler-border {
border: 1px groove #ddd !important;
padding: 32px 0 70px 2px;
margin: 0 0 1.5em 0 !important;
-webkit-box-shadow:  0px 0px 0px 0px #000;
        box-shadow:  0px 0px 0px 0px #000;
}

here code is line front legend tag

A: Just add:
legend {
  text-align: center;
}

A: Here is the simple Example of legend tag that align in center

<form>
  <fieldset>
    <legend align="center">Personalia:</legend>
    Name: <input type="text" size="30">

    Email: <input type="text" size="30">

    Date of birth: <input type="text" size="10">
  </fieldset>
</form>


text:
Q: array in my js file is not converting into JSON I am practicing code in node.js. I want to convert my array items into JSON format. I have also try body-parser but can't succeed.
var express=require('express');
var app= express();
var bodyParser= require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));

var items = [
{"id":"sd223",
"text":"food1"},

{"id":"sd12223",
"text":"food2"},

{"id":"s4d223",
"text":"food3"},

{"id":"s65d223",
"text":"food4"},

];

app.get('/',function(request,response)
{
    response.send(items);
});

app.listen(3000,function(){

    console.log("server 3000");
});

A: If you want to send the respond as json use response.json(items). If you simply want to convert it to JSON string use JSON.stringify(items)

A: body-parser is an npm module for parsing incoming request bodies.
If you would like to send your response as JSON, use response.json(items) as mentioned in another answer

A: I think you're looking for something like this:
response.header("Content-Type", 'application/json');
response.send(JSON.stringify(items, null, 4));


text:
Q: Matplotlib several subplots and axes I am trying to use matplotlib to plot several subplots, each with 2 y-axis (the values are completely different between the two curves, so I have to plot them in different y-axis)
To plot one graph with 2 y-axis I do:
fig, ax1 = plt.subplots(figsize=(16, 10))
ax2 = ax1.twinx()
ax1.plot(line1, 'r')
ax2.plot(line2, 'g')

To plot 2 subplots, one with each curve I do:
plt.subplot(2,1,1)
plt.plot(line1, 'r')
plt.subplot(2,1,2)
plt.plot(line2, 'g')

I can't manage to merge the two methods.
I wanted something like:
fig, ax1 = plt.subplots(figsize=(16, 10))
plt.subplot(2,1,1)
ax2 = ax1.twinx()
ax1.plot(line1, 'r')
ax2.plot(line2, 'g')
plt.subplot(2,1,2)
ax1.plot(line3, 'r')
ax2.plot(line4, 'g')

But this doesn't work, it just shows 2 empty subplots.
How can I do this?

A: You should create your subplots first, then twin the axes for each subplot.  It is easier to use the methods contained in the axis object to do the plotting, rather than the high level plot function calls.
The axes returned by subplots is an array of axes.  If you have only 1 column or 1 row, it is a 1-D array, but if both are greater than 1 it is a 2-D array.  In the later case, you need to either .ravel() the axes array or iterate over the rows and then axes in each row.
import numpy as np
import matplotlib.pyplot as plt

# create a figure with 4 subplot axes
fig, axes = plt.subplots(2,2, figsize=(8,8))

for ax_row in axes:
    for ax in ax_row:
        # create a twin of the axis that shares the x-axis
        ax2 = ax.twinx()
        # plot some data on each axis.
        ax.plot(np.arange(50), np.random.randint(-10,10, size=50).cumsum())
        ax2.plot(np.arange(50), 100+np.random.randint(-100,100, size=50).cumsum(), 'r-')

plt.tight_layout()
plt.show()


text:
Q: Send messages from firefox after loggedin I am working on an addon and I also have a website to which users login. Website authentication is based on Kerberos (protocol). Once the user logs into the website I want to send messages on behalf of user from addon. How do I send messages to the webserver on user's behalf.  Where are te authentication details saved for Kerberos authentication? DO I need to create headers myself for my messages to be accepted by the webserver?
I am planning to send the message from addon using javascript/jquery

A: Use an xmlhttprequest that uses cookies.
This one does the trick:
https://gist.github.com/Noitidart/9088113
example usage of it:
https://gist.github.com/Noitidart/9096743
this example here wont work for you because it makes execution WITHOUT the cookie I THINK
https://gist.github.com/Noitidart/11207278


text:
Q: Trouble using method get in php Hello my web page is hanging after executing this small part of the code.
It seems that is related to the use of the _GET table
<?php
  if(isset($_GET['radGr']))
  {
     $radGroup=$_GET['radGr']);
  }
?>

<form action='Exec3.php' method='get'>
<fieldset>
<legend>Operator</legend>
  <label>+
    <input type='radio' name='radGr'
    <?php if($radGr == 0){ echo 'Checked=checked' ;} ?>
    value=0 >
  </label>
  <label>-
    <input type='radio' name='radGr'
    <?php if($radGr == 1){ echo 'Checked=checked' ;} ?>
    value=1 >
  </label>
</fieldset>
<input type='submit' value='transfert'>
</form>

Do you see something wrong in my code ?
Thanks.

A: The variable $radGr does not exist, it should be $radGroup.
Change it in your php within the form.

A: It's because of ) near $radGroup=$_GET['radGr']);
just remove it.
and you can change your code to :
<input type='radio' name='radGr'
<?php echo(!empty($radGroup) && $radGroup == 0)? 'Checked=checked' : ''; ?>
value=0 >


text:
Q: When should I use UIImageJPEGRepresentation and UIImagePNGRepresentation for uploading different image formats to the server? In my application I have to send images of  different formats to the server (it must be all file formats that can be read by the UIImage class) https://developer.apple.com/library/ios/#documentation/uikit/reference/UIImage_Class/Reference/Reference.html
And the problem is: I don't know when I should use each of this methods. Of course it's obvious that for .png images I need to use UIImagePNGRepresentation and for .jpg/.jpeg UIImageJPEGRepresentation. But what about other formats (.tiff,.gif , etc.)? There are only two methods for image manipulations and so many formats.

A: You say:

Of course it's obvious that for .png images I need to use UIImagePNGRepresentation and for .jpg/.jpeg UIImageJPEGRepresentation.

No, that's not necessarily the case. If you have some original "digital asset", rather than creating a UIImage and then using one of those two functions to create the NSData that you'll upload, you will often just load the NSData from the original asset and bypass the round-trip to a UIImage at all. If you do this, you don't risk any loss of data that converting to a UIImage, and then back again, can cause.
There are some additional considerations, though:

*

*Meta data:
These UIImageXXXRepresentation functions strip the image of its meta data. Sometimes that's a good thing (e.g. you don't want to upload photos of your children or expensive gadgets the include the GPS locations where malcontents could identify where the shot was taken). In other cases, you don't want the meta data to be thrown away (e.g. date of the original shot, which camera, etc.).
You should make an explicit decision as to whether you want meta data stripped or not. If not, don't round-trip your image through a UIImage, but rather use the original asset.

*Image quality loss and/or file size considerations:
I'm particularly not crazy about UIImageJPEGRepresentation because it a lossy compression. Thus, if you use a compressionQuality value smaller than 1.0, you can lose some image quality (modest quality loss for values close to 1.0, more significant quality loss with lower compressionQuality values). And if you use a compressionQuality of 1.0, you mitigate much of the JPEG image quality loss, but the resulting NSData can often be bigger than the original asset (at least if the original was, itself, a compressed JPEG or PNG), resulting in slower uploads.
UIImagePNGRepresentation doesn't introduce compression-based data loss, but depending upon the image, you may still lose data (e.g. if the original file was a 48-bit TIFF or used a colorspace other than sRGB).
It's a question of whether you are ok with some image quality loss and/or larger file size during the upload process.

*Image size:
Sometimes you don't want to upload the full resolution image. For example, you might be using a web service that wants images no bigger than 800px per side. Or if you're uploading a thumbnail, they might want something even smaller (e.g. 32px x 32px). By resizing images, you can make the upload much smaller and thus much faster (though with obvious quality loss). But if you use an image resizing algorithm, then creating a PNG or JPEG using these UIImageXXXRepresentation functions would be quite common.
In short, if I'm trying to minimize the data/quality loss, I would upload the original asset if it's in a format that the server accepts, and I'd use UIImagePNGRepresentation (or UIImageJPGRepresentation with quality setting of 1.0) if the original asset was not in a format accepted by the server. But the choice of using these UIImageXXXRepresentation functions is a question of your business requirements and what the server accepts.

A: Rob points out a lot of very good things to consider when working with images (+1), however here is an example of how to create tiff's and gif's as you asked:
First, you need to link to the ImageIO library (under the Build Phases of your app).
Next you need to #import <ImageIO/ImageIO.h> at the top of your file.
Then, the following code will convert the image for you:
// Get a reference to the image that you already have stored on disk somehow.
// If it isn't stored on disk, then you can use CGImageSourceCreateWithData() to create it from an NSData representation of your image.
NSURL *url = [[NSBundle mainBundle] URLForResource:@"01" withExtension:@"jpg"];
CGImageSourceRef src = CGImageSourceCreateWithURL((__bridge CFURLRef)(url), NULL);

// Create a URL referencing the Application Support Directory.  We will save the new image there.
NSFileManager *fm = [NSFileManager defaultManager];
NSURL *suppurl = [fm URLForDirectory:NSApplicationSupportDirectory
                            inDomain:NSUserDomainMask
                   appropriateForURL:nil
                              create:YES
                               error:NULL];

// Append the name of the output file to the app support directory
// For tiff change the extension in the next line to .tiff
NSURL *gifURL = [suppurl URLByAppendingPathComponent:@"mytiff.gif"];

// Create the destination for the new image
// For tiff, use @"public.tiff" for the second argument of the next line (instead of @com.compuserve.gif".
CGImageDestinationRef dest = CGImageDestinationCreateWithURL((__bridge CFURLRef)gifURL,
                                                             (CFStringRef)@"com.compuserve.gif",
                                                             1,
                                                             NULL);
CGImageDestinationAddImageFromSource(dest, src, 0, NULL);

// Write the image data to the URL.
bool ok = CGImageDestinationFinalize(dest);
if (!ok)
    NSLog(@"Unable to create gif file.");

// Cleanup
CFRelease(src);
CFRelease(dest);

This was adapted from the code in this book.


text:
Q: Remove/hide Seearch Bar in Modern Sharepoint List How Can I remove delete/hide/get rid of a search bar in a Sharepoint List. I am not even sure why it is there. None of the regular pages have it. It only shows up in Document Libraries and List ( It is pretty useless because it doesn't return what is on the list - I do not need it and I would just rather remove it). I am okay with just disabling search on the whole Site - I just have no idea how.

A: I would wait for ~1 month. The search bar will move into the suitenav top and center. In general, modifying the DOM like you want to is not supported and will break in the future.


text:
Q: Как ускорить выполнение Выполнение GM Есть класс который служит для приведения фотографий к определенному стандарту 1024 х 756. ДЛя этого я использую GM.
Вопрос так ли я вызываю GM и как можно ускорить выполнение скрипта?
class CoreImgFiles {

private $files=[];
public $AllWaySavefiles=[];

public function __construct($allfiles)
{
   self::rewriteArray($allfiles);
   self::saveEvent();
}

private function rewriteArray($allfiles){

    $files = [];
    $file_count = count($allfiles['name'])-1;

    for($i=$file_count;$i>=0;$i--)
    {
        $files[] = $allfiles['tmp_name'][$i];
        unset($allfiles['name'][$i]);
        unset($allfiles['type'][$i]);
        unset($allfiles['tmp_name'][$i]);
        unset($allfiles['error'][$i]);
        unset($allfiles['size'][$i]);
    }
    unset($allfiles);
    return $this->files=$files;
}

private function minimilize($savefile){

    $image=new Gmagick($savefile);

    $width=$image->getimagewidth();
    $height=$image->getimageheight();

    $standartWidth='';
    $standartHeight='';
    $x='';
    $y='';

    if($width>$height) {

        $standartWidth=1024;
        $standartHeight=756;

        $masWidth=1300;
        $masHeight=900;

        $kw=$width/$masWidth;

        $wx=$width/$kw;

        $image->setCompressionQuality(80);
        $image->profileimage('*',null);
        $image->resizeimage($wx, $wx, null, 1, true);

        $x = (($masWidth - $standartWidth) / 2);
        $y = (($masHeight - $standartHeight) / 2);
    }

    if($width<$height) {

        $standartWidth=1024;
        $standartHeight=756;

        $koef=$width/1024;
        $wx=$height/$koef;

        $image->setCompressionQuality(80);
        $image->profileimage('*',null);
        $image->resizeimage($wx, $wx, null, 1, true);

        $x = 0;
        $y = $wx/7.75;

    }

    $image->cropimage($standartWidth, $standartHeight, $x,$y);
    $image->writeimage($savefile);
    $image->destroy();
}

private function saveEvent(){

    $event=mb_substr(sha1(date('YmdHis')), 0,10);

    $Head="img/"."$event";

    mkdir($Head,0777,true);
    chmod($Head, 0777);

    $AllWaySavefiles=[];

    $LengthDaunloadFiles=count($this->files)-1;

    for ($i=$LengthDaunloadFiles;$i>=0;$i--)
    {
        $newname = mb_substr(sha1(date('YmdHis',time()).mt_rand().$this->files[$i]),0,7).'.jpeg';

        $savefile=$Head.'/'."$newname";
        move_uploaded_file($this->files[$i],$savefile);
        unset($this->files[$i]);
        chmod($savefile, 0777);
        self::minimilize($savefile);
        $AllWaySavefiles[]=$savefile;
    }

    return  $this->AllWaySavefiles=$AllWaySavefiles;
}

}


text:
Q: How to Add multiple links Material Textfield How do I convert the text in MaterialUI TextField as Hyperlink TextField will be disabled when rendered, I have to display multiple links separated by comma some times.
{!this.state.disableEdit ? (
                  <TextField
                    multiline
                    rowsMax={15}
                    name="majorIncidentNumber"
                    variant="outlined"
                    label="MI Number"
                    defaultValue={impact.mi_number}
                    InputProps={{
                      readOnly: true,
                    }}
                  />
                ) : (
                  <TextField
                    multiline
                    rowsMax={15}
                    variant="outlined"
                    name="majorIncidentNumber"
                    label="MI Number"
                    defaultValue={this.state.majorIncidentNumber}
                    onChange={this.handleTextChange.bind(this)}
                    helperText="e.g. "MI0009164","MI00092345"
                  />
                )}

In the above code I want to display the {impact.mi_number} as hyperlinks, it is comma separated string. I can wrap entire thing  but it won't work when I have multiple links,

A: So impact.mi_number is like "link1,link2,link3"
I would use <Link> from Material-UI (or you can use TextField up to you)
import Link from '@material-ui/core/Link';

{impact.mi_number.split(",").map(link => (
  <Link>{link}</Link>
))}


text:
Q: Getting error as blank page when i click the mobile number which is responsive mode I add the following sample code
 +1 (555) 555-1212 for mobile number into clickable when the website into responsive mode. But i'm getting the error as blank page when i check into mobile. Is there any possible ways to do in wordpress.

A: You should remove // and instead callto://15555551212 it will be callto:15555551212


text:
Q: PHP Login Validation Issue
This is my PHP validation code

    include 'core/init.php';

if (empty($_POST) === false) {
  $username = $_POST['username'];
  $password = $_POST['password'];

    if (empty($username) === true || empty($password) === true) {
      $errors[] = 'Enter a valid username or password.';
    }
      elseif (user_exists($username) === false) {
        $errors[] = 'User does not exist.';
      }
      elseif (user_active($username) === false) {
        $errors[] = 'Please activate your account first.';
      }
      else {

        if (strlen($password) > 32) {
          $errors[] = 'Password too long.
';
        }

        $login = login($username, $password);

        if ($login === false) {
          $errors[] = 'Incorrect username or password.';
        }
          else {
            $_SESSION['user_id'] = $login; //login returns user_id
            header('Location: hashtagphotowall.php');
            exit();
          }
        }

    //visual representation of error arrays
    //print_r($errors);

}
  else {
    if (empty($errors) === false) {
      $_SESSION['validation_errors'] = $errors;
      header('Location: login.php');
    }
  }

This is my login form inside a modal

          <?php if(isset($_SESSION['validation_errors'])): ?>

              <?php output_errors($_SESSION['validation_errors']); ?>

          <?php endif; ?>

Sign In.

      Connect with Facebook

or login with email

        <form action="login.php" method="post">

            <input type="text" name="username" placeholder="Username:" />
            <input type="password" name="password" placeholder="Password:" />
            <input type="submit" name="loginbutton" class="button small" value="LOGIN" />

              <?php
                function output_errors($errors) {
                  echo '

' . implode('

', $errors) . '

';
                }
              ?>

        </form>

forgot your password? get help here.

        new user? sign up here.

      ×

I cannot achieve my goal which is "to display validation errors in the same place where my login form is located. For example, under the submit button." Before I arrived with this code, my first code outputs an error but not inline with the login form. It displays errors on another web page. So I revised it so that I can show errors under input tags or under the field box itself. But what's happening now with my code was when I hit the login button, it redirects to another web page with no results. Just plain white page. I used the header('Location: login.php'); which is the place where my php validation is located. When I changed it to where my login form is which is login-modal.php (take note that I used proper calling of dir, whatever you call it), it redirects to another page with NO foundation framework and CSS. Just plain login form. And also NO VALIDATION ERRORS DISPLAYED.
I am just a newbie with back-end web development so please bear with me. And also please help me. I have been stuck with this problem for long. Thank you. I highly appreciate your help.

A: Use jquery for same page updation 'AJAX'. Simple PHP codeing will not be effective.
When you use simple PHP it will work for reload purpose while if you use jquery it will work for refresh.


text:
Q: OpenGL memory management I have created an iOS application where I use GLKViews to realise an OpenGL environment. Now that everything works as expected, I have noticed that I get huge memory allocations and memory warnings as soon as I reinstantiate the view about three times over. Upon initialization I load textures like this:
  NSDictionary * options = [NSDictionary dictionaryWithObjectsAndKeys:
                              [NSNumber numberWithBool:YES],
                              GLKTextureLoaderOriginBottomLeft,
                              nil];

    NSError *error;
    topTexture = [GLKTextureLoader textureWithCGImage:[self imageWithView:v].CGImage options:options error:&error];
    if (error) {
        NSLog(@"Error loading texture from image: %@",error);
    }

and delete them (and the buffers) when the GLKView will disappear like this:
-(void)cleanUp{

    if(vertexArray != 0){
        glDeleteBuffers(1, &vertexArray);
        vertexArray = 0;
    }

    if( texArray != 0){
        glDeleteBuffers(1, &texArray);
        texArray = 0;
    }

    GLuint fT = frontTexture.name;
    glDeleteTextures(1, &fT);

    GLuint lT = leftTexture.name;
    glDeleteTextures(1, &lT);

    GLuint rT = rightTexture.name;
    glDeleteTextures(1, &rT);

    GLuint baT = backTexture.name;
    glDeleteTextures(1, &baT);

    GLuint boT = bottomTexture.name;
    glDeleteTextures(1, &boT);

    GLuint tT = topTexture.name;
    glDeleteTextures(1, &tT);

}

This is how they get drawn:
-(void)draw{

    [self.effect prepareToDraw];

    self.effect.texture2d0.enabled = YES;

    for(int i=0;i<6;i++){

        if(i==0)glBindTexture(GL_TEXTURE_2D, frontTexture.name);
        if(i==1)glBindTexture(GL_TEXTURE_2D, rightTexture.name);
        if(i==2)glBindTexture(GL_TEXTURE_2D, backTexture.name);
        if(i==3)glBindTexture(GL_TEXTURE_2D, leftTexture.name);
        if(i==4)glBindTexture(GL_TEXTURE_2D, bottomTexture.name);
        if(i==5)glBindTexture(GL_TEXTURE_2D, topTexture.name);
        glDrawArrays(GL_TRIANGLES, i*6, 6);
    }

}

Still, when I watch the allocations the live bytes go up 2 MB upon instantiation. Then when I remove the view the live bytes remain the same. So it seems the 2MB that are created are never released.

A: I assume you are testing this with ObjectAlloc, I don't think ObjectAlloc will see the OpenGLES related memory, Memory Monitor is more appropriate for this test.
Besides, there is no guaranty that the memory will be freed at the moment you call glDeleteTextures. The driver could defer this later.
You should use glFinish to make your test more accurate.
See zoul's post for more details : Understanding the memory consumption on iPhone


text:
Q: password_hash still hashes and stores an undefined variable I have a script which successfully writes to the database.
However, when I change the variable name $password1 or $password9 or $password34 and save the script, the script still works and a new entry in the DB appears with all the fields filled out including the password field.
$password0 = trim($_POST['password1']);
$hashed_passcode = password_hash($password4, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($q, 'ssss', $first_name, $last_name, $email, $hashed_passcode);

Above is an example, where I changed the variable to $password0. and when I hash it the variable is $password4. I resubmit the form and it still works. How can this be?

A: Reason being is that it will create a hash alright, it just won't store the hash associated with the actual password you want to store.
Having all error reporting set though, would have signaled an undefined variable.
Note: password_hash() only hashes passwords and does not show any type of error, that isn't its job to do that, it's the error handling on the server that does.


text:
Q: Want to replace string in js I want to replace ^ to ** in js but we try to use str.replace it only replaces a first one and rest string are same
 const input = "2^3+4^4";
    const replace = input.replace("^", "**");
    console.log(replace);

output :
2**3+4^4

but i want
2**3+4**4

A: You can use regex like this:
const input = "2^3+4^4";
const replace = input.replace(/\^/g, "**");
console.log(replace);

A: You can use regex with flag g which make the regex don't stop to the first occurrence.

const input = '2^3+4^4';

const replace = input.replace(/\^/g, '**');

console.log(replace); // output: 2**3+4**4

A: const replace = input.replace(/^/g, "**");

A: Try this:
const input = "2^3+4^4";
const replace = input.replace(/\^/g, "**");
console.log(replace);

The /g means it's "global" replacement.

A: const replace = input.split("^").join("**")


text:
Q: Adding multiple data to Tag Property of Checkbox I am currently working on a c# project where I need to add to bits of information to the tag property. I was hoping to create it via a class in the same sort of way as the List list array.
There are two strings that I need to add to the tag property, so can this be done.

A: Yes it can:
checkBox.Tag = new Tuple<string, string>("", "");
You can get the type out thus:
var stringPair = (Tuple<string, string>)checkBox.Tag;
As for what string you want, it depends on how you've put them in there.  This is where your own logic would decide.  Tuples expose the entries as properties of the relevant type, in this case you'll have two string properties.
Tag is an object, object's can contain whatever you like.  You just need to cast out.  Binding to this, on the other hand, might be a little difficult.


text:
Q: Using PHP from flash to email Image and Text I'm having a bit of trouble combining two things, sending text variables from flash and an image from flash. Here's what I do to email the image:
private function emailImage(imageToSend:MovieClip):void {
            trace("Sending Email");
            var data1:BitmapData = new BitmapData(imageToSend.width, imageToSend.height);
            data1.draw(imageToSend);

            var en:JPGEncoder = new JPGEncoder(80);
            var bArray:ByteArray=   en.encode(data1);

            var header:URLRequestHeader = new URLRequestHeader("Content-type", "application/octet-stream");

            var request:URLRequest = new URLRequest();
            request.requestHeaders.push(header);
            request.url = "http://192.168.1.117/mail.php";
            request.method = URLRequestMethod.POST;
            request.data = bArray;

            var loader:URLLoader = new URLLoader();
            loader.dataFormat = URLLoaderDataFormat.BINARY;
            loader.addEventListener(Event.COMPLETE, MailCompleteHandler);
            try
            {
                loader.load(request);
            }
            catch(error:Error)
            {
                trace("Unable to load URL");
            }
        }

And to email text variable I do this:
private function sendDataDB(Path:String) {
            var urlRequest:URLRequest = new URLRequest(Path);
            var loader:URLLoader = new URLLoader;
            urlRequest.method = URLRequestMethod.POST;
            var vars:URLVariables = new URLVariables;
            vars.cardID = cardID;
            vars.userName = userName;
            urlRequest.data = vars;
            loader.dataFormat = URLLoaderDataFormat.TEXT;
            loader.addEventListener(Event.COMPLETE,userDataStored);
            loader.load(urlRequest);
        }

But how do I do both, I want to send some text that would change for each user to be used as the body of the text and the email address but also send the picture to attach.
Thanks
EDIT:
Would it work to append data to the end of the URL:
request.url = "http://192.168.1.117/mail.php";

Not sure how to go about this, the correct format for the URL or how to read it in on the PHP side.

A: Yes, the solution will be to send the variables as GET, along with the image as POST. Add the variables to the end of the URL, for example "http://192.168.1.117/mail.php?cardID=" + cardID + "&userName=" + userName.
In your PHP file, you have a global $_GET variable, which will hold the variables passed via URL.
$cardID = $_GET["cardID"];
$userName = $_GET["userName"];

If you need more detail, you can read this post: Sending byteArray and variables to server-side script at the same time.
Hope this helps.


text:
Q: Loading content into TreeTable from database Primefaces TreeTable nodes seems to work in a reverse way.
You create a parent, then you create a child, than you tell the child what parent it belongs to. The parents should know their children, not the other way.
So... my problem is:
I need to load an undefined ammount of data from my database(grandparents, parents, children and grand children).
How to dinamically load them into the TreeTable? I can't think of a way inside my for-each to create TreeNodes and set it`s parents.
Anyone can give me and idea?

A: I haven't tested out this solution yet, but I think it should work. the examples on the primefaces showcase are all hard coded. To make it dynamic, You'll have to work with Arrays.

So for example the section of hardcoded code below:
 TreeNode documents = new DefaultTreeNode(new Document("Documents", "-", "Folder"), root);
 TreeNode pictures = new DefaultTreeNode(new Document("Pictures", "-", "Folder"), root);
 TreeNode music = new DefaultTreeNode(new Document("Music", "-", "Folder"), root);

Can be replaced with:
 Map<String, TreeNode> rootNodes = new HashMap<String, TreeNode>();

 //Retrieve the list of root Nodes. eg Tables in the database.
 for(Table table : databaseTables){

    //table.getTableName() will be the name of the node, it could be something like "music" or "documents"
    rootNodes.add(table.getTableName(), new DefaultTreeNode(table.getTableName(), new Document......, root);
 }

The reason I add them to the map is so that if you want to refer to them, you can use the key as a reference.
now If you want to add nodes to the pictures node for example
 //Create a new map
 Map<String, TreeNode> pictureNodes = new HashMap<String, TreeNode>();

 //now loop through your picture objects
for(picture : pictures){
    pictureNode.add(new DefaultTreeNode(picture.getName(), ......., root.get("pictures"));
}

Using this method, you can recursively loop through as many hierarchies as possible. I haven't been able to test this code (just notepad++) because I'm currently at the office. but try it out, if you're still stuck I can do something more detailed when I get home in a few hours.


text:
Q: How to remove an entry from nautilus context menu? I'd like to remove a specific menu entry on the nautilus right-click context menu - the "arrange alphabetically" option - since, being right after the "paste" entry, an imprecise click might produce a very disappointing mess among icons all over my desktop... as just happened once again minutes ago.
Is it possible to edit nautilus context-menu entries somehow?
Thanks everyone


text:
Q: Capitalization of Spanish month and day names in syslanguages Why does SQL Server capitalize month and day names when the language is set to Spanish?
The 'syslanguages' table contains the names as follows:
select langid, name, alias, months, days
from master..syslanguages
where alias in ('English', 'French', 'Spanish')

langid  alias    months                                                                                days
0       English  January,February,March,April,May,June,July,August,September,October,November,December     Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday
2       French   janvier,février,mars,avril,mai,juin,juillet,août,septembre,octobre,novembre,décembre      lundi,mardi,mercredi,jeudi,vendredi,samedi,dimanche
5       Spanish  Enero,Febrero,Marzo,Abril,Mayo,Junio,Julio,Agosto,Septiembre,Octubre,Noviembre,Diciembre  Lunes,Martes,Miércoles,Jueves,Viernes,Sábado,Domingo

As I understand it, convention is that the names of months and days should be lowercase in Spanish.  .NET's behaviour is consistent with this.  It doesn't seem that Microsoft is being consistent in this regard across their technology stack.
Any idea for the reason?

A: When I was in university Spanish, we capitalized month and day names just like in English.  Do you have a citation to suggest that that's incorrect?


text:
Q: Can the writematrix command in matlab specify the number of decimal places? The writematrix command can write matrices to text files. For example, for a matrix like the following
A = [1, 2, 3, 4];

It can be written to file a.txt using the writematrix command
A = [1, 2, 3, 4];
writematrix(A, 'a.txt', 'WriteMode', 'append', 'Delimiter', ' ');

The output is
1 2 3 4

But if I want the output like below
1.0000 2.0000 3.0000 4.0000

How do I go about using writematrix?

A: Convert A into a character array with num2str in the required format before using writematrix i.e.
writematrix(num2str(A,'%.4f '), 'a.txt', 'WriteMode', 'append', 'Delimiter', 'tab');

A: Converting into a character array did not work for me. Use this piece of code:
writematrix(round(A, 4), 'a.txt', 'WriteMode', 'append', 'Delimiter', ' ');


text:
Q: Cassandra partition keys organisation I am trying to store the following structure in cassandra.
ShopID, UserID , FirstName , LastName etc....

The most of the queries on it are
select * from table where  ShopID = ? , UserID = ?

That's why it is useful to set (ShopID, UserID) as the primary key.
According to docu the default partitioning key by Cassandra is the first column of primary key - for my case it's ShopID, but I want to distribute the data uniformly on Cassandra cluster, I can not allow that all data from one shopID are stored only in one partition, because some of shops have 10M records and some only 1k.
I can setup (ShopID, UserID) as partitioning keys then I can reach the uniform distribution of records in the Cassandra cluster . But after that I can not receive all users that belong to some shopid.
select *
from table
where ShopID = ?

Its obvious that this query demand full scan on the whole cluster but I have no any possibility to do it. And it looks like very hard constraint.
My question is how to reorganize the data to solve both problem (uniform data partitioning, possibility to make full scan queries) in the same time.

A: In general you need to make user id a clustering column and add some artificial information to your table and partition key during saving. It allows to break a large natural partition to multiple synthetic. But now you need to query all synthetic partitions during reading to combine back natural partition. So the goal is find a reasonable trade-off between number(size) of synthetic partitions and read queries to combine all of them.
Comprehensive description of possible implementations can be found here and here
 (Example 2: User Groups).
Also take a look at solution (Example 3: User Groups by Join Date) when querying/ordering/grouping is performed by clustering column of date type. It can be useful if you also have similar queries.

A: Each node in Cassandra is responsible for some token ranges. Cassandra derives a token from row's partition key using hashing and sends the record to node whose token range includes this token. Different records can have the same token and they are grouped in partitions. For simplicity we can assume that each cassandra nodes stores the same number of partitions. And we also want that partitions will be equal in size for uniformly distribution between nodes. If we have a too huge partition that means that one of our nodes needs more resources to process it. But if we break it in multiple smaller we increase the chance that they will be evenly distirbuted between all nodes.
However distribution of token ranges between nodes doesn't related with distribution of records between partitions. When we add a new node it just assumes responsibility for even portion of token ranges from other nodes and as the result the even number of partitions. If we had 2 nodes with 3 GB of data, after adding a third node each node stores 2 GB of data. That's why scalability isn't affected by partitioning and you don't need to change your historical data after adding a new node.


text:
Q: Temperamental mac mini 2011 running ubuntu 18.04 rejects SOME screens So, I have a Mac Mini 2011 that I rescued and ubuntu'd (18.04).
I platformed it at my father's place, and it worked wonderfully with his 1920xsomething, huge, fairly new, but still VGA, screen, which I used with the DisplayPort-VGA adapter.
Anyway, I took the thing to my place, went to hook it up to one of my several LCD screens (All my monitors are VGA.).
The monitor seemed totally unaware that the mac was booting up. and it wasn't like the problem was the screen itself, since I could plug it to my laptop, and it worked fine.
I repeated this with another LCD screen, same result, it was like plugging my vga port on to a toaster.
I was starting to worry I had broken the Mac on my way home.
Then I repeated the process, plugging the Mac to a way older LCD I had around, the LCD was broken, displaying only rainbow lines, or solid colors, at times, BUT it could clearly "sense" that the Mac was emitting a signal.
Extremely tired of this, I was thinking that it had something to do with resolution, "resolution", the way that word echoed in my mind it instantly made me go fetch an old CRT I have around.
The CRT works, in the sense that it displays the image being sent by my Mac. It's massively redshifted, but it works.
Then, to my despair, I found out that, actually, what's being projected onto the CRT is not some crazy HD that the poor thing swallows up, it's just 1024x768 @ 60 FPS.
That got me thinking "it must be the framerate??", so I created an xrandr config at 30 FPS, activated it, and straight up lost signal in the CRT. I know it's temporary unless I add it to my profile, but understandably, I wanna know if I'm even on the right track.
Why does my Mac Mini seem to reject SOME VGA monitors for factors that are absolutely beyond me? any ideas?


text:
Q: How would my Java program process a JS file to extract function names?
Possible Duplicate:
How to get method name from JavaScript file

I want to fetch Java Script function name in my Java file.I mean i want some solution so that i can go traverse my JS File,find out function name & list out them in my Java file.Is there any way so that i link my JS File,its function name with Java?

A: You need to parse the javascript file.  You can try to use the parser from Rhino, a quick google search shows this thread discussing how to do it.


text:
Q: Plot draws different curves in same colour even using Evaluate I would like the solutions of FindRoot (using NIntegrate under  it) to be drawn in different colours by Plot, like in the last plot but without defining a separate function for each element in the solution list of FindRoot:
Clear[w, x, y, z, plt1, plt2, plt3, w1, w2]
w[x_?NumericQ] := {y, z} /.
   FindRoot[{x*Exp[y] - y,
     x*(Exp[z] - z)}, {{y, 0.45, 0, 1}, {z, 0.52, 0, 1}}];
plt1 = Plot[w[x], {x, 0, 1}, Evaluated -> True];
plt2 = Plot[Evaluate[w[x]], {x, 0, 1}];
w1[x_?NumericQ] := w[x][[1]]
w2[x_?NumericQ] := w[x][[2]]
plt3 = Plot[{w1[x], w2[x]}, {x, 0, 1}];
GraphicsRow[{plt1, plt2, plt3}]

Is there some simple plot option that does this? Evaluate as in this question does not seem to work for me.
Mathematica 11.3 on Ubuntu 18.04.

A: There is an easy way to do this by making use of the function SetOptions. It allows one to modify the default options for any function. For the function Plot, its color is decided with the option PlotStyle. You can change this option to any other value globally using SetOptions.
SetOptions[Plot, PlotStyle :> RandomColor[]];

Note that I have used RuleDelayed instead of Rule. This is the key solution to your problem. When RuleDelayed is used, RandomColor[] is evaluated every time Plot is called, and thus the generated plot is of a different color. However, there are some rare cases when the subsequent output of RandomColor[] might be of a similar shade but I suppose you can figure out how to get around that.
So, after evaluating the above code, here is the output to your code:

A: Clear["Global`*"]

w[x_?NumericQ] := {y, z} /.
   FindRoot[{x*Exp[y] - y,
     x*(Exp[z] - z)}, {{y, 0.45, 0, 1}, {z, 0.52, 0, 1}}];

Evaluating w[x] with a symbolic input doesn't generate a List because w[x] is only defined for a numeric input.
Evaluate[w[x]]

(* w[x] *)

Since neither Evaluate nor the option Evaluated -> True has any effect on a symbolic w[x], there is only one PlotStyle
You don't need to define separate functions, but you do need to explicitly list both parts of w for when it has numeric values.
Plot[{w[x][[1]], w[x][[2]]}, {x, 0, 1},
  PlotLegends -> Placed[{"y", "z"}, {.2, .8}]] // Quiet


text:
Q: Can't load contextConfigLocation class on ServletContextHandler from a Service Class I have a project with Spring and several services. I'm trying to include a bunch of rest services in it. The thing is the embedded jetty server is within a @Service instance and for many reasons I can't touch it. So, I've tried to configure that server with my new requirements and I can't.
I've tried for discard with the classic approach outside the project logic, and it works:
public class Starter {
public static void main( final String[] args ) throws Exception {
    Server server = new Server( 8888 );

    // Register and map the dispatcher servlet
    final ServletHolder servletHolder = new ServletHolder( new CXFServlet() );
    final ServletContextHandler context = new ServletContextHandler();
    context.setContextPath( "/" );
    context.addServlet( servletHolder, "/rest/*" );
    context.addEventListener( new ContextLoaderListener() );

    context.setInitParameter( "contextClass", AnnotationConfigWebApplicationContext.class.getName() );
    context.setInitParameter( "contextConfigLocation", AppConfig.class.getName() );

    server.setHandler( context );
    server.start();
    server.join();
}

}
But, if I try to make the same thing within a spring context Service it doesn't work.
If I use the same initialization inside it, I get:
WARN  Can't find the the request for http://localhost:8888/rest/api/people's Observer

I've tried to modify  in applicationContext.xml to include rest needed classes but in that case the /api/ resource was registered twice.
I'm sure I'm not understanding something :)

A: Found it!
@Bean
@DependsOn( "cxf" )
public Server jaxRsServer() {
    JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class );
    factory.setBus(cxf()); // <-- THIS!
    factory.setServiceBeans( Arrays.< Object >asList( peopleRestService() ) );
    factory.setProviders( Arrays.< Object >asList( jsonProvider() ) );
    return factory.create();
}


text:
Q: Django admin page, user dropdown shows (None) when adding record, any idea? I have two model, both of them inherit from AbstractNonEntity, like
class BR(AbstractNonEntity):
   ...

class MS(AbstractNonEntity):
   ...

And class AbstractNonEntity is defined like below
class AbstractNonEntity(GlobalIDMixin, CreatedOnMixin):

creator = models.ForeignKey(User, related_name='%(class)s_created_objects',
                            verbose_name='Creator')
   ...

On admin page, when I add BR class, the creator show user drop-down, but when I add MS class, the creator only shows (None) and no drop-down.


text:
Q: c# windows form context menu control doesn't disappear fully it's hard to explane my problem with words, so I will try with words and images :)
I have context menu control in my win form app (ms visual studio project).
It doesn't disappear fully, a part from it stays over my panel control, it's custom panel class (with bordercolor property). The problem occurs only on Windows XP, not on Windows 7.

2. source code:
public class MyPanel : Panel
{
    private System.Drawing.Color colorBorder = System.Drawing.Color.Transparent;

    public MyPanel()
        : base()
    {
        this.SetStyle(ControlStyles.UserPaint, true);
        this.BorderStyle = BorderStyle.None;
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        e.Graphics.DrawRectangle(new System.Drawing.Pen(
            new System.Drawing.SolidBrush(colorBorder), 2), e.ClipRectangle);
    }

    protected override void OnResize(EventArgs e)
    {
        Invalidate();
    }

    public System.Drawing.Color BorderColor
    {
        get
        {
            return colorBorder;
        }
        set
        {
            colorBorder = value;
        }
    }
}

How to resolve this problem? I can add Invalidate() for the panel (to redraws it) when context menu closed event occurs, but I would like to know why exactly this problem occurs, is it some .NET Framework bug?

A:     e.Graphics.DrawRectangle(new System.Drawing.Pen(
        new System.Drawing.SolidBrush(colorBorder), 2), e.ClipRectangle);

Your code in fact asked the Graphics class to draw that rectangle.  You used the ClipRectangle property, it represents the bounding rectangle around the parts of the window that need to be repainted.  Which was just that intersection between the panel and the context menu.  What you meant to draw was a rectangle around the entire panel.  Or just a line that separates the panel from the toolstrip, it isn't clear.  Guessing at the line as the desired outcome:
protected override void OnPaint(PaintEventArgs e) {
    base.OnPaint(e);
    using (var pen = new Pen(colorBorder, 2)) {
        e.Graphics.DrawLine(pen, Point.Empty, new Point(this.ClientSize.Width, 0));
    }
}


text:
Q: What are the values assigned to a and b? int main()
{
    int a=1,2;
    int b=(3,4,5);
    printf("%d\n",a+b);
}

As execution starts from the main function then it will read the a variable value. I am confused about what value a will take. What value will b take?

A: 1) You can only assign one value to a variable of type 'int'
2) The line int a=1,2 will throw an error during compilation
3) The variable b will be set with the last value in your statement (3, 4, 5)
Try running this code and testing for yourself:
int main() {
  int a=1;
  int b=(3,4,5);
  printf("Value of a   [%d]\n", a);
  printf("Value of b   [%d]\n", b);
  printf("Value of a+b [%d]\n", a+b);
}


text:
Q: How can I lock a file in .net so that only my app can access it? I read queries regarding file locking but either they refer to multiple file access problem or something else.Ususal response to this would be lock to the file using FileStream.Lock,using FileShare.None with File.Open etc, but locking say a 100 files is not a good programming practice,also in these scenarios the lock will be released if my app closes/crashes which I don't want also  i.e. I want the lock to persist and only my app can open it for others.
On msdn I found System.Security,System.Security.AccessControl namespaces,I believe these might help.Also this article will shed some light on what I want.
EDIT::
Mannnnn... did anyone referred the "this"  link I provided.
Ok...in short I want something what PC Security software does.Does that ring a bell...anyone used it????
Thanks.

A: This just isn't possible.  A user with sufficient privileges can always alter security settings and run a program to access your file.  So, work from the assumption that you cannot stop this and focus on what the program or the user could do with the data in the file.
Encrypt it.

A: There's a basic flaw in your requirements here and that is that the file system only has one method of preventing access to a file, and that is through the ACL. You can specify that the user that logs on to the system doesn't have access rights to those files, and thus the files are not available to him.
However, in order for your program to be able to access those files, you need to set up a user that "logs on" in order to run your program, and of course any other programs configured to run as that user will have access to those files.
Other locks, like open the file for exclusive access, is as you've already discovered only effective when the program is running. If for any reason the program isn't running, those types of locks aren't in place.
What specifically are you trying to prevent? There might be other ways to handle that than to try to lock away the files.

A: You could encrypt the file and embed the key within your application. It depends on what you mean by "only my app can open it for others".

A: I would recommend using the IsolatedStorage class. There you can store a file which is directly "linked" to your application.
Have a closer look to it in MSDN IsolatedStorage. You may use a file assembly scoped. Anyway each user MAY navigate through the file system to your applicationData folder and open this file manually (although it is rather unexpected)

A: You are trying to find a way to implement a method ("lock" the files) and not to achieve a goal.
I assume that you want to hold some private data and optionally provide access to your data to other applications. In this case you need an encrypted container, which can be exposed to other applications, for example via a virtual disk (our SolFS OS edition is an optimal variant in this case).
However, the problem is that the key will be held in your application's code, and theoretically can be extracted and used to access the container. Practically the procedure can be made more complicated, but this is not a 100% bulletproof solution.

A: I think the thing which you want can only possible by using file system minifilter driver. as many other application provide this functionality by using driver like universal shield in which you can make process as trusted so only trusted process can access that file/folder an other application like folder protect which also provide such type of permission on file/folder..


text:
Q: Ruby on Rails Date Field Validation I'm working on this project for a class and one of the requirements is "Validation on the date field type".
For example, I did:
rails g scaffold Tasks id:primary_key description:string due:date

What would I add to the model so I can validate the date?
I've tried multiple different "solutions" and nothing seems to be working.

A: In your model, you can define a custom method to handle your validations.
class Task < ActiveRecord::Base
  validate :check_due_date

  def check_due_date
    # You can now check the "due" field here. For example, if you only want to allow due
    # dates today and later:

    if due < Date.today
      errors.add(:due, "can only be today or later.")
    end
  end
end

A: You could use the simple "validates timeliness" plugin: https://github.com/adzap/validates_timeliness/
Then use the following syntax:
class Task < ActiveRecord::Base
  validates_date :due
end

Unless plugins aren't allowed, in which case the other answer (creating your own validator) would be more suitable.