Processing math: 15%

Ярлыки

пятница, 9 августа 2013 г.

mongodb replicaset localhost

How I set "localhost" to replicaSet host where "rs0" is name of my replicaSet:
use local
cfg = db.system.replset.findOne({_id:"rs0"})
cfg.members[0].host="localhost:27017"
db.system.replset.update({_id:"rs0"},cfg)
then restart mongo

понедельник, 22 июля 2013 г.

How we can get sets from elements of different groups?


This task may be present as LP problem.
So, let n(i) - count of elements in group im(j) - volume of cell number j. Our goal is to fill all calls with condition: there are elements from different groups in each cell.
Let X(i,j) - count of element that from group  i and put into cell j.
Our main goal is maximize sumX(i,j) for all j with follow constraints:
1)    upper bound for elements count from each group:
sumjX(i,j)<=ni for all i;
2)    upper bound for volume of each cell:
sumi(X(i,j))<=m(j) for all j;
3) there are elements from the same group no more than t in each cell :
X(i,j)<=t for all i и j.

PyQt: create components dinamically


What to do: create some number of cells like matrix n by m.


1) we create ScrollArea in *.ui file, and QWidget under it:

<widget class="QScrollArea" name="scrollArea">
          <property name="mouseTracking">
           <bool>true</bool>
          </property>
          <property name="verticalScrollBarPolicy">
           <enum>Qt::ScrollBarAlwaysOn</enum>
          </property>
          <property name="horizontalScrollBarPolicy">
           <enum>Qt::ScrollBarAlwaysOn</enum>
          </property>
          <property name="widgetResizable">
           <bool>true</bool>
          </property>

          <widget class="QWidget" name="contents">
           <property name="geometry">
            <rect>
             <x>0</x>
             <y>0</y>
             <width>788</width>
             <height>223</height>
            </rect>
           </property>
          </widget>
         </widget>


2) my code:

class mainWindowQtGui.QMainWindow, UIclass.Ui_MainWindow:
    def __init__self, win_parent = None:
        QtGui.QMainWindow.__init__self, win_parent
        self.setupUiself
        #create QGridLayout on the first start
        self.scrollArea.widget.layout = QtGui.QGridLayout
        self.scrollArea.widget.layout.objectName='inputLayout'
        # create cells for input data
        self.connectself.createCells, QtCore.SIGNAL("clicked("), self.createCellsFunc)

    # function for create cells:
    def createCellsFuncself:
        # all was doing if we know number columns and number rows
        if strself.text1.toPlainText().isdigit and strself.text2.toPlainText().isdigit:
            # height and length for each cell
            h=25
            l=50
            # delete all old objects exclude layout
            for u in self.scrollArea.widget.children:
                if u.objectName!='inputLayout':
                    # "delete some later"
                    u.deleteLater
                    # hide now
                    u.hide
                    # set window as parent not ScrollArea
                    u.setParentself
                
            # number of columns
            hCount=intself.text1.toPlainText()
            # number of rows
            vCount=intself.text2.toPlainText()

            for i in range0,hCount:
                for j in range0,vCount:
                    # while creating insert text '0' and determine parent
                    textArea = QtGui.QTextEdit'0', self.scrollArea
                    # we give name to the element for fast find him
                    textArea.objectName = 'a'+stri+'-'+strj
                    # dimentions
                    textArea.setMinimumSizel,h
                    textArea.setMaximumSizel,h
                    # add created element to layer of widget textArea - adding object, (j + 1 and i + 1 - coordinates on layer grid of adding object)
                    self.scrollArea.widget.layout.addWidgettextArea,j+1,i+1
            # put layer to widget
            self.scrollArea.widget.setLayoutself.scrollArea.widget(.layout)
            self.scrollArea.widget.layout

