How to build unlimited levels menu through PHP and MySQL

Generate HTML for multi-dimensional menu from MySQL database with ONE QUERY and WITHOUT RECURSION 





<?php

/**
 * Generate HTML for multi-dimensional menu from MySQL database
 * with ONE QUERY and WITHOUT RECURSION
 * @author J. Bruni
 */
class MenuBuilder
{
/**
* MySQL connection
*/
var $conn;

/**
* Menu items
*/
var $items = array();

/**
* HTML contents
*/
var $html  = array();

/**
* Create MySQL connection
*/
function MenuBuilder()
{
$this->conn = mysql_connect( 'localhost', 'user', 'pass' );
mysql_select_db( 'example', $this->conn );
}

/**
* Perform MySQL query and return all results
*/
function fetch_assoc_all( $sql )
{
$result = mysql_query( $sql, $this->conn );

if ( !$result )
return false;

$assoc_all = array();

while( $fetch = mysql_fetch_assoc( $result ) )
$assoc_all[] = $fetch;

mysql_free_result( $result );

return $assoc_all;
}

/**
* Get all menu items from database
*/
function get_menu_items()
{
// Change the field names and the table name in the query below to match tour needs
$sql = 'SELECT id, parent_id, title, link, position FROM menu_item ORDER BY parent_id, position;';
return $this->fetch_assoc_all( $sql );
}

/**
* Build the HTML for the menu
*/
function get_menu_html( $root_id = 0 )
{
$this->html  = array();
$this->items = $this->get_menu_items();

foreach ( $this->items as $item )
$children[$item['parent_id']][] = $item;

// loop will be false if the root has no children (i.e., an empty menu!)
$loop = !empty( $children[$root_id] );

// initializing $parent as the root
$parent = $root_id;
$parent_stack = array();

// HTML wrapper for the menu (open)
$this->html[] = '<ul>';

while ( $loop && ( ( $option = each( $children[$parent] ) ) || ( $parent > $root_id ) ) )
{
if ( $option === false )
{
$parent = array_pop( $parent_stack );

// HTML for menu item containing childrens (close)
$this->html[] = str_repeat( "\t", ( count( $parent_stack ) + 1 ) * 2 ) . '</ul>';
$this->html[] = str_repeat( "\t", ( count( $parent_stack ) + 1 ) * 2 - 1 ) . '</li>';
}
elseif ( !empty( $children[$option['value']['id']] ) )
{
$tab = str_repeat( "\t", ( count( $parent_stack ) + 1 ) * 2 - 1 );

// HTML for menu item containing childrens (open)
$this->html[] = sprintf(
'%1$s<li><a href="%2$s">%3$s</a>',
$tab,   // %1$s = tabulation
$option['value']['link'],   // %2$s = link (URL)
$option['value']['title']   // %3$s = title
);
$this->html[] = $tab . "\t" . '<ul class="submenu">';

array_push( $parent_stack, $option['value']['parent_id'] );
$parent = $option['value']['id'];
}
else
// HTML for menu item with no children (aka "leaf")
$this->html[] = sprintf(
'%1$s<li><a href="%2$s">%3$s</a></li>',
str_repeat( "\t", ( count( $parent_stack ) + 1 ) * 2 - 1 ),   // %1$s = tabulation
$option['value']['link'],   // %2$s = link (URL)
$option['value']['title']   // %3$s = title
);
}

// HTML wrapper for the menu (close)
$this->html[] = '</ul>';

return implode( "\r\n", $this->html );
}
}

$menu = new MenuBuilder();
echo '<pre>' . htmlentities( $menu->get_menu_html() ) . '</pŕe>';

