id
stringlengths
36
36
text
stringlengths
1
1.25M
ad1e3bea-6115-4baa-afda-f529e636da31
private void updateTextPane(final String text) { SwingUtilities.invokeLater(new Runnable() { public void run() { Document doc = mExpertAnswerRootPane.getDocument(); try { doc.insertString(doc.getLength(), text, null); } catch (BadLocationException e) { throw new RuntimeException(e); } mExpertAnswerRootPane.setCaretPosition(doc.getLength() - 1); } }); }
02af6615-48af-45fd-a514-a6dcf5fd346e
public void run() { Document doc = mExpertAnswerRootPane.getDocument(); try { doc.insertString(doc.getLength(), text, null); } catch (BadLocationException e) { throw new RuntimeException(e); } mExpertAnswerRootPane.setCaretPosition(doc.getLength() - 1); }
94c0dd63-69f4-4c72-9ea7-dabeed805cd5
public void actionPerformed(ActionEvent e) { mExpertAnswerRootPane.setText(""); mOnQueryRequestedListener.onPrologQueryRequested( obtainPrologPreconditions(), RootFrame.this); }
93ba9419-cb6e-4404-b6e6-7d9e109e8c61
private List<PrologModelApplicable> obtainPrologPreconditions() { List<PrologModelApplicable> returnList = new ArrayList<PrologModelApplicable>(); for (JComboBox<PrologModelApplicable> comboBox : mPrologContentComboBoxes) { if (comboBox.getSelectedIndex() < 0) continue; PrologModelApplicable currentPredefinedPredicate = ((PrologModelApplicable) comboBox.getSelectedItem()); if (currentPredefinedPredicate == null) continue; returnList.add(currentPredefinedPredicate); } return returnList; }
cb628896-d1da-4930-89f3-062b46a6fc6c
public void onPrologQueryRequested( List<PrologModelApplicable> preconditionsList, OnPrologQueryResultListener resultListener) { // do nothing }
e4148238-9424-4eca-97b5-7fc130417ae4
public static void main(String... strings) { new Main().initialize(); }
5c58c227-9928-4bc8-8464-e1d13af61054
public void initialize() { EventQueue.invokeLater(new Runnable() { public void run() { try { mRootFrame.setOnPrologQueryRequestedListener(mPrologCommunicator); mRootFrame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); }
deee8549-86ca-45b9-90c9-6072f330a265
public void run() { try { mRootFrame.setOnPrologQueryRequestedListener(mPrologCommunicator); mRootFrame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } }
1bd355c5-45d1-49c6-85a7-c54660dab033
public void onPrologQueryResultReceived(List<String> associatedCarsList);
dd68b6db-ce17-402e-b7f1-be89925938e8
public void onPrologQueryRequested(List<PrologModelApplicable> preconditionsList, OnPrologQueryResultListener resultListener);
27bda441-ea41-4c74-aa81-da83ed729bae
@Override public void run() { REAL_DRIVER.close(); }
ac8e1545-eb30-4eeb-9c8b-393f99a294c8
public SharedDriver() { super(REAL_DRIVER); }
04be838f-2c0b-4ba3-a7ec-72cd2703ab8d
@Override public void close() { if (Thread.currentThread() != CLOSE_THREAD) { throw new UnsupportedOperationException("You shouldn't close this WebDriver. It's shared and will close when the JVM exits."); } super.close(); }
16587de3-aa30-4a13-8d70-95bb5828140f
@Before public void deleteAllCookies() { manage().deleteAllCookies(); }
3e7a3a83-751f-4aaa-a82d-8478fc1ba02e
@After public void embedScreenshot(Scenario scenario) { try { byte[] screenshot = getScreenshotAs(OutputType.BYTES); scenario.embed(screenshot, "image/png"); } catch (WebDriverException somePlatformsDontSupportScreenshots) { System.err.println(somePlatformsDontSupportScreenshots.getMessage()); } }
c0961c59-90cf-4303-922b-c896dcd274f8
public WebElement getErrorMessageElement() { return errorMessageElement; }
9e9be399-e2e0-4084-960a-31918fdf8104
public void SignUp(String emailAddress) { email.sendKeys(emailAddress); email.submit(); }
1d73d631-4354-449c-946f-8eb4e79c1d2c
public WebElement getNoSignUpsMessageElement() { return noSignUpsMessageElement; }
ba55707e-f435-4073-917f-bdb90514e9b4
public WebElement getThankYouHeadingElement() { return thankYouHeadingElement; }
1c1a12c8-ef3f-458b-9344-143c929bc6b0
public WebElement getThankYouBodyTextElement() { return thankYouBodyTextElement; }
05f4e082-e607-4571-ae2c-c747b0d0203f
public WebElement getInfoMessageElement() { return infoMessage; }
5d69e8f5-9c57-4d77-a2f3-a87840a0604c
public Reset(SharedDriver driver) { this.driver = driver; conf = ConfigFactory.load(); }
b7453ea7-5ac5-435f-acb8-f97ce4ee0b48
@When("^I go to the reset URL$") public void iGoToTheResetURL() { driver.get(conf.getString("moo-hw.host")+"reset"); }
a198fdcb-0c16-4a26-ac00-c316fda06f81
@Then("^I will see a confirmation message$") public void iWillSeeAConfirmationMessage() { resetPage = PageFactory.initElements(driver, ResetPage.class); assertThat(resetPage.getInfoMessageElement().getText(), is("List of emails has been reset")); driver.get(conf.getString("moo-hw.host")+"all"); }
330b523e-3773-4710-837b-e42f6155eef4
@Then("^there will be no email addresses on the email list$") public void thereWillBeNoEmailAddressesOnTheEmailList() { listAllPage = PageFactory.initElements(driver, ListAllPage.class); assertThat(listAllPage.getNoSignUpsMessageElement().getText(), is("No email signups so far")); }
681b6863-eff8-4e57-9b6d-f12b4f36a999
public ListAll(SharedDriver driver) { this.driver = driver; conf = ConfigFactory.load(); }
e27dd815-357f-4972-a1d2-445ae3e3eda6
@Given("^I have signed up to the email list$") public void iHaveSignedUpToTheEmailList() { driver.get(conf.getString("moo-hw.host")+"signup"); page = PageFactory.initElements(driver, SignUpPage.class); page.SignUp(emailAddress); }
fd1cb819-2b23-44c5-aedb-daae4554b8bc
@When("^I load the list subscribers page$") public void iLoadTheListSubscribersPage() { driver.get(conf.getString("moo-hw.host")+"all"); }
b2a927b6-0cda-4818-b6f6-c60ab48afdec
@Then("^I should see my email address$") public void iShouldSeeMyEmailAddress() throws Throwable { assertThat(driver.findElement(By.tagName("body")).getText(), containsString(emailAddress)); }
2b673340-6ccc-4397-9b96-10fee947c59f
public SignUp(SharedDriver driver) { this.driver = driver; conf = ConfigFactory.load(); page = PageFactory.initElements(driver, SignUpPage.class); }
1dda7e43-ba49-4a60-90dd-1995cc61b2ec
@Given("^I am on the email sign up page$") public void iAmOnTheEmailSignUpPage() { driver.get(conf.getString("moo-hw.host")+"signup"); }
7244eda0-1ff1-43cd-bcfe-128645057739
@When("^I enter a valid email address$") public void iEnterAValidEmailAddress() { page.SignUp(emailAddress); }
0c436f49-0f7b-4428-a6ad-6da61533cb86
@Then("^I see a thank you confirmation message$") public void iSeeAThankYouConfirmationMessage() { ThankYouPage page = PageFactory.initElements(driver, ThankYouPage.class); assertThat(page.getThankYouHeadingElement().getText(), is("Thank your for your details!")); assertThat(page.getThankYouBodyTextElement().getText(), containsString("You have signed up with email"+" "+emailAddress)); }
4f8364f9-34bd-40f5-b62d-79a04b32b281
@When("^I leave the email field blank$") public void iLeaveTheEmailFieldBlank() { page.SignUp(""); }
2f1d5922-9763-4fee-ab73-809a00bf050b
@Then("^I see an error message$") public void iSeeAnErrorMessage() { assertThat(page.getErrorMessageElement().getText(), is("Please provide your email address")); }
f96ec34c-4a21-4275-b7b0-f5fcf9bad39e
@Given("^I sign-up as \"(.*?)\"$") public void iSignUpAs(String emailAddress) { page.SignUp(emailAddress); }
0ca50eae-3847-4a56-a1d9-c139c762df42
@When("^I sign-up again as \"(.*?)\"$") public void iSignUpAgainAs(String emailAddress) { // need to navigate away to let us reload the sign-up page driver.get("about:blank"); driver.get(conf.getString("moo-hw.host")+"signup"); page.SignUp(emailAddress); }
5678d4eb-f112-4219-ad3a-5186f6ea593f
@Then("^I see an error message saying the email address is already subscribed$") public void iSeeAnErrorMessageSayingTheEmailAddressIsAlreadySubscribed() { assertThat(page.getErrorMessageElement().getText(), is("This email has already been signed up")); }
b570e2f4-c7c9-4bff-8043-ba4919df8fa5
@When("^I enter an invalid email address$") public void iEnterAnInvalidEmailAddress() { page.SignUp("invalid"); }
9a714f9c-4bab-4085-9314-c6f1a88cd8e6
@Then("^I see an error message to provide a valid email address$") public void iSeeAnErrorMessageToProvideAValidEmailAddress() { assertThat(page.getErrorMessageElement().getText(), is("Please provide a valid email address")); }
bb0eab5f-7a07-480e-8b6d-cf54bdc13c69
@Override public double evaluate(final IntSet subset) { int sum = 0; for (final int element : subset) { sum += element; } maxFitnessValue = Math.max(maxFitnessValue, sum); //System.out.println("fitness evaluated: "+sum+" max: "+maxFitnessValue); return sum; }
e518f14f-9153-4ec5-ba46-26d5021a69c6
@Override public double evaluate(final IntSet subset) { int sum = 1000; for (final int element : subset) { sum -= element; } return sum; }
9fcf88c8-0c7f-4d4e-a3a3-1c012fcecff9
public synchronized void testSubSetLargest() throws InvalidConfigurationException { final IntSet set = new IntArraySet(); final int[] elements = {1, 2, 3, 4, 5, 6, 7, 8, 9}; for (final int element : elements) { set.add(element); } final OptimizeSubSet optimizer = new OptimizeSubSet(set, 3, largestCriterion); optimizer.setRandomSeed(1); final boolean converged = optimizer.optimize(10000, 0.001); assertTrue(converged); final IntSet optimalsubSet = optimizer.getFitestSubset(); printSubset(optimalsubSet); assertTrue(optimalsubSet.contains(7)); assertTrue(optimalsubSet.contains(8)); assertTrue(optimalsubSet.contains(9)); }
5c98dec7-578b-44a2-8d55-acb8c13c4654
public synchronized void testSubSetLargestWithGaps() throws InvalidConfigurationException { final IntSet set = new IntArraySet(); final int[] elements = {1, 74, 87, 900, 2, 61}; for (final int element : elements) { set.add(element); } final OptimizeSubSet optimizer = new OptimizeSubSet(set, 3, largestCriterion); optimizer.setRandomSeed(1); final boolean converged = optimizer.optimize(10000, 0.001); assertTrue(converged); final IntSet optimalsubSet = optimizer.getFitestSubset(); printSubset(optimalsubSet); assertTrue(optimalsubSet.contains(74)); assertTrue(optimalsubSet.contains(87)); assertTrue(optimalsubSet.contains(900)); }
5f20186b-5bf7-4fb7-803a-1c123225a028
@Override public double evaluate(final IntSet subset, final double... paramValues) { assert paramValues.length == 2 : "evaluate must be called with two parameter values"; int sum = 100; for (final int element : subset) { sum += (element * paramValues[0]) - paramValues[1]; } maxFitnessValue = Math.max(maxFitnessValue, sum); return sum; }
287328e4-e619-4c0c-a8ca-1c179eb40dad
public synchronized void testSubSetLargestWithGapsAndParams() throws InvalidConfigurationException { final IntSet set = new IntArraySet(); final int[] elements = {1, 74, 87, 900, 2, 61}; for (final int element : elements) { set.add(element); } // fitness function=sum of elements in subset multiplied by alpha, minus beta. final String param1 = "alpha=1,2,3,4,0.5,0.1"; //optimal alpha=4 final String param2 = "beta=1,2,0,3,4,0.5"; //optimal beta=0 final OptimizeSubSet optimizer = new OptimizeSubSet(set, 3, largestCriterionWithAlphaBeta, param1, param2); optimizer.setRandomSeed(1); final boolean converged = optimizer.optimize(10000, 0.001); assertTrue(converged); final IntSet optimalsubSet = optimizer.getFitestSubset(); printSubset(optimalsubSet); assertTrue(optimalsubSet.contains(74)); assertTrue(optimalsubSet.contains(87)); assertTrue(optimalsubSet.contains(900)); final double[] optimalParameterValues = optimizer.getFitestParameterValues(); assertEquals(4d, optimalParameterValues[0]); assertEquals(0d, optimalParameterValues[1]); }
71612904-0c18-4a6c-add1-6b23bb25818a
public synchronized void testSubSetSmallest() throws InvalidConfigurationException { final IntSet set = new IntArraySet(); final int[] elements = {1, 2, 3, 4, 5, 6, 7, 8, 9}; for (final int element : elements) { set.add(element); } final OptimizeSubSet optimizer = new OptimizeSubSet(set, 3, smallestCriterion); optimizer.setRandomSeed(1); final boolean converged = optimizer.optimize(10000, 0.001); assertTrue(converged); final IntSet optimalsubSet; System.out.println("Number of iterations: " + optimizer.getNumberOfIterationsPerformed()); optimalsubSet = optimizer.getFitestSubset(); printSubset(optimalsubSet); assertTrue(optimalsubSet.contains(1)); assertTrue(optimalsubSet.contains(2)); assertTrue(optimalsubSet.contains(3)); }
76641739-0c15-4bd3-95fa-d38efe62af66
public synchronized void testSubSetLargest100() throws InvalidConfigurationException { final IntSet set = new IntArraySet(); final int[] elements = new int[100]; int max = Integer.MIN_VALUE; for (int i = 1; i <= elements.length; ++i) { set.add(i); max = Math.max(i, max); } System.out.println("max element: " + max); final OptimizeSubSet optimizer = new OptimizeSubSet(set, 3, largestCriterion); optimizer.setRandomSeed(39); optimizer.setPopulationSize(10000); maxFitnessValue = 0; final boolean converged = optimizer.optimize(10000, 0.001); assertEquals("fitest chromosome must have maximum fitness evaluated by fitness function.", maxFitnessValue, optimizer.getFitestFunctionValue()); assertTrue(converged); System.out.println("Number of iterations: " + optimizer.getNumberOfIterationsPerformed()); final IntSet optimalsubSet; optimalsubSet = optimizer.getFitestSubset(); printSubset(optimalsubSet); assertTrue(optimalsubSet.contains(elements.length)); assertTrue(optimalsubSet.contains(elements.length - 1)); assertTrue(optimalsubSet.contains(elements.length - 2)); }
65ec92bf-d11d-428c-a4dc-f9fb3dc137dc
public synchronized void testSubSetLargest2000() throws InvalidConfigurationException { final IntSet set = new IntArraySet(); final int[] elements = new int[2000]; for (int i = 1; i <= elements.length; ++i) { set.add(i); } final double optimal = 2000 + 1999 + 1998; final OptimizeSubSet optimizer = new OptimizeSubSet(set, 3, largestCriterion); optimizer.setPopulationSize(1000); optimizer.setRandomSeed(1); maxFitnessValue = 0; final boolean converged = optimizer.optimize(20000, 0.001); assertEquals("fitest chromosome must have maximum fitness evaluated by fitness function.", maxFitnessValue, optimizer.getFitestFunctionValue()); assertTrue(converged); final IntSet optimalsubSet; assertEquals("optimal fitest function must match true optimum", optimal, optimizer.getFitestFunctionValue()); optimalsubSet = optimizer.getFitestSubset(); printSubset(optimalsubSet); assertTrue(optimalsubSet.contains(elements.length)); assertTrue(optimalsubSet.contains(elements.length - 1)); assertTrue(optimalsubSet.contains(elements.length - 2)); }
770e3610-4b7e-4508-a1e8-fadf0efcff13
public synchronized void TestSubSetLargest20000() throws InvalidConfigurationException { final IntSet set = new IntArraySet(); final int[] elements = new int[20000]; for (int i = 1; i <= elements.length; ++i) { set.add(i); } final double optimal = 20000 + 20000-1 + 20000-2; final OptimizeSubSet optimizer = new OptimizeSubSet(set, 3, largestCriterion); optimizer.setPopulationSize(1000); final boolean converged = optimizer.optimize(200000, 0.001); assertTrue(converged); assertEquals("optimal fitest function must match true optimum", optimal, optimizer.getFitestFunctionValue()); final IntSet optimalsubSet; optimalsubSet = optimizer.getFitestSubset(); printSubset(optimalsubSet); assertTrue(optimalsubSet.contains(elements.length)); assertTrue(optimalsubSet.contains(elements.length - 1)); assertTrue(optimalsubSet.contains(elements.length - 2)); }
706e5798-c025-49de-a06c-13d6901a9645
private void printSubset(final IntSet optimalsubSet) { for (final int element : optimalsubSet) { System.out.println("element " + element); } }
23e76d11-abf0-475c-acc7-9d2f156ec69f
double evaluate(IntSet subset, double ... paramValues);
ebf1a4d5-7bca-44b0-a159-d2e78154cd86
double evaluate(IntSet subset);
722dadac-f660-4824-8528-66b395c3a3ea
public SubsetSuperGene() throws InvalidConfigurationException { this.subset = new IntArraySet(); }
51d82b34-5bac-4d85-9830-5054ee010d22
public SubsetSuperGene(final Configuration configuration) throws InvalidConfigurationException { super(configuration); this.subset = new IntArraySet(); }
019ac5d7-9527-4729-a6b5-40dc728edb87
public SubsetSuperGene(final Configuration configuration, final Gene[] subsetGenes) throws InvalidConfigurationException { super(configuration, subsetGenes); this.subset = new IntArraySet(); }
35bb0433-a4a9-4cb3-9e04-670ee422985a
public SubsetSuperGene(final Configuration configuration, final Gene[] subsetGenes, final int[] allElements) throws InvalidConfigurationException { super(configuration, subsetGenes); this.subset = new IntArraySet(); this.allElements = allElements; }
848b545b-0fb9-4f90-a258-9d6e77b2e87c
@Override public synchronized boolean isValid(final Gene[] genes, final Supergene supergene) { subset.clear(); int previous = -1; for (final Gene gene : genes) { final int element = (Integer) gene.getAllele(); if (element <= previous) { // force increasing order of element to avoid considering order permutations return false; } subset.add(element); previous = element; } // valid solutions have no duplicate elements. return subset.size() == genes.length; }
fce204b8-e912-4115-93e3-deebb0f0ac2f
@Override public Gene newGene() { final SubsetSuperGene copy = (SubsetSuperGene) super.newGene(); copy.allElements = allElements; return copy; }
79e20922-d787-4f22-afe9-fba0689b3a8d
public IntSet getSubSet() { final IntSet result = new IntArraySet(); for (final Gene gene : getGenes()) { final Integer element = (Integer) gene.getAllele(); result.add(allElements[element]); } return result; }
3e48cb30-67d6-44a3-9845-097b625c950b
@Override public String toString() { final MutableString result = new MutableString(); result.append("{ "); for (final Gene gene : getGenes()) { result.append(gene.getAllele()); result.append(' '); } result.append("} "); return result.toString(); }
a9de5b9c-d358-4808-a957-0ba8c3809f05
@Override public void setToRandomValue(final RandomGenerator a_numberGenerator) { final IntList sortedSubSet = new IntArrayList(); final Gene[] m_genes = getGenes(); for (int i = 0; i < m_genes.length; i++) { int value = -1; do { m_genes[i].setToRandomValue(a_numberGenerator); value = (Integer) m_genes[i].getAllele(); } while (sortedSubSet.contains(value)); sortedSubSet.add(value); } Collections.sort(sortedSubSet); // set all to random value first for (int i = 0; i < m_genes.length; i++) { m_genes[i].setAllele(sortedSubSet.get(i)); } if (!isValid()) { throw new InternalError("Supergene content must be compatible with valid method"); } }
b5ea5375-b940-41b8-a4a9-f2f92b08958f
public double evaluate(final IntSet subset, final double... paramValues) { assert paramValues.length == 0 : " paramValues are not supported by this implementation."; return evaluate(subset); }
6ed3be1a-8f87-4664-8e92-f650594092cc
public double evaluate(final IntSet subset) { assert false : "This method must be overriden with a functional implementation"; return 0; }
283a48a7-c775-4ade-8128-a1c7aeda3c01
public void setModuloProgressReport(final int moduloProgressReport) { this.moduloProgressReport = moduloProgressReport; }
8a59f27b-9397-4ce9-980e-ebb526f6914d
public OptimizeSubSet(final IntSet set, final int k, final SubSetFitnessFunction convergenceCriterion) throws InvalidConfigurationException { this(set, k, convergenceCriterion, DEFAULT_POPULATION_SIZE); }
996d2f70-a64c-4f48-a5ed-089c6daeb9fc
public OptimizeSubSet(final IntSet set, final int k, final SubSetFitnessFunction convergenceCriterion, final String... params) throws InvalidConfigurationException { this(set, k, convergenceCriterion, DEFAULT_POPULATION_SIZE, params); }
eda2f141-c0cd-45f8-81b1-fb36b21ade18
public OptimizeSubSet(final IntSet set, final int k, final SubSetFitnessFunction convergenceCriterion, final int populationSize, final String... params) throws InvalidConfigurationException { this.numParams = params.length; parseParameterDefinitions(params); this.set = set; this.k = k; int i = 0; this.allElements = new int[set.size()]; for (final int element : set) { allElements[i++] = element; } this.convergenceCriterion = convergenceCriterion; this.k = k; numElementsInSet = set.size(); // This is odd: JGAP seems to maintain properties associated with each thread, so creating a new // Configuration instance is not sufficient to indicate that we want a fresh configuration. We have // to call the static reset method on Configuration.. Configuration.reset(); randomGenerator = new TwisterGenerator(); this.populationSize = populationSize; configure(); }
e4db6555-6554-426d-9575-e919dc53f479
private void parseParameterDefinitions(final String[] paramDefinitions) { int paramIndex = 0; parameterNames = new String[paramDefinitions.length]; allPossibleParameterValues = new double[paramDefinitions.length][]; for (final String parameterDefinition : paramDefinitions) { final String[] tokens = parameterDefinition.split("[=,]"); assert tokens.length > 3 : "parameter definition must be of the form name=value1,value2,..."; parameterNames[paramIndex] = tokens[0]; final DoubleList paramValues = new DoubleArrayList(); for (int valueIndex = 1; valueIndex < tokens.length; valueIndex++) { paramValues.add(Double.parseDouble(tokens[valueIndex])); } allPossibleParameterValues[paramIndex] = paramValues.toDoubleArray(); paramIndex++; } }
3a21f904-5db9-4ef3-980c-c519bda300b4
public void setPopulationSize(final int populationSize) { this.populationSize = populationSize; }
8de7b917-9a6d-4367-9b8c-b08ffd8ca82b
public void setRandomSeed(final int randomSeed) { this.randomSeed = randomSeed; this.randomGenerator = new TwisterGenerator(randomSeed); }
390b31ff-7c4a-40ed-bf57-59f585a456e8
public void configure() throws InvalidConfigurationException { configuration = new DefaultConfiguration(); configuration.setPreservFittestIndividual(true); configuration.setKeepPopulationSizeConstant(true); configuration.setRandomGenerator(randomGenerator); fitnessFunction = new FitnessFunctionAdapter(set, k, convergenceCriterion, allPossibleParameterValues); configuration.setBulkFitnessFunction(new BulkFitnessNoOffset(fitnessFunction)); subsetChromosome = setupChromosome(allElements); configuration.setSampleChromosome(subsetChromosome); configuration.setPopulationSize(populationSize); progressLogger = new ProgressLogger(log); fitestSubset = new IntArraySet(); configured = true; }
4e4def46-73ed-4b9e-9660-f338891d35b8
private IChromosome setupChromosome(final int[] set) throws InvalidConfigurationException { subsetGenes = new Gene[k]; int minElementValue = Integer.MAX_VALUE; int maxElementValue = Integer.MIN_VALUE; for (final int element : set) { minElementValue = Math.min(element, minElementValue); maxElementValue = Math.max(element, maxElementValue); } for (int g = 0; g < k; g++) { subsetGenes[g] = new IntegerGene(configuration, 0, numElementsInSet - 1); } final Gene[] genes = new Gene[1 + getNumberOfParameters()]; final AbstractSupergene constrainedGenes = new SubsetSuperGene(configuration, subsetGenes, this.allElements); genes[0] = constrainedGenes; for (int paramIndex = 0; paramIndex < getNumberOfParameters(); paramIndex++) { genes[1 + paramIndex] = new IntegerGene(configuration, 0, this.allPossibleParameterValues[paramIndex].length - 1); } subsetChromosome = new Chromosome(configuration, genes); return subsetChromosome; }
fb6796e6-a3b5-4c8f-b71e-f50ef93349bd
public void setLog(final Logger log) { this.log = log; progressLogger = new ProgressLogger(log); }
69e5e983-458f-4988-9ca6-7120c4bfcc20
public int getNumberOfIterationsPerformed() { return numberOfIterationsPerformed; }
0321cba6-64fb-4265-80e9-12050b83757e
public boolean optimize(final int numSteps, final double convergenceDelta) throws InvalidConfigurationException { if (!configured) { configure(); } final int deltaNumSteps = numSteps/10; final Genotype population = Genotype.randomInitialGenotype(configuration); final boolean converged; int timesFitnessStable = 0; double previousFitness = -1; progressLogger.expectedUpdates = numSteps; progressLogger.start("optimization"); IChromosome fitestChromosome = null; double fitness = -2; for (int i = 0; i < numSteps; i++) { // writeCurrentPopulation(population); fitestChromosome = population.getFittestChromosome(); fitness = fitnessFunction.getFitnessValue(fitestChromosome); fitestFunctionValue = fitness; if (i % moduloProgressReport == 1) { log.info("Current solution has a fitness value of " + formatDouble(Math.log(fitestChromosome.getFitnessValue())) + " absolute: " + formatDouble(Math.log(fitness)) + "or raw: " + fitness); log.debug(fitestChromosome.getGene(0).toString()); } if (fitness >= previousFitness && fitness - previousFitness < Math.abs(convergenceDelta)) { timesFitnessStable++; log.trace("fitness function value stable " + timesFitnessStable); } else { timesFitnessStable = 0; log.trace("fitness function not stable, old: " + previousFitness + " new fitness: " + fitness); } previousFitness = fitness; if (timesFitnessStable >= deltaNumSteps) { break; } numberOfIterationsPerformed = i; if (i != numSteps - 1) { // do not evolve if this is the last step. population.evolve(); progressLogger.lightUpdate(); } } if (fitness - previousFitness < Math.abs(convergenceDelta)) { converged = true; } else { converged = false; } progressLogger.stop("optimization"); convertFittestToSolution(fitestChromosome); return converged; }
075bf53d-0902-4b8e-8834-7814e0d70626
private void convertFittestToSolution(final IChromosome fittestChromosome) { if (fittestChromosome == null) { fitestSubset = null; fitestParams = ArrayUtils.EMPTY_DOUBLE_ARRAY; } else { fitestSubset = ((SubsetSuperGene) fittestChromosome.getGene(0)).getSubSet(); fitestParams = FitnessFunctionAdapter.getParameterValues(fittestChromosome, allPossibleParameterValues); } }
2758bb5e-8a83-4971-a0c1-8dde819e1774
public IntSet getFitestSubset() { return fitestSubset; }
03e73151-fc34-48f0-93be-7595f7aa9d6c
public double[] getFitestParameterValues() { return fitestParams; }
a63b7fe6-3110-4347-88f7-e0d3046d1cf4
private String formatDouble(final double v) { return formatter.format(v); }
276bd556-9d15-4322-9095-d3b01579cd03
public int getNumberOfParameters() { return numParams; }
cc8a484c-ed33-4b5b-b685-79680644d683
public double getFitestFunctionValue() { return fitestFunctionValue; }
ea415ecc-a7fd-4faf-a655-aa8dc7a898b1
public BulkFitnessNoOffset(final FitnessFunction fitnessFunction) { this.fitnessFunction = fitnessFunction; }
72ec5a6d-c1f8-43de-8d4d-266ca47188cb
@Override public void evaluate(final Population a_chromosomes) { double curFitness; final Iterator itChromosomes = a_chromosomes.iterator(); IChromosome chromosome; while (itChromosomes.hasNext()) { chromosome = (IChromosome) itChromosomes.next(); curFitness = chromosome.getFitnessValueDirectly(); if (curFitness < 0) { // fitness was not evaluated for this chromosome yet. curFitness = fitnessFunction.getFitnessValue(chromosome); // And store it to avoid evaluation of the same Chromosome again: chromosome.setFitnessValue(curFitness); } else { chromosome.setFitnessValue(curFitness); } } }
6aeccd7f-6498-47f5-b08f-6bb06316f233
public CacheThread(Socket s) { log.info("New Thread created!"); this.s = s; //setDaemon(true); //setPriority(NORM_PRIORITY); }
db0312b9-d830-451b-8cbb-3a3d1eb10b06
protected void from_net(String header, String host, int port, String path) throws Exception { log.info("New socked (host, port):" + host + ":" + port + "\n"); Socket requestSocket = new Socket(host, port); log.info("Request Header: \n" + header); requestSocket.getOutputStream().write(header.getBytes("ASCII")); // log.info("Sended from from_net"); InputStream responseIs = requestSocket.getInputStream(); // File f = new File((new File(path)).getParent()); // if (!f.exists()) // f.mkdirs(); // FileOutputStream fos = new FileOutputStream(path); try { //get header // StringBuilder responseHeaderSB = new StringBuilder(); ArrayList<Byte> arrayList = new ArrayList(2048); int buf; while ((buf = responseIs.read()) != -1) { // responseHeaderSB.append(new String(new byte[]{(byte) buf}, "ASCII")); // System.out.printf(new String(new byte[]{(byte)buf}), "ASCII"); arrayList.add((byte) buf); if (13 == buf) { buf = responseIs.read(); arrayList.add((byte) buf); if (10 == buf) { buf = responseIs.read(); arrayList.add((byte) buf); if (13 == buf) { buf = responseIs.read(); arrayList.add((byte) buf); if (10 == buf) { break; } } } } // if (responseHeaderSB.toString().endsWith("\n\n") || responseHeaderSB.toString().endsWith("\r\n\r\n")) { // break; // } } byte[] resposebHeader = new byte[arrayList.size()]; for (int i = 0; i < arrayList.size(); i++) { resposebHeader[i] = arrayList.get(i); } String responseHeader = new String(resposebHeader, "ASCII"); log.info("Response Header\n" + responseHeader); os.write(resposebHeader); if (responseHeader.startsWith("HTTP/1.0 304 Not Modified") || responseHeader.startsWith("HTTP/1.0 302 Moved Temporarily")) { log.info("302 or 304"); return; } // HTTP/1.0 304 Not Modified //get content Length String[] requestHeaders = responseHeader.split("\\n"); long contentLength = 0; for (String requestHeader1 : requestHeaders) { if (requestHeader1.startsWith("Content-Length:")) { log.info(requestHeader1); String cl = requestHeader1.substring(requestHeader1.indexOf(":") + 1).trim(); log.info(cl); contentLength = Long.parseLong(cl); break; } } log.info("Content Length: " + contentLength); if (contentLength != 0) { for (long i = 0; i < contentLength; i++) { //fos.write(responseIs.read()); os.write(responseIs.read()); } } else { byte reply[] = new byte[1024]; int bytes_read; while ((bytes_read = responseIs.read(reply)) != -1) { //fos.write(reply, 0, bytes_read); os.write(reply, 0, bytes_read); } } // while ((bytes_read = is.read(reply)) != 0) { // System.out.printf(new String(reply, 0, bytes_read, "ASCII")); //// fos.write(reply, 0, bytes_read); // os.write(reply, 0, bytes_read); // } } catch (SocketTimeoutException e) { log.error(e.getMessage(), e); // log.error("SocketTimeoutException: Read timed out in socked (host, port):" + host + ":" + port + "\n"); // log.error("HEADER:" + header); } finally { // fos.close(); // os.close(); responseIs.close(); requestSocket.close(); } }
bf77a60b-8e0f-4a71-a6be-6c1837b7d77f
protected void from_net(String header) throws Exception { log.info("Try from net!"); String host = extractFromHeader(header, "Host:", "\n"), path = getPath(header); if ((host == null) || (path == null)) { printError("invalid request:\n" + header); return; } log.info("Transform path: " + path); int port = host.indexOf(":", 0); if (port < 0) port = 80; else { port = Integer.parseInt(host.substring(port + 1)); host = host.substring(0, port); } log.info("From net Host+port: " + host + ":" + port); from_net(header, host, port, path); }
fdc04d50-2e94-48cf-8ab3-f9960805edae
protected void from_cache(String header) throws Exception { log.info("Try from cache!"); this.method = "GET"; String path = getPath(header); log.info("Transform path: " + path); if (path == null) { this.error = "invalid request:\n" + header; log.info(this); printError("invalid request:\n" + header); return; } // except "Pragma: no-cache" /* * String pragma = extractFromHeader(header, "Pragma:", "\n"); if * (pragma != null) if (pragma.toLowerCase().equals("no-cache")) { * System.out.println("Pragma no-cache!"); from_net(header); return; } */ this.path = path; if ((new File(path)).exists()) { log.info("File is exists!"); this.fromCache = true; FileInputStream fis = new FileInputStream(path); byte buf[] = new byte[64 * 1024]; int r = 1; log.info(this); while (r > 0) { r = fis.read(buf); if (r > 0) os.write(buf, 0, r); } fis.close(); os.flush(); os.close(); } else { log.info("File is NOT exists!"); from_net(header); } }
061027e1-83bd-4e96-8d31-cbb3a9ebbbae
public void run() { log.info("Process request\n"); int r = 0; try { is2 = s.getInputStream(); os = s.getOutputStream(); byte buf[] = new byte[10 * 1024]; r = is2.read(buf); if (r > 0) { String header = new String(buf, 0, r, "ASCII"); //Хидер GET только из кеша // if (header.indexOf("GET ", 0) == 0) // from_cache(header); // //Иные из интернета // else // log.info("REQUEST main:\n" + header); from_net(header); } } catch (Exception e) { try { log.error(e.getMessage(), e); // e.printStackTrace(); // printError("exception:\n" + e); } catch (Exception ex) { } } finally { try { // if (is2 != null) is2.close(); // if (os != null) os.close(); if (s != null) s.close(); log.info("Thread finished!"); } catch (IOException e) { } } }
c1da543c-6241-4f4f-b193-83f2f2b857c9
private void printError(String err) throws Exception { os.write((new String(PROXY_ERROR + err)).getBytes()); }
9bf6e917-fe1e-4333-bd5a-6400f77de02b
@Override public String toString() { return "CacheThread [method=" + method + ", path=" + path + ", fromCache=" + fromCache + ", error=" + error + "]"; }
e1489c83-3307-4b7f-988d-7a358284fcc3
static String getPageCharsetFromHeaders(Map<String, List<String>> headers) { String contentType = Arrays.toString(headers.get("Content-Type").toArray()).replaceAll("\\[|\\]", "").replaceAll(", ", "\t"); String[] values = contentType.split(";"); //The values.length must be equal to 2... String charset = ""; for (String value : values) { value = value.trim(); if (value.toLowerCase().startsWith("charset=")) { charset = value.substring("charset=".length()); } } if ("".equals(charset)) { charset = "UTF-8"; //f**k ups...lol, Default encoding accepted! } log.info("\n Accepted encoding: " + charset); return charset; }
b500452d-e45f-42f6-9fb3-240fa5c04b7a
public static String extractFromHeader(String str, String start, String end) { int s = str.indexOf("\n\n", 0), e; if (s < 0) s = str.indexOf("\r\n\r\n", 0); if (s > 0) str = str.substring(0, s); s = str.indexOf(start, 0) + start.length(); if (s < start.length()) return null; e = str.indexOf(end, s); if (e < 0) e = str.length(); return (str.substring(s, e)).trim(); }
8e8f9bbd-ee27-4398-afc5-c8623d7a6456
public static StringBuilder replaceAll(StringBuilder builder, String from, String to) { StringBuilder replaceBuilder = builder; int index = replaceBuilder.indexOf(from); while (index != -1) { replaceBuilder.replace(index, index + from.length(), to); index += to.length(); // Move to the end of the replacement index = replaceBuilder.indexOf(from, index); } return replaceBuilder; }
83f2bc18-f2e0-4588-8473-bd839734c42b
public static String replaceRegex(StringBuilder builder, String pattern, String replacement) { Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(builder); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, replacement); } m.appendTail(sb); return sb.toString(); }
ec4188b4-47f9-4bb9-828d-b66ab90ffd16
public static String getPath(String header) { String URI = extractFromHeader(header, "GET ", " "), path; if (URI == null) URI = extractFromHeader(header, "POST ", " "); if (URI == null) return null; path = URI.toLowerCase(); if (path.length() >= 7 && path.indexOf("http://", 0) == 0) URI = URI.substring(7); else { path = extractFromHeader(header, "Host:", "\n"); if (path == null) return null; URI = path + URI; } URI = Transform.fixURL(URI); URI = Transform.URL2File(URI, (byte) 0); path = CACHE_PATH + File.separator + URI; //System.out.println("Method getPath(fix+transform), Getted path: "+path); return path; }
798576fb-4d0d-4e3a-b3bb-0a8ef0f00186
public static String fixURL(String URI) { //System.out.println("\tFIX URL Getted URI: "+URI); if (URI.length() >= 7 && URI.indexOf("http://", 0) == 0) URI = URI.substring(7); String s = URI; int startIndex = s.indexOf('#'); if (startIndex >= 0) { StringBuilder sb = new StringBuilder(s); s = sb.delete(startIndex, sb.length()).toString(); } // Делаем URL более однозначным // -Коды символов %xX в %XX (верхний регист) s = replaceToUpCase(s, Pattern.compile("%[A-Fa-f\\d]{2}")); // -Символ ' " ' в %22 s = s.replace("\"", "%22"); // -Символ ' < ' в %3C s = s.replace("<", "%3C"); // -Символ ' > ' в %3E s = s.replace(">", "%3E"); // -Символ ' ` ' в %60 s = s.replace("`", "%60"); int num1 = s.indexOf('?'); s = (num1 < 0) ? s.replace("^", "%5E") : s.substring(0, num1).replace( "^", "%5E") + s.substring(num1); s = escape_unicode_rus(s); if (s.indexOf('/') < 0 & s.length() > 0) s = s + '/'; int num2 = s.indexOf('/'); if (num2 >= 0) s = Pattern.compile("(:(80)?$)?").matcher(s.substring(0, num2)) .replaceAll("").toLowerCase() + s.substring(num2); int num3 = s.indexOf('/'); char[] Chars = s.toCharArray(); for (int index = 0; index < num3; ++index) { if (((int) Chars[index] < 48 | (int) Chars[index] > 57) & ((int) Chars[index] < 97 | (int) Chars[index] > 122) & ((int) Chars[index] != 45 & (int) Chars[index] != 46 & (int) Chars[index] != 58)) { s = "НЕПРАВИЛЬНЫЙ ХОСТ"; break; } } //System.out.println("Transformed URI: "+s); return s; }
d830d2ee-bbb1-4135-90f1-b678936463bf
public static String URL2File(String url, byte redir) { //System.out.println("To file: "+url); // Обрезаем 'http:\\' в URL чтобы не писать в путь файла if (url.length() >= 7 && url.substring(0, 7).toLowerCase().equals("http://")) { url = url.substring(7); } /* * Преобразовать символы * '*' в '#x' (совместимость) * '\\' в '#~' (совместимость) * '|' в '#i' (совместимость) * ':' в '#=' (НЕсовместимость!), ранее в '!', соответственно '!' ранее в '#I' */ String str1 = url.replace("*", "#x").replace("\\", "#~") .replace("|", "#i").replace(":", "#="); // Опционально: // Кодировать %22 (") - двойную ковычку // --в символ #' // str1 = str1.replace("%22", "#'"); // --в символ `` // str1 = str1.replace("%22", "``"); // Кодировать %3C (<) и %3E (>) - скобы // --в символы '#(' и '#)' // str1 = str1.replace("%3C", "#(").replace("%3E", "#)"); // --в символы '#{' и '#}' // str1 = str1.replace("%3C", "#{").replace("%3E", "#}"); /** * Преобразование URL содержащих символ '?' (основная часть) * Знак '?' преобразуется в '^\' * за тем преобразуются символы: * Символ до '?' после '?' ранее * / \ #! \ и #% * // \#! #!#! \~ и #%~ * /// \#!#! #!#!#! \~\ и #%~#% * .\ .#n\ .#n\ * пробел\ пробел#n\ пробел#n\ */ int startIndex = str1.indexOf('?'); String str2 = ""; if (startIndex >= 0) { String str3 = str1.substring(startIndex + 1); StringBuilder sb = new StringBuilder(str1); str1 = sb.delete(startIndex, sb.length()).toString(); str2 = "^\\" + str3.replace("/", "#!").replace("?", "#^"); } String s = str1.replace("//", "\\#!").replace("#!\\", "#!#!") .replace('/', '\\').replace(".\\", ".#n\\") + str2; // Преобразовывать русские коды Win-1251 в символы в имени файла // s = unescape_win1251_rus(s); // Преобразовывать коды русского Юникода в русские символы в имени файла s = unescape_unicode_rus(s); // Преобразовывать коды пробела %20 в символ пробела s = unescape_space(s).replace(" \\", " #n\\"); // Использовать алгоритм шифрования CRC32 для длинных URL // [путь<maxUrlLength-15]\#-[CRC32(урл_без_хоста)] int maxUrlLength = 200; if (s.length() > maxUrlLength - 5) { int num1 = url.indexOf('/'); int num2 = s.substring(0, maxUrlLength - 10 - 5).lastIndexOf('\\'); s = s.substring(0, num2 + 1) + "#-" + CRC32(url.substring(num1 + 1)); } // Преобразовать редирект (301 Moved Permanently) к виду редирект#m if ((int) redir == 1) s = s + "#m"; char[] Chars = s.toCharArray(); if (s.length() > 0 && Chars[s.length() - 1] == 92 | Chars[s.length() - 1] == 46 | Chars[s.length() - 1] == 32) s = s + "#_"; //System.out.println("FilePath is: "+s); return s; }
63b66763-70e5-4270-b5bb-0d22dce3f49c
public static String CRC32(String str) { CRC32 crc = new CRC32(); crc.update(str.getBytes()); long result = crc.getValue(); return Long.toHexString(result).toUpperCase(); }
0627ce98-0f8b-4455-8a7b-9d2cc2e211b5
private static String escape_unicode_rus(String s) { for (int index = 0; index < RUSSIAN_CHARS.length; ++index) s = s.replace(RUSSIAN_CHARS[index], ESCAPE_CHARS[index]); s = s.replace(" ", "%20"); return s; }