3) get data from cells:

            #horizontal cells count
            hCount=intself.text1.toPlainText()
            #vertical cells count
            vCount=intself.text2.toPlainText()
            #check for all child objects "ScrollBox": did all data is number?
            for u in self.scrollArea.findChildrenQtGui.QTextEdit:
                try:
                    floatstr(u.toPlainText())
                except:
                    self.labelWarning.setTextQtCore.QString(u'Some data is not number')
                    return None
            
            #put data to array
            a,a0=list,list
            for j in range0,vCount:
                for i in range0,hCount:
                    for u in self.scrollArea.findChildrenQtGui.QTextEdit:
                        if u.objectName=='a'+stri+'-'+strj:
                            a0.appendfloat(u.toPlainText())
                a.appenda0
                a0=list

четверг, 21 марта 2013 г.

use mosek for solve LP in Python


#import module
import mosek
#import numpy arrays or mosek arraystry:    from numpy import array,zeros,ones
except ImportError:
    from mosek.array import array, zeros, ones
# stream for collect data from MOSEKdef streamprintertext:    sys.stdout.flush     #main functiondef main (bkc,blc,buc,bkx,blx,bux,csub,cval,asub,acof,ptrb,ptre,niv,ntc):  # create mosek environment  env = mosek.Env   # add stream to environment  env.set_Stream mosek.streamtype.log, streamprinter    # create task  task = env.Task0,0  # add output-data stream to task  task.set_Stream mosek.streamtype.log, streamprinter
#there are examples of creation right part of constraints and variable constraints#  bkc = mosek.boundkey.up, mosek.boundkey.lo  #  blc =               -inf,              -4.0 
#  buc =              250.0,               inf 
#  bkx = mosek.boundkey.lo, mosek.boundkey.lo 
#  blx =                0.0,               0.0 
#  bux =                inf,               inf 
#coefficients of goal function#  c   =                1.0,               0.64
#coeff numbers in constraints
#  asub =   array([0,   1),    array[0,    1]   ]
#...and this values
#  aval = array([50.0, 3.0), array[31.0, -2.0] ]
#number of variables  numvar = lenbkx
#number of constraints  numcon = lenbkc
  # create constraints
  task.appendmosek.accmode.con,numcon
  # create variables
  task.appendmosek.accmode.var,numvar
  # The goal function adding csub - numbers of variables, cval - coefficients of variables
  task.putcfix0.0  task.putclistcsub,cval
  # add constraints  task.putboundslice(mosek.accmode.con,                     0, numcon,
                     bkc, blc, buc)
  # add variable constraints  task.putboundslice(mosek.accmode.var,                     0, numvar,
                     bkx, blx, bux)
  # Input non-zero elements of matrix A by column  for j in rangenumcon:
      aptrb,aptre = ptrbj,ptrej
      task.putavecmosek.accmode.con,j,                    asub[aptrb:aptre],                    acof[aptrb:aptre]
  # input optimize criterion minimize/maximize  task.putobjsense(mosek.objsense.minimize)    # integer variables  numlist=list
  typelist=list
  for i in rangeniv,numvar:
      numlist.appendi
      typelist.appendmosek.variabletype.type_int
  task.putvartypelistnumlist,typelist
   
  # constants of begin solve   task.putintparam(mosek.iparam.mio_construct_sol,                   mosek.onoffkey.on);
  # all variable are unknown in begin of solve   task.makesolutionstatusunknown(mosek.soltype.itg);
 #we can save task in some file #task.writedata"test.lp"   # solve task  task.optimize
  # output solution
  if task.solutiondefmosek.soltype.itg:
      ...

среда, 20 марта 2013 г.

Python: your time to each program Windows

Script that write how many time each program used in Windows by title of show window.


import sys

#module for work with windows 32bit
import win32gui

txt=''
time1=time.time
#times dictionary
appdict=dict
while True:
#pause (it's influence to accuracy)
    time.sleep5
#title of the current window
    newtxt = win32gui.GetWindowText(win32gui.GetForegroundWindow)
#if window was changed than update time of beginning work with other window
    if txt!=newtxt:
        time2=time.time