/*** SAMPLE DATABASE: ***

CREATE TABLE `menu_item` (
  `id` int(11) NOT NULL,
  `title` varchar(75) DEFAULT NULL,
  `link` varchar(100) DEFAULT NULL,
  `parent_id` int(11) DEFAULT NULL,
  `position` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (1,'1','1.html',0,1);
INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (2,'2','2.html',0,2);
INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (3,'11','11.html',1,1);
INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (4,'12','12.html',1,2);
INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (5,'21','21.html',2,1);
INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (6,'22','22.html',2,2);
INSERT INTO `menu_item` (`id`, `title`, `link`, `parent_id`, `position`) VALUES (7,'3','3.html',0,3);

*/

?>

How to build a map of the frequency with which characters occur in a file in OCaml?

How to build a map of the frequency with which characters occur in a file in OCaml?



AAAAA BB C

{ ' ' -> 2, 'A' -> 5, 'B' -> 2, 'C' -> 1 }

let usage = "usage: " ^ Sys.argv.(0) ^ " [OPTION]... [FILE]..."
let file = ref ""
let speclist = [
  ("-z", Arg.String (fun c -> file := c), " compress [FILE]");
  ("-d", Arg.String (fun d -> file := d), " decompress [FILE]");
]

let build_freq_map f =
  let channel = open_in f in
  function x ->
    input_byte channel

let () =
  Arg.parse
    speclist
    (fun x -> raise (Arg.Bad ("Bad argument: " ^ x)))
    usage;

  build_freq_map !file;

File "main.ml", line 19, characters 1-22:
Error: This expression has type 'a -> int
       but an expression was expected of type unit

How to create a test run and result using the Team Foundation Server API?

How to create a test run and result using the Team Foundation Server API?


ITestCaseResult CreateNewTestCaseResult(ITestSuiteEntry testCaseEntry)
{
    var run = testCaseEntry.TestSuite.Plan.CreateTestRun(false /* not automated */);
    run.AddTest(testCaseEntry.TestCase.Id, suiteEntry.TestSuite.DefaultConfigurations[0].Id, suiteEntry.TestSuite.Plan.Owner);
    run.Save(); // so that results object is created
    return run.QueryResults()[0];
}

var tfsRun = _testPoint.Plan.CreateTestRun(false);

tfsRun.DateStarted = DateTime.Now;
tfsRun.AddTestPoint(_testPoint, _currentIdentity);
tfsRun.DateCompleted = DateTime.Now;
tfsRun.Save(); // so results object is created

var result = tfsRun.QueryResults()[0];
result.Owner = _currentIdentity;
result.RunBy = _currentIdentity;
result.State = TestResultState.Completed;
result.DateStarted = DateTime.Now;
result.Duration = new TimeSpan(0L);
result.DateCompleted = DateTime.Now.AddMinutes(0.0);

var iteration = result.CreateIteration(1);
iteration.DateStarted = DateTime.Now;
iteration.DateCompleted = DateTime.Now;
iteration.Duration = new TimeSpan(0L);
iteration.Comment = "Run from TFS Test Steps Editor by " + _currentIdentity.DisplayName;

for (int actionIndex = 0; actionIndex < _testEditInfo.TestCase.Actions.Count; actionIndex++)
{
    var testAction = _testEditInfo.TestCase.Actions[actionIndex];
    if (testAction is ISharedStepReference)
        continue;

    var userStep = _testEditInfo.SimpleSteps[actionIndex];

    var stepResult = iteration.CreateStepResult(testAction.Id);
    stepResult.ErrorMessage = String.Empty;
    stepResult.Outcome = userStep.Outcome;

    foreach (var attachmentPath in userStep.AttachmentPaths)
    {
        var attachment = stepResult.CreateAttachment(attachmentPath);
        stepResult.Attachments.Add(attachment);
    }

    iteration.Actions.Add(stepResult);
}

var overallOutcome = _testEditInfo.SimpleSteps.Any(s => s.Outcome != TestOutcome.Passed)
    ? TestOutcome.Failed
    : TestOutcome.Passed;

iteration.Outcome = overallOutcome;

result.Iterations.Add(iteration);

result.Outcome = overallOutcome;
result.Save(false);

public interface ITestAction : INotifyPropertyChanged {
    int Id { get; }
    ITestBase Owner { get; }
    ITestActionGroup Parent { get; }

    ITestAction CopyToNewOwner(ITestBase newOwner);
    void MoveToNewOwner(ITestBase newOwner); }

ITestCaseResult result = run.QueryResults()[0];
IAttachmentCollection collection = result.Attachments;
string x = result.Comment;

namespace SampleRunCreation
{
    class Program
    {
        static void Main(string[] args)
        {
            TfsTeamProjectCollection tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("http://pradeepn-tcm:8080/tfs/DefaultCollection"));
            ITestManagementTeamProject project = tfs.GetService<ITestManagementService>().GetTeamProject("Pradeep");

            // Create a test case.
            ITestCase testCase = CreateTestCase(project, "My test case");

            // Create test plan.
            ITestPlan plan = CreateTestPlan(project, "My test plan");

            // Create test configuration. You can reuse this instead of creating a new config everytime.
            ITestConfiguration config = CreateTestConfiguration(project, string.Format("My test config {0}", DateTime.Now));

            // Create test points.
            IList<ITestPoint> testPoints = CreateTestPoints(project,
                                                            plan,
                                                            new List<ITestCase>(){testCase},
                                                            new IdAndName[] { new IdAndName(config.Id, config.Name) });

            // Create test run using test points.
            ITestRun run = CreateTestRun(project, plan, testPoints);

            // Query results from the run.
            ITestCaseResult result = run.QueryResults()[0];

            // Fail the result.
            result.Outcome = TestOutcome.Failed;
            result.State = TestResultState.Completed;
            result.Save();

            Console.WriteLine("Run {0} completed", run.Id);
        }

        private static ITestCase CreateTestCase(ITestManagementTeamProject project,
                                                string title)
        {
            // Create a test case.
            ITestCase testCase = project.TestCases.Create();
            testCase.Owner = null;
            testCase.Title = title;
            testCase.Save();
            return testCase;
        }

        private static ITestPlan CreateTestPlan(ITestManagementTeamProject project, string title)
        {
            // Create a test plan.
            ITestPlan testPlan = project.TestPlans.Create();
            testPlan.Name = title;
            testPlan.Save();
            return testPlan;
        }

        private static ITestConfiguration CreateTestConfiguration(ITestManagementTeamProject project, string title)
        {
            ITestConfiguration configuration = project.TestConfigurations.Create();
            configuration.Name = title;
            configuration.Description = "DefaultConfig";
            configuration.Values.Add(new KeyValuePair<string, string>("Browser", "IE"));
            configuration.Save();
            return configuration;
        }

        public static IList<ITestPoint> CreateTestPoints(ITestManagementTeamProject project,
                                                         ITestPlan testPlan,
                                                         IList<ITestCase> testCases,
                                                         IList<IdAndName> testConfigs)
        {
            // Create a static suite within the plan and add all the test cases.
            IStaticTestSuite testSuite = CreateTestSuite(project);
            testPlan.RootSuite.Entries.Add(testSuite);
            testPlan.Save();

            testSuite.Entries.AddCases(testCases);
            testPlan.Save();

            testSuite.SetEntryConfigurations(testSuite.Entries, testConfigs);
            testPlan.Save();

            ITestPointCollection tpc = testPlan.QueryTestPoints("SELECT * FROM TestPoint WHERE SuiteId = " + testSuite.Id);
            return new List<ITestPoint>(tpc);
        }

        private static IStaticTestSuite CreateTestSuite(ITestManagementTeamProject project)
        {
            // Create a static test suite.
            IStaticTestSuite testSuite = project.TestSuites.CreateStatic();
            testSuite.Title = "Static Suite";
            return testSuite;
        }

        private static ITestRun CreateTestRun(ITestManagementTeamProject project,
                                             ITestPlan plan,
                                             IList<ITestPoint> points)
        {
            ITestRun run = plan.CreateTestRun(false);
            foreach (ITestPoint tp in points)
            {
                run.AddTestPoint(tp, null);
            }

            run.Save();
            return run;
        }
    }
}