#add previous time to dict
        if appdict.gettxt!=None:
            appdicttxt=appdicttxt+roundtime2,0-roundtime1,0
        else:
            appdicttxt=roundtime2,0-roundtime1,0
        txt=newtxt
        time1=time.time
    f=open'timerep.csv', 'w'
    csvwr = csv.writer(f, delimiter=';',lineterminator='\n')
#We write only window that summary time over 5 minutes (Other window is non-influential).
    for i in appdict.items:
        if i1>=300:
            csvwr.writerowi
    f.close

вторник, 19 марта 2013 г.

static in Apache simple


static in Apache:


We must write next string in file apache2.conf:
Alias /media/ "/home/username/mysite/media/"
first arg - link to get images, second arg - full path to storage images folder.

Than we can write in code link to the image:
<img src="/media/my_image1.jpg" />

понедельник, 18 марта 2013 г.

using GLPK in Python Linear programming


# import PuLP's functions

from pulp import *

# create new task of Linear programming LP with maximize of the goal functions
prob = LpProblem"Knapsack problem", LpMaximize

# variable integer
x1 = LpVariable"x1", 0, 10, 'Integer'
x2 = LpVariable"x2", 0, 10, 'Integer'
x3 = LpVariable"x3", 0, 10, 'Integer'

goal function ("the cost of all in backpack")
prob += 17*x1 + 30*x2 + 75*x3, "obj"

# constraints "weight of the backpack"
prob += 1.5*x1 + 2.5*x2 + 6*x3 <= 20, "c1"

# run solver
prob.solve

# print task status
print "Status:", LpStatusprob.status

# print optimized variable result
for v in prob.variables:
    print v.name, "=", v.varValue

# print value of goal function
print "objective = %s$" % value(prob.objective)

Alternate:
we can create LP-file CPLEX and use it with GLPK:

    cmd=['glpsol.exe','--cpxlp',outputname,'-o',solfile]
    p = subprocess.Popencmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE
    for line in p.stdout:
        print">>>>> " + str(line.decode().rstrip)

PyQt: show SVG

#scale increase 
self.connectself.incScaleButton, QtCore.SIGNAL("clicked("),lambda who="incScale": self.incScale)
 #scale decrease 
 self.connectself.decScaleButton, QtCore.SIGNAL("clicked("),lambda who="decScale": self.decScale)
 #create Scene for show diagrams
 self.sc=QtGui.QGraphicsSceneself.graphicsView

 def incScaleself:
     self.scale+=0.1
     self.printGDPscale=self.scale

 def decScaleself:
     self.scale-=0.1
     self.printGDPscale=self.scale

 #show diagram: 
 filename=fileArraytfileNumber
 #create object for SVG modification 
 r=QtSvg.QSvgRenderer
 #load data 
 r.loadQtCore.QByteArray(arrayToSave)
 #change rectangle for our image 
 r.setViewBoxQtCore.QRectF(0.0, 0.0, 3200.0, 2000)
 #create additional element
 item=QtSvg.QGraphicsSvgItem
 #put our image into it 
 item.setSharedRendererr
 #change scale
 item.setScale1.0
 #clear Scene, change size of it 
 self.sc.clear
 self.sc.setSceneRectQtCore.QRectF(0.0, 0.0, 3200.0, 2000)
 #change position of item into Scene 
 item.setPosQtCore.QPointF(10,50)
 #add item to Scene 
 self.sc.addItemitem
 #for QGraphicsView set Scene, define "view point" 
 self.graphicsView.setSceneself.sc
 self.graphicsView.centerOn0,0

create JAR in Eclipse

1. Project import Import files as existing project File → Import... → Existing Projects into Workspace. 2. Creating JAR Context menu on project folder > Export... > Java/JAR file. Than we change path and name of JAR in field "Select the export destination". 3. Some error Error: "JAR creation failed. See details for additional information". Details: Resource is out of sync with the file system: /projectName/.svn/entries Solution: Context menu on project folder > Refresh

add cirillic language to TEX Ubuntu

install follow packages in Ubuntu and use "utf8x": texlive-lang-cyrillic texlive-latex-extra \usepackageutf8x{inputenc}