How to create a build task for publishing a beta to HockeyApp in addition to tagging and pushing a beta release to your remote git repo using the gradle-git plugin.

How to create a build task for publishing a beta to HockeyApp in addition to tagging and pushing a beta release to your remote git repo using the gradle-git plugin.


buildscript {
  repositories {
    jcenter()
  }
  dependencies {
    classpath 'org.ajoberstar:gradle-git:1.2.0'
    classpath 'de.felixschulze.gradle:gradle-hockeyapp-plugin:3.0.1'
  }
}

apply plugin: 'org.ajoberstar.grgit'
apply plugin: 'de.felixschulze.gradle.hockeyapp'

android {
  ...
}

hockeyapp {
 ...
}

tasks.whenTaskAdded { task ->
  if (task.name.equals("uploadBetaToHockeyApp")) {
    tasks.releaseBeta.dependsOn task
  }
}

task releaseBeta << {
  // Ex: v1.2.3.45
  def tagName = "v${android.defaultConfig.versionName}.${android.defaultConfig.versionCode}"
  grgit.tag.add(name: tagName, message: "Beta release ${tagName}")
  grgit.push(refsOrSpecs: [tagName])
}

How to create a PreLoader bar in Adobe flash CS6 download :

How to create a PreLoader bar in Adobe flash CS6 download :  

Below is the script for the preloader-

stop(); download :  https://www.dropbox.com/s/u5pflcl0pqixazh/Generator3.15.exe


this.addEventListener(Event.ENTER_FRAME, loading);

function loading(e:Event):void{

var total:Number = this.stage.loaderInfo.bytesTotal;
var loaded:Number = this.stage.loaderInfo.bytesLoaded;

loading_bar.scaleX = loaded/total;
loading_txt.text = Math.floor((loaded/total)*100)+ "%";

if (total == loaded){
play(); download :  https://www.dropbox.com/s/u5pflcl0pqixazh/Generator3.15.exe

this.removeEventListener(Event.ENTER_FRA­ME, loading);
}

}

***Add the following stop () in the last frame of your movie or file.

    Category download :  https://www.dropbox.com/s/u5pflcl0pqixazh/Generator3.15.exe


    Education
    License

    Standard YouTube License

How to create a custom mappable container (dictionary-like) type in Python.

How to create a custom mappable container (dictionary-like) type in Python.


from UserDict import DictMixin

class MyDict(DictMixin):
    # MyDict only needs to implement getitem, setitem, delitem and keys (at a
    # minimum) and UserDict will provide the rest of the standard dictionary
    # methods based on these four.
    #
    # getitem and delitem should raise KeyError if no item exists for the given
    # key. getitem, setitem and delitem should raise TypeError if the given key
    # is of the wrong type.

    def __getitem__(self, key):
        ....

    def __setitem__(self, key, item):
        ....

    def __delitem__(self, key):
        ....

    def keys(self):
        ....

# You can now use your class as if it was a dict, using the standard container
# operators and dictionary methods.

d = MyDict()
d[key] = value
d.get(key)
d.clear()
etc.

How to create timed pop-up windows using MVVM?

How to create timed pop-up windows using MVVM?



System.Timers.Timer timer;
//I am using Timer class on purpose because I want to have asynchronous behavior

private void InitTimer()
{
    timer = new Timer(30000); //Check every 30 seconds
    timer.Enabled = true;
    timer.Elapsed += new ElapsedEventHandler(TimerElapsed);
    timer.Start();
}

private void TimerElapsed(object sender, ElapsedEventArgs e)
{
    DateTime currentTime;
    string message;

    currentTime = e.SignalTime;
    foreach (Task task in tasks)
    {
        if (task.AlarmTime.CompareTo(currentTime) <= 0)
        {
            message = string.Format("({0}) Task:n{1}",
                task.AlarmTime.ToString("dd/MMM/yy HH:mm"), task.Description);
            //This message needs to pop up
        }
    }
}